diff --git a/CMakeLists.txt b/CMakeLists.txt index c38285647..6aeeb3eac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -269,6 +269,7 @@ set(SOURCES "application/editormodevehicle.cpp" "application/editormodeselection.cpp" "application/editormodeviewport.cpp" +"application/editormodefields.cpp" "application/editormodeterrainchunks.cpp" "application/editormodesignal.cpp" "application/editormodecatenary.cpp" diff --git a/application/editormode.cpp b/application/editormode.cpp index 61f1405fc..21d0b037f 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -2003,6 +2003,9 @@ void editor_mode::render_terrain_ui() ImGui::TextDisabled("%s", STR_C("The holes follow the ground every metre (every grid point of finer chunks), whatever the drawn grid")); } + if (ImGui::CollapsingHeader(STR_C("Fields"), m_terrain_tool == terrain_tool::fields ? ImGuiTreeNodeFlags_DefaultOpen : 0)) + render_fields_ui(); + if (ImGui::CollapsingHeader(STR_C("Fill"), m_terrain_tool == terrain_tool::fill ? ImGuiTreeNodeFlags_DefaultOpen : 0)) { auto const &layers{m_streamer.manifest().layers}; @@ -2386,7 +2389,7 @@ void editor_mode::draw_terrain_overlay() outline.emplace_back(point.x, water[i].level, point.y); polyline(outline, static_cast(i) == m_water_selected ? IM_COL32(120, 200, 255, 255) : IM_COL32(60, 120, 220, 160), true, static_cast(i) == m_water_selected ? 2.5f : 1.5f); } - if (m_terrain_tool == terrain_tool::fill && false == m_paint_outline.empty()) + if ((m_terrain_tool == terrain_tool::fill || m_terrain_tool == terrain_tool::fields) && false == m_paint_outline.empty()) { // laid over the ground, the edges followed every few metres std::vector outline; @@ -2956,6 +2959,7 @@ void editor_mode::handle_terrain_click(bool const Shift) break; } case terrain_tool::fill: + case terrain_tool::fields: { if (Shift) { diff --git a/application/editormode.h b/application/editormode.h index 38d51286e..71cd5a394 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -550,7 +550,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri restore, // takes the touch-ups over the modifiers back fill, // outlines an area filled with a material holes, // cuts holes in the ground (portals of tunnels), Shift: closes them - grass // grows the chosen kind of grass, Shift: takes the grass away + grass, // grows the chosen kind of grass, Shift: takes the grass away + fields // outlines a field: a surface cut out of the terrain with a material of its own, the ground under it made wavy }; terrain_tool m_terrain_tool{terrain_tool::none}; bool terrain_brush() const @@ -569,9 +570,64 @@ class editor_mode : public application_mode, private editor_track::observer, pri void remove_selected_chunks(); // takes the height of whatever is under the cursor (terrain, track, model) for the target of the level brush. returns: false if there's nothing bool pick_terrain_target(); - bool terrain_clicking() const { return m_terrain_tool == terrain_tool::chunks || m_terrain_tool == terrain_tool::spacing || m_terrain_tool == terrain_tool::water || m_terrain_tool == terrain_tool::fill; } + bool terrain_clicking() const + { + return m_terrain_tool == terrain_tool::chunks || m_terrain_tool == terrain_tool::spacing || m_terrain_tool == terrain_tool::water || m_terrain_tool == terrain_tool::fill || + m_terrain_tool == terrain_tool::fields; + } // fills the outlined area with the material of the chosen palette entry, turned by m_paint_rotation void fill_terrain_area(); + + // the fields (editormodefields.cpp): surfaces cut out of the terrain within the outline of the Fill tool, each with a material + // of its own, kept in a list to be changed later; painted into the paint of the chunks, or as a mesh of its own over a hole + // (out of the 8 materials a chunk holds, its seam showing); the ground under them made wavy; the slopes of the formation + // modifiers made natural + struct field_settings + { + float feather{1.0f}; // metres the field blends into the ground around over + float noise{0.3f}; // metres its edge wanders in and out by + float noise_scale{4.0f}; // about how long the waves of the edge are + int grass{-1}; // the 3D grass under it: -2 left, -1 taken away, 0 or more: that kind grown + bool separate{false}; // a mesh of its own over a hole instead of the paint of the chunks + bool everywhere{false}; // where the slopes are made natural: the whole scenery, or around the camera + float radius{1500.0f}; + }; + field_settings m_field; + // the ground under a field made wavy: rolling hills, furrows of a field, bumps, long waves, a hollow or a mound + struct terrain_waves + { + enum kind { hills, furrows, bumps, waves, hollow, grid, strips, count }; + // the profile of a wave: rounded as a sine, sharp ridges, sharp valleys, terraces, flat tops; how sharp it goes + enum profile { smooth, ridges, valleys, terraces, plateaus, profiles }; + bool on{false}; + int kind{hills}; + float height{0.4f}; // metres, from the lowest to the highest point of a wave; negative for the hollow, upside down + float length{25.0f}; // metres, of a wave + float angle{0.0f}; // degrees the furrows and the waves run at, counterclockwise from x + float edge{6.0f}; // metres inside the outline over which the waves fade in from nothing + float variation{0.35f}; // 0..1, how much the waves differ from one another + int shape{smooth}; + float sharpness{0.5f}; // 0..1: 0 the profile still rounded, 1 its corners and edges as sharp as it gets + int steps{4}; // of the terraces, from the bottom of a wave to its top + float roughness{0.0f}; // 0..1, small bumps over the whole surface, as clods of a field + }; + terrain_waves m_waves; + heightmap::modifier::natural_shape m_natural{0.8, 15.0, 0.15, 0.3, 0.08}; + int m_patch_selected{-1}; // field chosen in the list + void render_fields_ui(); + void cut_out_field(); + void render_waves_options(); + // the ground within Outline made wavy as m_waves says; returns true if it changed + bool apply_waves(std::vector const &Outline); + // a combo of what's done with the grass; true if changed + bool grass_choice(char const *Label, int &Choice); + // a field painted into the chunks, with its grass + bool paint_patch(heightmap::surface_patch const &Patch); + // the list of the fields set to All, the ones of Changed painted again with the ones over them they touch, the ground under the + // ones of Cleared given back the first material of the palette + void repaint_patches(std::vector All, std::vector const &Changed, std::vector const &Cleared = {}); + void render_patches_list(); + void naturalise_slopes(bool Natural); // the brush, the hovered chunk and the outlines of water drawn over the viewport void draw_terrain_overlay(); // forgets what's known about the ground, after the terrain changed diff --git a/application/editormodefields.cpp b/application/editormodefields.cpp new file mode 100644 index 000000000..ed53ae9f8 --- /dev/null +++ b/application/editormodefields.cpp @@ -0,0 +1,904 @@ +/* +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/. +*/ + +// the Fields of the Terrain field of work: surfaces cut out of the terrain within an outline, each with a material of its own and +// kept in a list to be changed later, painted into the chunks or drawn as a mesh of their own over a hole; the ground under them +// made wavy (furrows, strips of fields, hills); the slopes of the formation modifiers made natural + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +// the order the painted surfaces go on in: the slopes, then the track bed over them, then the ones drawn by hand over both +int paint_priority(heightmap::surface_patch const &Patch) +{ + if (Patch.name.find(" km ") != std::string::npos) + { + if (Patch.name.find(" torowisko ") != std::string::npos) + return 1; + if (Patch.name.find(" nasyp ") != std::string::npos || Patch.name.find(" przekop ") != std::string::npos) + return 0; + } + return 2; +} + +void reach_of(heightmap::surface_patch const &Patch, glm::dvec2 &Low, glm::dvec2 &High) +{ + Patch.bounds(Low, High); + auto const margin{Patch.paint ? Patch.feather * 0.5 + Patch.noise + 1.0 : 1.0}; + Low -= glm::dvec2{margin}; + High += glm::dvec2{margin}; +} +} // namespace + +namespace +{ +// value noise of the waves, 0..1, smooth, the same for the same place: the waves of the ground don't change as it's cut again +double wave_hash(std::int64_t const X, std::int64_t const Z) +{ + auto h{static_cast(X) * 0x9E3779B97F4A7C15ull ^ static_cast(Z) * 0xC2B2AE3D27D4EB4Full}; + h ^= h >> 31; + h *= 0xBF58476D1CE4E5B9ull; + h ^= h >> 29; + return static_cast(h & 0xffffff) / static_cast(0xffffff); +} + +double wave_noise(double const X, double const Z) +{ + auto const ix{static_cast(std::floor(X))}; + auto const iz{static_cast(std::floor(Z))}; + auto const fx{X - std::floor(X)}; + auto const fz{Z - std::floor(Z)}; + auto const sx{fx * fx * (3.0 - 2.0 * fx)}; + auto const sz{fz * fz * (3.0 - 2.0 * fz)}; + auto const a{wave_hash(ix, iz) + (wave_hash(ix + 1, iz) - wave_hash(ix, iz)) * sx}; + auto const b{wave_hash(ix, iz + 1) + (wave_hash(ix + 1, iz + 1) - wave_hash(ix, iz + 1)) * sx}; + return a + (b - a) * sz; +} + +// a few octaves of it, 0..1 +double wave_fractal(double const X, double const Z, int const Octaves) +{ + double sum{0.0}; + double weight{1.0}; + double total{0.0}; + double scale{1.0}; + for (int i = 0; i < Octaves; ++i) + { + sum += wave_noise(X * scale + i * 17.3, Z * scale - i * 9.1) * weight; + total += weight; + weight *= 0.5; + scale *= 2.0; + } + return sum / total; +} +} // namespace + +void editor_mode::render_fields_ui() +{ + auto &settings{m_field}; + auto const &layers{m_streamer.manifest().layers}; + ImGui::TextWrapped("%s", STR_C("LMB adds a point of the outline, Shift+LMB takes the last one back. The field gets the material chosen in the palette and is " + "kept in the list below, where its material can be changed later")); + if (false == layers.empty()) + { + auto const &chosen{layers[std::clamp(m_terrain_layer, 0, static_cast(layers.size()) - 1)]}; + ImGui::Text(STR_C("Material: %s (chosen in the palette above)"), chosen.material.c_str()); + } + ImGui::Text(STR_C("Outline: %zu points"), m_paint_outline.size()); + int kind{settings.separate ? 1 : 0}; + ImGui::RadioButton(STR_C("Painted into the terrain##fields"), &kind, 0); + item_tooltip("The material goes into the paint of the chunks: no seam, the edge blends into the ground around; a chunk holds up to 8 materials"); + ImGui::SameLine(); + ImGui::RadioButton(STR_C("A surface of its own##fields"), &kind, 1); + item_tooltip("The ground is cut away within the outline and the field drawn over the hole as a mesh of its own, following the heights of the terrain:\n" + "it doesn't take one of the 8 materials of a chunk, but its edge is sharp and the seam can show"); + settings.separate = kind == 1; + ImGui::SeparatorText(STR_C("Edge")); + if (false == settings.separate) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Transition (m)##fields"), &settings.feather, 0.05f, 0.0f, 20.0f, settings.feather > 0.0f ? "%.2f" : STR_C("sharp")); + settings.feather = std::max(0.0f, settings.feather); + item_tooltip("Metres across the edge the material passes into the one around over, half of them inside the field.\n" + "The paint of the terrain is kept every metre (every 0.5 m in the chunks converted to 0.5 m), narrower comes out in steps"); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Noise of the edge (m)##fields"), &settings.noise, 0.05f, 0.0f, 10.0f, settings.noise > 0.0f ? "%.2f" : STR_C("none")); + settings.noise = std::max(0.0f, settings.noise); + item_tooltip("How far the edge wanders in and out of the outline, so it isn't drawn with a ruler"); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Waves of the noise (m)##fields"), &settings.noise_scale, 0.1f, 0.5f, 50.0f, "%.1f"); + settings.noise_scale = std::max(0.5f, settings.noise_scale); + item_tooltip("About how long the waves of the edge are: small - frayed, large - gently wavy"); + grass_choice(STR_C("3D grass under it##fields"), settings.grass); + } + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat(STR_C("Texture turned by (deg)##fields"), &m_paint_rotation, -180.0f, 180.0f, "%.0f"); + render_waves_options(); + ImGui::Spacing(); + ImGui::BeginDisabled(m_paint_outline.size() < 3 || layers.empty()); + if (main_button(STR_C("Cut out the field"), ImVec2(-FLT_MIN, tall_button_height()))) + cut_out_field(); + ImGui::EndDisabled(); + if (ImGui::Button(STR_C("Clear the outline##fields"), ImVec2(-FLT_MIN, 0.0f))) + m_paint_outline.clear(); + render_patches_list(); + + ImGui::SeparatorText(STR_C("Natural slopes")); + auto &natural{m_natural}; + ImGui::TextWrapped("%s", STR_C("The embankments and the cuttings of the formation modifiers not drawn with a ruler: the formation and the edges of the track bed " + "stay as designed, the slopes and their foot wander, get gentler here and there and meet the ground softly")); + auto drag = [](char const *Label, double &Value, float Speed, float Low, float High, char const *Format, char const *Tip) { + float value{static_cast(Value)}; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::DragFloat(Label, &value, Speed, Low, High, Format)) + Value = std::clamp(static_cast(value), static_cast(Low), static_cast(High)); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", Tip); + }; + drag(STR_C("Foot wanders by (m)"), natural.wander, 0.05f, 0.0f, 5.0f, "%.2f", STR_C("How far the foot of the slope goes in and out of the line of the slope")); + drag(STR_C("Waves along the line (m)"), natural.scale, 0.5f, 2.0f, 100.0f, "%.0f", STR_C("About how long the waves of the foot are along the line")); + drag(STR_C("Gentler by up to"), natural.gentler, 0.01f, 0.0f, 0.6f, "%.2f", STR_C("0.2: the slope 1:1.5 gets as gentle as 1:1.8 here and there, never steeper than designed")); + drag(STR_C("Soft foot (m/m)"), natural.soften, 0.01f, 0.0f, 2.0f, "%.2f", STR_C("Metres the foot is rounded off over, for a metre of the height of the slope: high embankments meet the ground softer")); + drag(STR_C("Bumps on the face (m)"), natural.roughness, 0.01f, 0.0f, 0.5f, "%.2f", STR_C("Metres the face of the slope is uneven by, as earth settled for years")); + int scope{settings.everywhere ? 1 : 0}; + ImGui::RadioButton(STR_C("Around the camera##natural"), &scope, 0); + ImGui::SameLine(); + ImGui::RadioButton(STR_C("The whole scenery##natural"), &scope, 1); + settings.everywhere = scope == 1; + if (false == settings.everywhere) + { + ImGui::SameLine(); + ImGui::SetNextItemWidth(90.0f); + ImGui::DragFloat(STR_C("m##natural"), &settings.radius, 10.0f, 100.0f, 20000.0f, "%.0f"); + } + ImGui::BeginDisabled(m_streamer.modifiers().empty()); + if (main_button(STR_C("Make the slopes natural"), ImVec2(-FLT_MIN, tall_button_height()))) + naturalise_slopes(true); + item_tooltip("The terrain under the modifiers is shaped anew; Ctrl+Z takes it back"); + if (ImGui::Button(STR_C("Back to the slopes as designed"), ImVec2(-FLT_MIN, 0.0f))) + naturalise_slopes(false); + ImGui::EndDisabled(); +} + + +void editor_mode::cut_out_field() +{ + auto const &layers{m_streamer.manifest().layers}; + if (m_paint_outline.size() < 3 || layers.empty()) + return; + auto const &settings{m_field}; + auto const &chosen{layers[std::clamp(m_terrain_layer, 0, static_cast(layers.size()) - 1)]}; + heightmap::surface_patch patch; + patch.material = chosen.material; + patch.size = chosen.size; + patch.rotation = static_cast(std::remainder(static_cast(chosen.rotation + m_paint_rotation), 360.0)); + patch.follow = true; + patch.paint = false == settings.separate; + patch.feather = settings.feather; + patch.noise = settings.noise; + patch.noise_scale = settings.noise_scale; + patch.grass = settings.grass; + for (auto const &point : m_paint_outline) + patch.outline.emplace_back(point.x, point.z); + auto patches{m_streamer.patches()}; + // a name not taken yet + for (int number = static_cast(patches.size()) + 1;; ++number) + { + patch.name = format(STR_C("field %d"), number); + if (std::none_of(patches.begin(), patches.end(), [&](heightmap::surface_patch const &Other) { return Other.name == patch.name; })) + break; + } + auto const name{patch.name}; + auto const separate{false == patch.paint}; + // the waves of the ground and the field are one step of the undo + terrain_history_step(); + if (m_waves.on && apply_waves(patch.outline)) + forget_ground(); + auto const outline{patch.outline}; + patches.push_back(std::move(patch)); + auto const index{patches.size() - 1}; + if (separate) + { + // the ground cut away under it, the field drawn over the hole with the heights the terrain has there + m_streamer.cut(outline, true); + m_streamer.patches(std::move(patches)); + forget_ground(); + } + else + repaint_patches(std::move(patches), {index}); + terrain_history_step(); + m_patch_selected = static_cast(index); + m_paint_outline.clear(); + m_terrain_status = format(STR_C("Cut out as %s with %s, Ctrl+Z puts it back"), name.c_str(), chosen.material.c_str()); +} + + +void editor_mode::render_waves_options() +{ + auto &waves{m_waves}; + ImGui::SeparatorText(STR_C("Waves of the ground")); + ImGui::Checkbox(STR_C("Make the ground under the surface wavy"), &waves.on); + item_tooltip("The heights of the terrain within the outline get the waves chosen below, fading in from the edge: a field ploughed into furrows, a meadow of gentle hills, a hollow. Ctrl+Z takes them back with the surface"); + if (false == waves.on) + return; + char const *const kinds[]{STR_C("Rolling hills"), STR_C("Furrows of a field"), STR_C("Bumps and molehills"), STR_C("Long waves"), STR_C("A hollow or a mound"), + STR_C("A grid of hummocks"), STR_C("Strips of fields")}; + char const *const tips[]{STR_C("Gentle hills of all sizes, as a meadow or a pasture has them"), STR_C("Ridges and furrows side by side, along the angle below, as a ploughed field or the beds of a garden"), + STR_C("Small mounds scattered about, as molehills or tussocks"), STR_C("Long even waves across the angle below, as a field rolling over a hill or dunes"), + STR_C("The middle lowered (a negative height raises it): a hollow by a pond, a dip in a field, or a mound"), + STR_C("Waves along the angle and across it at once: hummocks in rows, as a drained meadow or an orchard on ridges"), + STR_C("Long strips along the angle, each a little higher or lower than the next, with banks between them: the fields of a village cut up between farms")}; + ImGui::SetNextItemWidth(180.0f); + if (ImGui::BeginCombo(STR_C("Kind##waves"), kinds[std::clamp(waves.kind, 0, static_cast(terrain_waves::count) - 1)])) + { + for (int i = 0; i < terrain_waves::count; ++i) + { + if (ImGui::Selectable(kinds[i], i == waves.kind)) + { + waves.kind = i; + // the sizes a kind usually has + static float const heights[]{0.6f, 0.25f, 0.2f, 1.0f, -0.8f, 0.3f, 0.6f}; + static float const lengths[]{40.0f, 1.5f, 3.0f, 60.0f, 0.0f, 6.0f, 25.0f}; + waves.height = heights[i]; + if (lengths[i] > 0.0f) + waves.length = lengths[i]; + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", tips[i]); + } + ImGui::EndCombo(); + } + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Height (m)##waves"), &waves.height, 0.01f, -5.0f, 5.0f, "%.2f"); + item_tooltip("From the bottom of a wave to its top; for the hollow how deep its middle goes, negative: a mound"); + if (waves.kind != terrain_waves::hollow) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Length of a wave (m)##waves"), &waves.length, 0.1f, 0.5f, 300.0f, "%.1f"); + waves.length = std::clamp(waves.length, 0.5f, 300.0f); + item_tooltip("From one top to the next: furrows 0.7-2 m, the beds of a garden 1.5-3 m, hills 20-100 m"); + } + if (waves.kind == terrain_waves::furrows || waves.kind == terrain_waves::waves || waves.kind == terrain_waves::grid || waves.kind == terrain_waves::strips) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat(STR_C("Direction (deg)##waves"), &waves.angle, -180.0f, 180.0f, "%.0f"); + item_tooltip("Which way the furrows or the ridges of the waves run, counterclockwise from the x axis of the scenery; the texture turned by the same angle lies along them"); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("as the texture"))) + waves.angle = m_paint_rotation; + } + if (waves.kind != terrain_waves::hollow) + { + char const *const shapes[]{STR_C("Rounded"), STR_C("Sharp ridges"), STR_C("Sharp valleys"), STR_C("Terraces"), STR_C("Flat tops")}; + char const *const shape_tips[]{STR_C("Every wave a gentle curve, as before"), STR_C("Tops pointed, sides straight: ploughed ridges, a dune crest, a bank between fields"), + STR_C("Bottoms pointed: drainage ditches, gullies cut by water, the furrow left by a plough"), + STR_C("The slopes broken into flat steps: terraced fields on a hillside, a quarry, the shelves of a vineyard"), + STR_C("Tops and bottoms cut flat with steep sides between: beds of a garden, fields on raised strips, plateaus")}; + ImGui::SetNextItemWidth(180.0f); + if (ImGui::BeginCombo(STR_C("Profile##waves"), shapes[std::clamp(waves.shape, 0, static_cast(terrain_waves::profiles) - 1)])) + { + for (int i = 0; i < terrain_waves::profiles; ++i) + { + if (ImGui::Selectable(shapes[i], i == waves.shape)) + waves.shape = i; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", shape_tips[i]); + } + ImGui::EndCombo(); + } + item_tooltip("The cross-section of a wave; the rounded one makes the fields look soft, the others give them edges"); + if (waves.shape != terrain_waves::smooth) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat(STR_C("Sharpness##waves"), &waves.sharpness, 0.0f, 1.0f, "%.2f"); + item_tooltip("0: the profile barely changed from the rounded one; 1: its edges and corners as sharp as they get"); + } + if (waves.shape == terrain_waves::terraces) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderInt(STR_C("Steps##waves"), &waves.steps, 2, 12); + item_tooltip("How many flat steps a slope is broken into, from the bottom of a wave to its top"); + } + } + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat(STR_C("Roughness##waves"), &waves.roughness, 0.0f, 1.0f, "%.2f"); + item_tooltip("Clods and hummocks of about 3 m over the whole surface, up to 20 cm high: a ploughed field, a trodden pasture.\n" + "The terrain under the surface gets a point every metre for them (and for waves shorter than 15 m), the files grow"); + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat(STR_C("Differences between them##waves"), &waves.variation, 0.0f, 1.0f, "%.2f"); + item_tooltip("0: every wave alike, as drawn; 1: waves of quite different heights and places, as nature has them"); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Fading in from the edge (m)##waves"), &waves.edge, 0.1f, 0.0f, 100.0f, "%.1f"); + waves.edge = std::max(0.0f, waves.edge); + item_tooltip("Metres inside the outline over which the waves grow from nothing, so the ground around meets the surface without a step"); +} + +bool editor_mode::apply_waves(std::vector const &Outline) +{ + if (Outline.size() < 3 || (std::abs(m_waves.height) < 0.001f && m_waves.roughness < 0.001f)) + return false; + auto const waves{m_waves}; + glm::dvec2 low{std::numeric_limits::max()}, high{-std::numeric_limits::max()}; + for (auto const &point : Outline) + { + low = glm::min(low, point); + high = glm::max(high, point); + } + auto const centre{(low + high) * 0.5}; + auto const radians{glm::radians(static_cast(waves.angle))}; + glm::dvec2 const along{std::cos(radians), std::sin(radians)}; + glm::dvec2 const across{-along.y, along.x}; + auto const length{std::max(0.5, static_cast(waves.length))}; + auto const variation{std::clamp(static_cast(waves.variation), 0.0, 1.0)}; + auto const edge{std::max(0.0, static_cast(waves.edge))}; + // for the hollow: how far in the middle of it is, the most distance from the edge found in the outline + double deepest{edge}; + auto const inside_by = [&](glm::dvec2 const &Point, double &Distance) { + bool inside{false}; + auto nearest{std::numeric_limits::max()}; + for (std::size_t i = 0, j = Outline.size() - 1; i < Outline.size(); j = i++) + { + auto const &a{Outline[i]}; + auto const &b{Outline[j]}; + if ((a.y > Point.y) != (b.y > Point.y) && Point.x < (b.x - a.x) * (Point.y - a.y) / (b.y - a.y) + a.x) + inside = !inside; + auto const run{b - a}; + auto const run2{glm::dot(run, run)}; + auto const t{run2 > 1e-12 ? std::clamp(glm::dot(Point - a, run) / run2, 0.0, 1.0) : 0.0}; + nearest = std::min(nearest, glm::length(Point - (a + run * t))); + } + Distance = nearest; + return inside; + }; + if (waves.kind == terrain_waves::hollow) + { + // a coarse look for the middle, every few metres + auto const step{std::max(1.0, std::max(high.x - low.x, high.y - low.y) / 60.0)}; + for (double z = low.y; z <= high.y; z += step) + for (double x = low.x; x <= high.x; x += step) + if (double distance; inside_by({x, z}, distance)) + deepest = std::max(deepest, distance); + } + auto const shape = [&](glm::dvec2 const &Point) -> double { + auto const u{glm::dot(Point - centre, across)}; // across the furrows and the ridges + auto const v{glm::dot(Point - centre, along)}; + switch (waves.kind) + { + case terrain_waves::hills: + return wave_fractal(Point.x / length, Point.y / length, variation > 0.0 ? 3 : 1) * 2.0 - 1.0; + case terrain_waves::furrows: + { + // the furrows wander a little sideways and change their depth along the field + auto const wander{(wave_noise(v / (length * 12.0), u / (length * 40.0)) - 0.5) * length * variation}; + auto const depth{1.0 - variation * 0.5 * wave_noise(v / (length * 8.0) + 3.1, u / (length * 8.0))}; + return std::sin(glm::two_pi() * (u + wander) / length) * depth; + } + case terrain_waves::bumps: + { + auto const n{wave_fractal(Point.x / length, Point.y / length, 2)}; + auto const threshold{0.55 - 0.15 * variation}; + auto const t{std::clamp((n - threshold) / (1.0 - threshold), 0.0, 1.0)}; + return t * t * 2.0; // 0..2 of the half height: the ground between the bumps stays as it is + } + case terrain_waves::waves: + { + auto const shift{(wave_noise(v / (length * 3.0), 0.37) - 0.5) * length * variation}; + auto const size{1.0 - variation * 0.6 * wave_noise(u / (length * 2.0), v / (length * 2.0) + 5.7)}; + return std::sin(glm::two_pi() * (u + shift) / length) * size; + } + case terrain_waves::grid: + { + auto const shift{(wave_noise(u / (length * 4.0), v / (length * 4.0) + 1.3) - 0.5) * length * variation}; + auto const a{std::sin(glm::two_pi() * (u + shift) / length)}; + auto const b{std::sin(glm::two_pi() * (v - shift) / length)}; + return a * b; + } + case terrain_waves::strips: + { + // strips of about the length across, each of its own height, the banks between them as steep as the sharpness + auto const width{length * (1.0 + variation * 0.6 * (wave_noise(v / (length * 10.0), 2.9) - 0.5))}; + auto const place{u / width}; + auto const strip{std::floor(place)}; + auto const in{place - strip}; + auto const level = [&](double const S) { return wave_noise(S * 0.731 + 0.17, 4.4) * 2.0 - 1.0; }; + auto const bank{0.5 * (0.35 - 0.3 * static_cast(waves.sharpness))}; // share of the strip each side of the edge + auto const here{level(strip)}; + if (in < bank) + { + auto t{(in + bank) / (2.0 * bank)}; + t = t * t * (3.0 - 2.0 * t); + return level(strip - 1.0) + (here - level(strip - 1.0)) * t; + } + if (in > 1.0 - bank) + { + auto t{(in - (1.0 - bank)) / (2.0 * bank)}; + t = t * t * (3.0 - 2.0 * t); + return here + (level(strip + 1.0) - here) * t; + } + return here; + } + default: + return 0.0; + } + }; + // the cross-section of a wave: the value -1..1 of the shape bent to the profile chosen + auto const sharp{std::clamp(static_cast(waves.sharpness), 0.0, 1.0)}; + auto const steps{static_cast(std::clamp(waves.steps, 2, 12))}; + auto const profile = [&](double S) -> double { + S = std::clamp(S, -1.0, 1.0); + switch (waves.shape) + { + case terrain_waves::ridges: + case terrain_waves::valleys: + { + // the sine straightened into a triangle (straight sides, corners at the top and the bottom) as far as it's sharp, + // then the valleys widened under pointed ridges, or the other way round + auto const triangle{std::asin(S) * 2.0 / glm::pi()}; + auto const t{(S + (triangle - S) * sharp) * 0.5 + 0.5}; + auto const power{1.0 + 2.0 * sharp}; + auto const bent{waves.shape == terrain_waves::ridges ? std::pow(t, power) : 1.0 - std::pow(1.0 - t, power)}; + return bent * 2.0 - 1.0; + } + case terrain_waves::terraces: + { + auto const q{(S * 0.5 + 0.5) * steps}; + auto const step{std::floor(q)}; + auto const in{q - step}; + // the ramp between the flat steps narrows with the sharpness + auto const ramp{std::max(0.04, 1.0 - sharp * 0.92)}; + auto t{std::clamp((in - (1.0 - ramp)) / ramp, 0.0, 1.0)}; + t = t * t * (3.0 - 2.0 * t); + return std::clamp((step + t) / steps, 0.0, 1.0) * 2.0 - 1.0; + } + case terrain_waves::plateaus: + { + // cut flat above and below: the sides steeper the sharper + auto const gain{1.0 + sharp * 6.0}; + return std::tanh(S * gain) / std::tanh(gain); + } + default: + return S; + } + }; + auto const rough{std::clamp(static_cast(waves.roughness), 0.0, 1.0)}; + auto const shaped = [&](glm::dvec2 const &Point) -> double { + double value; + if (waves.kind == terrain_waves::bumps) + value = profile(shape(Point) - 1.0) + 1.0; // the bumps stand on untouched ground: shaped from -1 up + else if (waves.kind == terrain_waves::strips) + value = shape(Point); // the strips have their own banks + else + value = profile(shape(Point)); + return value; + }; + auto const half{static_cast(waves.height) * 0.5}; + // a grid point every 5 m can't carry waves of 3 m or clods: the chunks under the surface made as fine as they have to be + // (the shortest wave three points, a clod of 3 m every metre), never coarser than they are + { + auto finest{5.0}; + if (waves.kind != terrain_waves::hollow && std::abs(waves.height) >= 0.001f) + finest = std::min(finest, length / 3.0); + if (rough > 0.0) + finest = std::min(finest, 1.0); + float target{heightmap::spacings.front()}; + for (auto const spacing : heightmap::spacings) + if (spacing <= finest + 1e-6) + target = spacing; + auto const first{heightmap::chunk_at(low.x, low.y)}, last{heightmap::chunk_at(high.x, high.y)}; + bool finer{false}; + for (int cx = std::min(first.first, last.first); cx <= std::max(first.first, last.first); ++cx) + for (int cz = std::min(first.second, last.second); cz <= std::max(first.second, last.second); ++cz) + { + auto const centre{heightmap::chunk_corner({cx, cz}) + glm::dvec2{heightmap::chunk_size * 0.5}}; + auto const *chunk{m_streamer.terrain_at(centre.x, centre.y)}; + if (chunk != nullptr && chunk->data().spacing() > target + 1e-3 && m_streamer.spacing(cx, cz, target)) + finer = true; + } + if (finer) + { + // as after Point spacing: the tiles of the ground made from the old grid + forget_ground_in(heightmap::chunk_corner(first), heightmap::chunk_corner(last) + glm::dvec2{heightmap::chunk_size}); + } + } + return m_streamer.reshape(low, high, [&](double const X, double const Z, float &Height) { + glm::dvec2 const point{X, Z}; + double distance; + if (false == inside_by(point, distance)) + return false; + auto fade{edge > 0.0 ? std::clamp(distance / edge, 0.0, 1.0) : 1.0}; + fade = fade * fade * (3.0 - 2.0 * fade); + double offset; + if (waves.kind == terrain_waves::hollow) + { + // lowered most in the middle, a smooth bowl to the edge, a little uneven + auto t{std::clamp(distance / std::max(deepest, 0.5), 0.0, 1.0)}; + t = t * t * (3.0 - 2.0 * t); + auto const uneven{1.0 + variation * 0.3 * (wave_noise(X / 10.0, Z / 10.0) * 2.0 - 1.0)}; + offset = -static_cast(waves.height) * t * uneven; + } + else + offset = shaped(point) * half * fade; + // clods and hummocks of about 3 m, up to 20 cm, whatever the waves (the grid made a point a metre for them) + if (rough > 0.0) + offset += (wave_fractal(X / 3.0 + 17.0, Z / 3.0 - 5.0, 3) * 2.0 - 1.0) * 0.2 * rough * fade; + if (std::abs(offset) < 1e-4) + return false; + Height += static_cast(offset); + return true; + }); +} + +bool editor_mode::paint_patch(heightmap::surface_patch const &Patch) +{ + auto const &layers{m_streamer.manifest().layers}; + if (Patch.outline.size() < 3 || layers.empty()) + return false; + // the material as the palette has it, turned and repeated as the surface wants it: another entry of the palette when it differs + std::uint16_t layer{0}; + if (false == Patch.material.empty()) + layer = m_streamer.layer(Patch.material, Patch.size, Patch.rotation); + auto const painted{m_streamer.fill(Patch.outline, Patch.feather, layer, 1.0, Patch.noise, Patch.noise_scale)}; + // the 3D grass: the texture alone wouldn't do, the blades would go on growing over the gravel + if (Patch.grass >= -1) + { + m_streamer.grass(Patch.outline, 0, true); + if (Patch.grass >= 0 && Patch.grass < static_cast(m_streamer.grass_kinds().size())) + m_streamer.grass(Patch.outline, static_cast(Patch.grass), false); + } + return painted; +} + +bool editor_mode::grass_choice(char const *Label, int &Choice) +{ + auto const &kinds{m_streamer.grass_kinds()}; + auto const name = [&](int const Value) -> std::string { + if (Value == -2) + return STR("left as it grows"); + if (Value == -1) + return STR("taken away"); + return Value < static_cast(kinds.size()) ? format(STR_C("grown: %s"), kinds[Value].name.c_str()) : std::string{"?"}; + }; + bool changed{false}; + ImGui::SetNextItemWidth(160.0f); + if (ImGui::BeginCombo(Label, name(Choice).c_str())) + { + for (int value = -2; value < static_cast(kinds.size()); ++value) + if (ImGui::Selectable(name(value).c_str(), value == Choice)) + { + Choice = value; + changed = true; + } + ImGui::EndCombo(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The 3D grass under the surface: left as it grows, taken away (gravel, a yard), or another kind of the grass palette grown there instead")); + return changed; +} + +void editor_mode::repaint_patches(std::vector All, std::vector const &Changed, std::vector const &Cleared) +{ + // the ones changed, and the painted ones over them they touch: the transitions between them made again + std::vector paint(All.size(), 0); + double constexpr cell{100.0}; + auto const key = [](double const X, double const Z) { + return (static_cast(std::floor(X / cell)) << 32) ^ (static_cast(std::floor(Z / cell)) & 0xffffffff); + }; + std::unordered_map> grid; + if (false == Changed.empty() || false == Cleared.empty()) + for (std::size_t i = 0; i < All.size(); ++i) + { + if (false == All[i].paint) + continue; + glm::dvec2 low, high; + reach_of(All[i], low, high); + for (auto z{std::floor(low.y / cell)}; z <= std::floor(high.y / cell); z += 1.0) + for (auto x{std::floor(low.x / cell)}; x <= std::floor(high.x / cell); x += 1.0) + grid[key(x * cell, z * cell)].push_back(i); + } + auto const touching = [&](glm::dvec2 const &Low, glm::dvec2 const &High, auto const &Take) { + for (auto z{std::floor(Low.y / cell)}; z <= std::floor(High.y / cell); z += 1.0) + for (auto x{std::floor(Low.x / cell)}; x <= std::floor(High.x / cell); x += 1.0) + { + auto const lookup{grid.find(key(x * cell, z * cell))}; + if (lookup == grid.end()) + continue; + for (auto const other : lookup->second) + { + glm::dvec2 low, high; + reach_of(All[other], low, high); + if (low.x <= High.x && high.x >= Low.x && low.y <= High.y && high.y >= Low.y) + Take(other); + } + } + }; + for (auto const index : Changed) + { + if (index >= All.size() || false == All[index].paint) + continue; + paint[index] = 1; + glm::dvec2 low, high; + reach_of(All[index], low, high); + auto const priority{paint_priority(All[index])}; + // over it: higher in the order, or the same and later in the list + touching(low, high, [&](std::size_t const Other) { + auto const other{paint_priority(All[Other])}; + if (other > priority || (other == priority && Other > index)) + paint[Other] = 1; + }); + } + for (auto const &gone : Cleared) + { + glm::dvec2 low, high; + reach_of(gone, low, high); + // what was under it shows again; all the painted ones it touched get their edges back + touching(low, high, [&](std::size_t const Other) { paint[Other] = 1; }); + } + std::vector order; + for (std::size_t i = 0; i < All.size(); ++i) + if (paint[i] != 0) + order.push_back(i); + std::stable_sort(order.begin(), order.end(), [&](std::size_t const A, std::size_t const B) { return paint_priority(All[A]) < paint_priority(All[B]); }); + m_streamer.patches(All); + for (auto const &gone : Cleared) + { + auto base{gone}; + base.material.clear(); // the first material of the palette, as the ground was + base.size = 0.f; + base.rotation = 0.f; + // the grass back as the terrain grows it most: the first kind of the palette, where it was taken away + base.grass = gone.grass == -2 ? -2 : (m_streamer.grass_kinds().empty() ? -1 : 0); + paint_patch(base); + } + std::size_t failed{0}; + for (auto const index : order) + if (false == paint_patch(All[index])) + ++failed; + if (failed > 0) + WriteLog(format("Editor: %zu surfaces painted nothing: no chunk under them, or no room for another material in a chunk (8 at most)", failed)); + forget_ground(); +} + +void editor_mode::render_patches_list() +{ + auto const &patches = m_streamer.patches(); + if (patches.empty()) + return; + ImGui::Text(STR_C("Fields: %zu"), patches.size()); + // a filter by name, for the many cut along the tracks (e.g. "nasyp", "L132 torowisko") + static char filter[96]{}; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::InputTextWithHint("##patchfilter", STR_C("Filter by name, words apart by spaces..."), filter, sizeof(filter)); + std::vector words; + { + std::istringstream split{std::string{filter}}; + std::string word; + while (split >> word) + { + std::transform(word.begin(), word.end(), word.begin(), [](unsigned char C) { return static_cast(std::tolower(C)); }); + words.push_back(word); + } + } + // filtered again only when the filter or the list changes: tens of thousands of names a frame cost a frame + static std::vector shown; + static std::string shown_filter; + static void const *shown_revision{nullptr}; + static std::size_t shown_count{0}; + if (shown_filter != filter || shown_revision != static_cast(patches.data()) || shown_count != patches.size()) + { + shown_filter = filter; + shown_revision = static_cast(patches.data()); + shown_count = patches.size(); + shown.clear(); + shown.reserve(patches.size()); + for (int i = 0; i < static_cast(patches.size()); ++i) + { + auto name{patches[i].name}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char C) { return static_cast(std::tolower(C)); }); + if (std::all_of(words.begin(), words.end(), [&](std::string const &Word) { return name.find(Word) != std::string::npos; })) + shown.push_back(i); + } + } + if (false == words.empty()) + { + ImGui::TextDisabled(STR_C("%zu shown"), shown.size()); + auto const &layers = m_streamer.manifest().layers; + ImGui::SameLine(); + ImGui::BeginDisabled(layers.empty() || shown.empty()); + if (ImGui::SmallButton(STR_C("Material of the palette to all shown"))) + { + auto const &chosen = layers[std::clamp(m_terrain_layer, 0, static_cast(layers.size()) - 1)]; + auto all{patches}; + std::vector changed; + for (auto const index : shown) + { + all[index].material = chosen.material; + all[index].size = chosen.size; + all[index].rotation = chosen.rotation; + changed.push_back(static_cast(index)); + } + repaint_patches(std::move(all), changed); + m_terrain_status = format(STR_C("%s given to %zu surfaces, Ctrl+Z takes it back"), chosen.material.c_str(), shown.size()); + ImGui::EndDisabled(); + return; + } + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip("%s", STR_C("The material chosen in the palette, with its repeat and rotation, to all the surfaces the filter shows")); + } + std::optional> dropped; + if (ImGui::BeginListBox("##patches", ImVec2(-FLT_MIN, std::min(8.0f, static_cast(shown.size()) + 0.5f) * ImGui::GetTextLineHeightWithSpacing()))) + { + ImGuiListClipper clipper; + clipper.Begin(static_cast(shown.size())); + while (clipper.Step()) + for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; ++row) + { + auto const i{static_cast(shown[row])}; + ImGui::PushID(static_cast(i)); + auto const material = patches[i].material.empty() ? std::string(STR_C("default material")) : patches[i].material; + if (ImGui::Selectable(format(STR_C("%s, %zu points, %s"), patches[i].name.c_str(), patches[i].outline.size(), material.c_str()).c_str(), static_cast(i) == m_patch_selected)) + m_patch_selected = static_cast(i); + // a texture dropped on an entry becomes the material of that surface + std::string name; + if (material_drop(name)) + dropped = std::make_pair(i, name); + ImGui::PopID(); + } + ImGui::EndListBox(); + } + if (dropped) + { + auto changed{patches}; + changed[dropped->first].material = dropped->second; + repaint_patches(std::move(changed), {dropped->first}); + m_patch_selected = static_cast(dropped->first); + return; + } + if (m_patch_selected < 0 || m_patch_selected >= static_cast(patches.size())) + return; + auto patch{patches[m_patch_selected]}; + bool changed{false}; + char buffer[256]; + std::snprintf(buffer, sizeof(buffer), "%s", patch.material.c_str()); + ImGui::SetNextItemWidth(220.0f); + if (ImGui::InputText(STR_C("Material##patch"), buffer, sizeof(buffer), ImGuiInputTextFlags_EnterReturnsTrue)) + patch.material = buffer, changed = true; + std::string name; + if (material_drop(name)) + patch.material = name, changed = true; + ImGui::SameLine(); + auto const &layers = m_streamer.manifest().layers; + ImGui::BeginDisabled(layers.empty()); + if (ImGui::Button(STR_C("From the palette##patch"))) + { + auto const &chosen = layers[std::clamp(m_terrain_layer, 0, static_cast(layers.size()) - 1)]; + patch.material = chosen.material; + patch.size = chosen.size; + patch.rotation = chosen.rotation; + changed = true; + } + ImGui::EndDisabled(); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Repeat (m)##patch"), &patch.size, 0.1f, 0.0f, 500.0f, patch.size > 0.0f ? "%.1f" : STR_C("of the material")); + changed |= ImGui::IsItemDeactivatedAfterEdit(); + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat(STR_C("Turned by (deg)##patch"), &patch.rotation, -180.0f, 180.0f, "%.0f"); + changed |= ImGui::IsItemDeactivatedAfterEdit(); + if (patch.paint) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Transition (m)##patch"), &patch.feather, 0.05f, 0.0f, 20.0f, patch.feather > 0.0f ? "%.2f" : STR_C("sharp")); + changed |= ImGui::IsItemDeactivatedAfterEdit(); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Noise of the edge (m)##patch"), &patch.noise, 0.05f, 0.0f, 10.0f, patch.noise > 0.0f ? "%.2f" : STR_C("none")); + changed |= ImGui::IsItemDeactivatedAfterEdit(); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Waves of the noise (m)##patch"), &patch.noise_scale, 0.1f, 0.5f, 50.0f, "%.1f"); + changed |= ImGui::IsItemDeactivatedAfterEdit(); + changed |= grass_choice(STR_C("3D grass under it##patch"), patch.grass); + } + else + { + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Lift (m)##patch"), &patch.lift, 0.01f, -5.0f, 5.0f, "%.2f"); + changed |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Metres the surface lies over the heights taken from the terrain")); + } + if (changed) + { + patch.size = std::max(0.0f, patch.size); + patch.feather = std::max(0.0f, patch.feather); + patch.noise = std::max(0.0f, patch.noise); + patch.noise_scale = std::max(0.5f, patch.noise_scale); + auto all{patches}; + all[m_patch_selected] = std::move(patch); + repaint_patches(std::move(all), {static_cast(m_patch_selected)}); + return; + } + if (ImGui::Button(STR_C("Outline it again##patch"))) + { + m_paint_outline.clear(); + for (auto const &point : patch.outline) + { + double height{0.0}; + patch.height(point.x, point.y, height); + m_paint_outline.emplace_back(point.x, height, point.y); + } + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Puts the outline of the field back as the outline being drawn")); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Give back to the terrain##patch"))) + { + auto const gone = patch; + auto all{patches}; + all.erase(all.begin() + m_patch_selected); + m_patch_selected = -1; + if (gone.paint) + { + // the first material of the palette over it again, the ones around get their edges back + repaint_patches(std::move(all), {}, {gone}); + m_terrain_status = STR_C("Surface removed, the ground under it has the first material of the palette again"); + return; + } + m_streamer.cut(gone.outline, false); + m_streamer.patches(std::move(all)); + forget_ground(); + m_terrain_status = STR_C("Surface removed, the hole under it closed"); + } +} + +void editor_mode::naturalise_slopes(bool const Natural) +{ + auto const &settings{m_field}; + glm::dvec2 const camera{Camera.Pos.x, Camera.Pos.z}; + std::vector changed; + for (auto const &modifier : m_streamer.modifiers()) + { + if (modifier.points.size() < 2) + continue; + if (false == settings.everywhere) + { + auto const [low, high]{modifier.bounds()}; + if (glm::distance(glm::clamp(camera, low, high), camera) > settings.radius) + continue; + } + auto copy{modifier}; + copy.natural = Natural ? m_natural : heightmap::modifier::natural_shape{}; + changed.push_back(std::move(copy)); + } + if (changed.empty()) + { + m_terrain_status = STR_C("No formation modifier there"); + return; + } + auto const count{changed.size()}; + m_streamer.modifiers(std::move(changed)); + forget_ground(); + m_terrain_status = format(Natural ? STR_C("The slopes of %zu modifiers made natural, the terrain shaped anew. Ctrl+Z takes it back") + : STR_C("The slopes of %zu modifiers as designed again. Ctrl+Z takes it back"), + count); + WriteLog("Editor: " + m_terrain_status); +} diff --git a/application/editormodeviewport.cpp b/application/editormodeviewport.cpp index 4097eceee..5a1f94440 100644 --- a/application/editormodeviewport.cpp +++ b/application/editormodeviewport.cpp @@ -245,6 +245,10 @@ void editor_mode::work_area_tools(std::vector &Buttons) Buttons.push_back({icon::area_fill, STR_C("Water"), nullptr, STR_C("LMB adds a point of the outline of a body of water, Shift+LMB takes the last one back"), chosen(terrain_tool::water), choose(terrain_tool::water)}); Buttons.push_back({icon::count, STR_C("Fill"), nullptr, STR_C("LMB adds a point of the outline of an area to fill with a material, Shift+LMB takes the last one back"), chosen(terrain_tool::fill), choose(terrain_tool::fill)}); + Buttons.push_back({icon::grass, STR_C("Fields"), nullptr, + STR_C("LMB adds a point of the outline of a field: a surface cut out of the terrain with a material of its own, the ground under it made wavy if wanted; " + "Shift+LMB takes the last one back"), + chosen(terrain_tool::fields), choose(terrain_tool::fields)}); Buttons.push_back({icon::hole, STR_C("Holes"), nullptr, STR_C("LMB cuts a hole in the terrain under the brush (portals of tunnels), Shift+LMB closes it"), chosen(terrain_tool::holes), choose(terrain_tool::holes)}); auto const orthophoto{m_orthophoto.enabled()}; diff --git a/editor/editorTerrainStreamer.cpp b/editor/editorTerrainStreamer.cpp index f13fc9a9c..cad7e76ae 100644 --- a/editor/editorTerrainStreamer.cpp +++ b/editor/editorTerrainStreamer.cpp @@ -615,8 +615,19 @@ void terrain_streamer::update(glm::dvec3 const &Camera) ahead *= look_ahead_limit / glm::length(ahead); auto const target{Camera + ahead}; + // the pieces cut out near the camera: made anew as it moves on, and for the ones waiting for their ground, now and then + if (false == m_manifest.patches.empty() && false == m_waterchanged) + { + auto const moved{glm::distance(glm::dvec2{Camera.x, Camera.z}, m_patchcentre)}; + if (moved > patch_move || (m_patchpending && m_patchloaded && now - m_patchtried > 1.0)) + m_waterchanged = true; + } if (m_waterchanged) + { + m_patchtried = now; + m_patchloaded = false; build_water(); + } // finished work, within a few milliseconds while (steady_seconds() - now < upload_budget) @@ -630,6 +641,7 @@ void terrain_streamer::update(glm::dvec3 const &Camera) m_results.pop_front(); } process(done); + m_patchloaded = true; m_settled = false; } @@ -1413,11 +1425,47 @@ bool terrain_streamer::paint(double X, double Z, double Radius, double Strength, }); } +namespace +{ +// smooth noise of -1..1 in waves of about Scale metres, the same at the same place every time +double edge_noise(double const X, double const Z, double const Scale) +{ + auto const hash = [](std::int64_t const Ix, std::int64_t const Iz) { + auto h{static_cast(Ix) * 0x9E3779B97F4A7C15ull ^ static_cast(Iz) * 0xC2B2AE3D27D4EB4Full}; + h ^= h >> 31; + h *= 0xBF58476D1CE4E5B9ull; + h ^= h >> 29; + return static_cast(h & 0xffffff) / static_cast(0xffffff) * 2.0 - 1.0; + }; + auto const octave = [&](double const U, double const V) { + auto const iu{std::floor(U)}; + auto const iv{std::floor(V)}; + auto const fu{U - iu}; + auto const fv{V - iv}; + auto const su{fu * fu * (3.0 - 2.0 * fu)}; + auto const sv{fv * fv * (3.0 - 2.0 * fv)}; + auto const x{static_cast(iu)}; + auto const z{static_cast(iv)}; + auto const a{hash(x, z) + (hash(x + 1, z) - hash(x, z)) * su}; + auto const b{hash(x, z + 1) + (hash(x + 1, z + 1) - hash(x, z + 1)) * su}; + return a + (b - a) * sv; + }; + auto const scale{std::max(0.5, Scale)}; + return std::clamp(0.7 * octave(X / scale, Z / scale) + 0.3 * octave(X / scale * 2.7 + 17.3, Z / scale * 2.7 - 9.1), -1.0, 1.0); +} +} // namespace + bool terrain_streamer::fill(std::vector const &Outline, double Feather, std::uint16_t Layer, double Strength) +{ + return fill(Outline, Feather, Layer, Strength, 0.0, 4.0); +} + +bool terrain_streamer::fill(std::vector const &Outline, double Feather, std::uint16_t Layer, double Strength, double Noise, double NoiseScale) { if (Outline.size() < 3 || Strength <= 0.0) return false; Feather = std::max(0.0, Feather); + Noise = std::max(0.0, Noise); glm::dvec2 low{std::numeric_limits::max()}, high{-std::numeric_limits::max()}; for (auto const &point : Outline) { @@ -1426,7 +1474,8 @@ bool terrain_streamer::fill(std::vector const &Outline, double Feath } // the blend runs across the outline, half of it inside auto const margin{Feather * 0.5}; - return paint_area(low - glm::dvec2{margin}, high + glm::dvec2{margin}, Layer, true, [&](double const Px, double const Pz) { + auto const reach{margin + Noise}; + return paint_area(low - glm::dvec2{reach}, high + glm::dvec2{reach}, Layer, true, [&](double const Px, double const Pz) { glm::dvec2 const point{Px, Pz}; bool inside{false}; auto nearest{std::numeric_limits::max()}; @@ -1436,7 +1485,7 @@ bool terrain_streamer::fill(std::vector const &Outline, double Feath auto const &b{Outline[j]}; if ((a.y > Pz) != (b.y > Pz) && Px < (b.x - a.x) * (Pz - a.y) / (b.y - a.y) + a.x) inside = !inside; - if (Feather > 0.0) + if (Feather > 0.0 || Noise > 0.0) { auto const run{b - a}; auto const length{glm::dot(run, run)}; @@ -1444,10 +1493,15 @@ bool terrain_streamer::fill(std::vector const &Outline, double Feath nearest = std::min(nearest, glm::length(point - (a + run * t))); } } - if (Feather <= 0.0) + if (Feather <= 0.0 && Noise <= 0.0) return inside ? Strength : 0.0; - // signed distance from the outline, inside positive, led smoothly through the blend - auto const t{std::clamp(((inside ? nearest : -nearest) + margin) / Feather, 0.0, 1.0)}; + // signed distance from the outline, inside positive, the edge shifted by the noise, led smoothly through the blend + auto distance{inside ? nearest : -nearest}; + if (Noise > 0.0) + distance += Noise * edge_noise(Px, Pz, NoiseScale); + if (Feather <= 0.0) + return distance > 0.0 ? Strength : 0.0; + auto const t{std::clamp((distance + margin) / Feather, 0.0, 1.0)}; return Strength * t * t * (3.0 - 2.0 * t); }); } @@ -2078,6 +2132,7 @@ void terrain_streamer::remember_manifest() m_change.manifest = true; m_change.layers = m_manifest.layers; m_change.water = m_manifest.water; + m_change.patches = m_manifest.patches; m_change.water_material = m_manifest.water_material; m_change.modifiers = m_manifest.modifiers; m_change.grass = m_manifest.grass; @@ -2126,6 +2181,7 @@ terrain_streamer::change terrain_streamer::restore(change const &Change) opposite.manifest = true; opposite.layers = m_manifest.layers; opposite.water = m_manifest.water; + opposite.patches = m_manifest.patches; opposite.water_material = m_manifest.water_material; opposite.modifiers = m_manifest.modifiers; opposite.grass = m_manifest.grass; @@ -2134,6 +2190,7 @@ terrain_streamer::change terrain_streamer::restore(change const &Change) m_manifest.layers = Change.layers; m_manifest.modifiers = Change.modifiers; m_manifest.water = Change.water; + m_manifest.patches = Change.patches; m_manifest.grass = Change.grass; if (false == Change.water_material.empty()) m_manifest.water_material = Change.water_material; @@ -2243,6 +2300,160 @@ bool terrain_streamer::save(std::string *Error) return true; } +// water and the pieces of the ground cut out + +namespace +{ + +// the grid a piece cut out of the terrain is laid on: its own, or for a piece following the terrain, one of its spacing laid from 0 +// (as the grids of the chunks are) over the box of the outline +struct patch_grid +{ + glm::dvec2 origin{0.0}; + double step{1.0}; + int columns{0}; + int rows{0}; +}; + +patch_grid grid_of(heightmap::surface_patch const &Patch) +{ + patch_grid grid; + if (false == Patch.follow) + { + grid.origin = Patch.origin; + grid.step = Patch.spacing; + grid.columns = Patch.columns; + grid.rows = Patch.rows; + return grid; + } + glm::dvec2 low; + glm::dvec2 high; + Patch.bounds(low, high); + grid.step = std::max(0.25, Patch.spacing); + grid.origin = glm::floor(low / grid.step) * grid.step; + grid.columns = static_cast(std::ceil((high.x - grid.origin.x) / grid.step)) + 1; + grid.rows = static_cast(std::ceil((high.y - grid.origin.y) / grid.step)) + 1; + return grid; +} + +// the triangles of a piece cut out of the terrain, in world space, facing up: the cells of its grid wholly inside the outline in two +// triangles each, cut along the diagonal the chunks are (from x0, z1 to x1, z0), the ones the outline runs through clipped to it +// triangle by triangle, so a piece following the terrain lies in the planes of its triangles. Height gives the heights; false where +// one isn't known yet (a chunk not loaded), then the piece is left for later and Missing set +template +std::vector patch_triangles(heightmap::surface_patch const &Patch, Height_ const &Height, bool &Missing) +{ + std::vector result; + Missing = false; + auto const &outline{Patch.outline}; + auto const grid{grid_of(Patch)}; + if (outline.size() < 3 || grid.columns < 2 || grid.rows < 2) + return result; + auto const step{grid.step}; + auto const cellsx{grid.columns - 1}; + auto const cellsz{grid.rows - 1}; + auto const inside = [&](double const X, double const Z) { + bool in{false}; + for (std::size_t i = 0, j = outline.size() - 1; i < outline.size(); j = i++) + if ((outline[i].y > Z) != (outline[j].y > Z) && X < (outline[j].x - outline[i].x) * (Z - outline[i].y) / (outline[j].y - outline[i].y) + outline[i].x) + in = !in; + return in; + }; + // the cells the outline runs through + std::vector edge(static_cast(cellsx) * cellsz, 0); + auto const mark = [&](glm::dvec2 const &Point) { + auto const cx{static_cast(std::floor((Point.x - grid.origin.x) / step))}; + auto const cz{static_cast(std::floor((Point.y - grid.origin.y) / step))}; + for (int dz = -1; dz <= 1; ++dz) + for (int dx = -1; dx <= 1; ++dx) + if (cx + dx >= 0 && cx + dx < cellsx && cz + dz >= 0 && cz + dz < cellsz) + edge[static_cast(cz + dz) * cellsx + cx + dx] = 1; + }; + for (std::size_t i = 0; i < outline.size(); ++i) + { + auto const &a{outline[i]}; + auto const &b{outline[(i + 1) % outline.size()]}; + auto const samples{std::max(1, static_cast(std::ceil(glm::distance(a, b) / (step * 0.25))))}; + for (int k = 0; k <= samples; ++k) + mark(glm::mix(a, b, static_cast(k) / samples)); + } + auto const vertex = [&](double const X, double const Z) { + double height{0.0}; + if (false == Height(X, Z, height)) + Missing = true; + return glm::dvec3{X, height, Z}; + }; + // a polygon in the plan, as triangles facing up + auto const emit = [&](std::vector const &Polygon) { + if (Polygon.size() < 3) + return; + auto const indices{heightmap::triangulate(Polygon)}; + // the polygon is turned counterclockwise in the plan, the triangles go the other way round to face up + for (std::size_t i = 0; i + 2 < indices.size(); i += 3) + for (auto const index : {indices[i + 2], indices[i + 1], indices[i]}) + result.push_back(vertex(Polygon[index].x, Polygon[index].y)); + }; + // Sutherland-Hodgman: the outline clipped to a triangle of a cell (A, B, C counterclockwise) + auto const clip = [&](glm::dvec2 const &A, glm::dvec2 const &B, glm::dvec2 const &C) { + std::vector polygon{outline}; + glm::dvec2 const corners[]{A, B, C}; + for (int side = 0; side < 3 && polygon.size() >= 3; ++side) + { + auto const &p{corners[side]}; + auto const &q{corners[(side + 1) % 3]}; + auto const keep = [&](glm::dvec2 const &P) { return (q.x - p.x) * (P.y - p.y) - (q.y - p.y) * (P.x - p.x) >= 0.0; }; + std::vector out; + for (std::size_t i = 0; i < polygon.size(); ++i) + { + auto const &a{polygon[i]}; + auto const &b{polygon[(i + 1) % polygon.size()]}; + auto const ina{keep(a)}; + auto const inb{keep(b)}; + if (ina) + out.push_back(a); + if (ina != inb) + { + auto const da{(q.x - p.x) * (a.y - p.y) - (q.y - p.y) * (a.x - p.x)}; + auto const db{(q.x - p.x) * (b.y - p.y) - (q.y - p.y) * (b.x - p.x)}; + out.push_back(a + (b - a) * (da / (da - db))); + } + } + polygon = std::move(out); + } + // points closer than a millimetre merged, the clipping leaves them along the sides of the triangle + std::vector clean; + for (auto const &point : polygon) + if (clean.empty() || glm::distance(clean.back(), point) > 1e-3) + clean.push_back(point); + while (clean.size() > 1 && glm::distance(clean.front(), clean.back()) <= 1e-3) + clean.pop_back(); + emit(clean); + }; + for (int cz = 0; cz < cellsz; ++cz) + for (int cx = 0; cx < cellsx; ++cx) + { + auto const x0{grid.origin.x + cx * step}; + auto const z0{grid.origin.y + cz * step}; + auto const x1{x0 + step}; + auto const z1{z0 + step}; + glm::dvec2 const a{x0, z0}, b{x1, z0}, c{x1, z1}, d{x0, z1}; + if (edge[static_cast(cz) * cellsx + cx]) + { + // the two triangles of the cell, counterclockwise, either side of the diagonal from (x0, z1) to (x1, z0) + clip(a, b, d); + clip(b, c, d); + continue; + } + if (false == inside(x0 + 0.5 * step, z0 + 0.5 * step)) + continue; + for (auto const &corner : {a, d, b, b, d, c}) + result.push_back(vertex(corner.x, corner.y)); + } + return result; +} + +} // namespace + // water void terrain_streamer::clear_water(bool const Touch) @@ -2346,4 +2557,123 @@ void terrain_streamer::build_water() entry.section = §ion; m_watershapes.push_back(entry); } + // the pieces of the ground cut out, with the geometry of the water: made anew together, in the same bank. Only the ones near + // the camera (pieces cut along the tracks of a whole network go in tens of thousands), again as it moves on; a piece over + // ground not loaded yet waits for it + m_patchcentre = glm::dvec2{m_camera.x, m_camera.z}; + m_patchpending = false; + for (auto const &patch : m_manifest.patches) + { + if (patch.paint) + continue; // laid into the paint of the chunks, no mesh of its own + glm::dvec2 boxlow; + glm::dvec2 boxhigh; + patch.bounds(boxlow, boxhigh); + auto const nearest{glm::clamp(m_patchcentre, boxlow, boxhigh)}; + if (m_hascamera && glm::distance(nearest, m_patchcentre) > patch_reach) + continue; + auto const surface = [&](double const X, double const Z, double &Height) { + if (false == patch.follow) + { + if (patch.height(X, Z, Height)) + return true; + // past the grid: the nearest of its edge + return patch.height(std::clamp(X, patch.origin.x, patch.origin.x + (patch.columns - 1) * patch.spacing), + std::clamp(Z, patch.origin.y, patch.origin.y + (patch.rows - 1) * patch.spacing), Height); + } + if (false == height_at(X, Z, Height)) + return false; + Height += patch.lift; + return true; + }; + bool missing{false}; + auto const triangles{patch_triangles(patch, surface, missing)}; + if (missing) + { + m_patchpending = true; + continue; + } + if (triangles.empty()) + continue; + glm::dvec2 low{std::numeric_limits::max()}; + glm::dvec2 high{-std::numeric_limits::max()}; + double bottom{std::numeric_limits::max()}; + double top{-std::numeric_limits::max()}; + for (auto const &point : triangles) + { + low = glm::min(low, glm::dvec2{point.x, point.z}); + high = glm::max(high, glm::dvec2{point.x, point.z}); + bottom = std::min(bottom, point.y); + top = std::max(top, point.y); + } + auto const middle{(low + high) * 0.5}; + if (false == in_region(middle)) + continue; + auto const name{patch.material.empty() ? (m_manifest.layers.empty() ? std::string{"grass"} : m_manifest.layers.front().material) : patch.material}; + auto const material{GfxRenderer->Fetch_Material(name)}; + auto const *materialdata{GfxRenderer->Material(material)}; + auto const repeat{patch.size > 0.f ? static_cast(patch.size) : (materialdata != nullptr && materialdata->GetSize().x > 0.f) ? static_cast(materialdata->GetSize().x) : 8.0}; + glm::dvec3 const centre{middle.x, 0.5 * (bottom + top), middle.y}; + auto §ion{simulation::Region->section(centre)}; + section.create_geometry(); + auto const origin{section.m_area.center}; + auto const angle{glm::radians(static_cast(patch.rotation))}; + glm::dvec2 const along{std::cos(angle), std::sin(angle)}; + glm::dvec2 const across{-along.y, along.x}; + // the slope of the heights at the point, for the normal + auto const normal_at = [&](double const X, double const Z) { + auto const d{std::max(0.25, patch.spacing * 0.5)}; + double hx0{0.0}, hx1{0.0}, hz0{0.0}, hz1{0.0}; + if (false == (surface(X - d, Z, hx0) && surface(X + d, Z, hx1) && surface(X, Z - d, hz0) && surface(X, Z + d, hz1))) + return glm::vec3{0.f, 1.f, 0.f}; + return glm::vec3(glm::normalize(glm::dvec3{-(hx1 - hx0) / (2.0 * d), 1.0, -(hz1 - hz0) / (2.0 * d)})); + }; + gfx::vertex_array vertices; + vertices.reserve(triangles.size()); + for (auto const &point : triangles) + { + glm::dvec2 const local{point.x - patch.origin.x, point.z - patch.origin.y}; + gfx::basic_vertex vertex; + vertex.position = glm::vec3(point - origin); + vertex.normal = normal_at(point.x, point.z); + vertex.texture = {static_cast(glm::dot(local, along) / repeat), static_cast(-glm::dot(local, across) / repeat)}; + vertex.tangent = {static_cast(along.x), 0.f, static_cast(along.y), 1.f}; + vertices.push_back(vertex); + } + gfx::userdata_array nouserdata; + water_shape entry; + if (false == m_waterfree.empty()) + { + entry.geometry = m_waterfree.back(); + m_waterfree.pop_back(); + GfxRenderer->Replace(vertices, nouserdata, entry.geometry, GL_TRIANGLES); + } + else + { + if (m_waterbank.bank == 0 && m_waterbank.chunk == 0) + m_waterbank = GfxRenderer->Create_Bank(); + entry.geometry = GfxRenderer->Insert(vertices, nouserdata, m_waterbank, GL_TRIANGLES); + } + if (entry.geometry.chunk == 0) + continue; + auto const reach{glm::length(high - low) * 0.5}; + std::vector bounds(2); + bounds[0].position = glm::dvec3{low.x, bottom, low.y}; + bounds[1].position = glm::dvec3{high.x, top, high.y}; + scene::shape_node shape; + shape.make_terrain(material, std::move(bounds), origin); + shape.geometry(entry.geometry); + section.m_shapes.emplace_back(std::move(shape)); + section.m_area.radius = std::max(section.m_area.radius, static_cast(glm::length(section.m_area.center - centre) + reach)); + entry.section = §ion; + m_watershapes.push_back(entry); + } +} + +void terrain_streamer::patches(std::vector Patches) +{ + remember_manifest(); + m_manifest.patches = std::move(Patches); + m_manifestchanged = true; + m_waterchanged = true; } diff --git a/editor/editorTerrainStreamer.hpp b/editor/editorTerrainStreamer.hpp index 1b3282196..07b9b15ea 100644 --- a/editor/editorTerrainStreamer.hpp +++ b/editor/editorTerrainStreamer.hpp @@ -130,6 +130,8 @@ class terrain_streamer // Feather: metres across the outline the material blends in over, half of them inside; 0: a sharp edge, as sharp as // the paint samples of the chunks go. the chunks are loaded where needed bool fill(std::vector const &Outline, double Feather, std::uint16_t Layer, double Strength = 1.0); + // the same with the edge shifted by up to Noise metres, in waves of about NoiseScale metres, so it isn't drawn with a ruler + bool fill(std::vector const &Outline, double Feather, std::uint16_t Layer, double Strength, double Noise, double NoiseScale); // holes, for the portals of tunnels and the like: cut in the ground (Cut true) within Radius of (X,Z), or closed again bool cut(double X, double Z, double Radius, bool Cut); // the same within Outline (x, z); the chunks are loaded where needed @@ -159,6 +161,9 @@ class terrain_streamer void water(std::vector Water); // material of the bodies of water which don't name their own void water_material(std::string const &Material); + // pieces of the ground cut out of the terrain with a material of their own (the fields), drawn with the water + std::vector const &patches() const { return m_manifest.patches; } + void patches(std::vector Patches); // modifiers: added or replaced by name void modifier(heightmap::modifier Modifier); // many at once, as the formation of all the tracks: each chunk they reach is led anew once @@ -180,6 +185,7 @@ class terrain_streamer bool manifest{false}; // the palette, the water (and its material) and the modifiers below were changed std::vector layers; std::vector water; + std::vector patches; std::string water_material; std::vector modifiers; std::vector grass; @@ -334,6 +340,13 @@ class terrain_streamer glm::dvec3 m_velocity{0.0}; double m_cameratime{0.0}; bool m_hascamera{false}; + // the pieces cut out of the terrain are made around where the camera was, within patch_reach, again when it moves patch_move away + static constexpr double patch_reach{1500.0}; + static constexpr double patch_move{200.0}; + glm::dvec2 m_patchcentre{1e12}; + bool m_patchpending{false}; // some waited for chunks not loaded + bool m_patchloaded{false}; // a chunk came since they were made + double m_patchtried{0.0}; std::vector m_ring; // offsets of the chunks around a point, the nearest first int m_ringradius{-1}; double m_pixel{0.0}; // metres a pixel of the top view spans; none in the 3D view diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 2aeaefec1..78e106617 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14294,3 +14294,348 @@ msgstr "Przesuwa profil na miejsce trasy, gdzie jest kamera, bez zmiany powięks msgid "The switch drawn to the joint of the tracks" msgstr "Rozjazd dosunięty do styku torów" + +msgid "Edge" +msgstr "Krawędź" + +msgid "How far the edge wanders in and out of the outline, so it isn't drawn with a ruler" +msgstr "Na ile krawędź wchodzi w obrys i z niego wychodzi, żeby nie była od linijki" + +msgid "About how long the waves of the edge are: small - frayed, large - gently wavy" +msgstr "Mniej więcej długość fal krawędzi: małe - poszarpana, duże - łagodnie falista" + +msgid "Natural slopes" +msgstr "Naturalne skarpy" + +msgid "Foot wanders by (m)" +msgstr "Falowanie podnóża (m)" + +msgid "Waves along the line (m)" +msgstr "Fale wzdłuż linii (m)" + +msgid "About how long the waves of the foot are along the line" +msgstr "Mniej więcej długość fal podnóża wzdłuż linii" + +msgid "Gentler by up to" +msgstr "Łagodniejsze o najwyżej" + +msgid "0.2: the slope 1:1.5 gets as gentle as 1:1.8 here and there, never steeper than designed" +msgstr "0,2: skarpa 1:1,5 miejscami łagodnieje do 1:1,8, nigdy nie jest bardziej stroma niż w projekcie" + +msgid "Soft foot (m/m)" +msgstr "Miękkie podnóże (m/m)" + +msgid "Metres the foot is rounded off over, for a metre of the height of the slope: high embankments meet the ground softer" +msgstr "Na ilu metrach podnóże się zaokrągla, na metr wysokości skarpy: wysokie nasypy łagodniej wchodzą w teren" + +msgid "Bumps on the face (m)" +msgstr "Nierówności skarpy (m)" + +msgid "Metres the face of the slope is uneven by, as earth settled for years" +msgstr "O ile metrów powierzchnia skarpy jest nierówna, jak ziemia ułożona przez lata" + +msgid "Make the slopes natural" +msgstr "Zrób naturalne skarpy" + +msgid "Back to the slopes as designed" +msgstr "Z powrotem skarpy według projektu" + +msgid "Cut out as %s with %s, Ctrl+Z puts it back" +msgstr "Wycięto jako %s z %s, Ctrl+Z przywraca" + +msgid "Waves of the ground" +msgstr "Falowanie terenu" + +msgid "Make the ground under the surface wavy" +msgstr "Pofałduj teren pod powierzchnią" + +msgid "The heights of the terrain within the outline get the waves chosen below, fading in from the edge: a field ploughed into furrows, a meadow of gentle hills, a hollow. Ctrl+Z takes them back with the surface" +msgstr "Wysokości terenu w obrysie dostają wybrane niżej fale, narastające od krawędzi: pole zaorane w bruzdy, łąka z łagodnymi pagórkami, niecka. Ctrl+Z cofa je razem z powierzchnią" + +msgid "Rolling hills" +msgstr "Łagodne pagórki" + +msgid "Furrows of a field" +msgstr "Bruzdy na polu" + +msgid "Bumps and molehills" +msgstr "Garby i kretowiska" + +msgid "Long waves" +msgstr "Długie fale" + +msgid "A hollow or a mound" +msgstr "Niecka albo kopiec" + +msgid "A grid of hummocks" +msgstr "Kratka garbów" + +msgid "Strips of fields" +msgstr "Pasy pól" + +msgid "Gentle hills of all sizes, as a meadow or a pasture has them" +msgstr "Łagodne pagórki różnej wielkości, jak na łące albo pastwisku" + +msgid "Ridges and furrows side by side, along the angle below, as a ploughed field or the beds of a garden" +msgstr "Grzbiety i bruzdy obok siebie, w kierunku podanym niżej, jak na zaoranym polu albo grządkach" + +msgid "Small mounds scattered about, as molehills or tussocks" +msgstr "Rozrzucone małe garby, jak kretowiska albo kępy" + +msgid "Long even waves across the angle below, as a field rolling over a hill or dunes" +msgstr "Długie równe fale w poprzek kierunku podanego niżej, jak pole na zboczu albo wydmy" + +msgid "The middle lowered (a negative height raises it): a hollow by a pond, a dip in a field, or a mound" +msgstr "Obniżony środek (ujemna wysokość go podnosi): niecka przy stawie, zagłębienie w polu albo kopiec" + +msgid "Waves along the angle and across it at once: hummocks in rows, as a drained meadow or an orchard on ridges" +msgstr "Fale wzdłuż kąta i w poprzek naraz: garby w rzędach, jak meliorowana łąka albo sad na zagonach" + +msgid "Long strips along the angle, each a little higher or lower than the next, with banks between them: the fields of a village cut up between farms" +msgstr "Długie pasy wzdłuż kąta, każdy trochę wyżej lub niżej od sąsiada, z miedzami między nimi: wiejskie pola podzielone między gospodarstwa" + +msgid "Kind##waves" +msgstr "Rodzaj##waves" + +msgid "Height (m)##waves" +msgstr "Wysokość (m)##waves" + +msgid "From the bottom of a wave to its top; for the hollow how deep its middle goes, negative: a mound" +msgstr "Od dołu fali do jej szczytu; dla niecki głębokość środka, ujemna: kopiec" + +msgid "Length of a wave (m)##waves" +msgstr "Długość fali (m)##waves" + +msgid "From one top to the next: furrows 0.7-2 m, the beds of a garden 1.5-3 m, hills 20-100 m" +msgstr "Od jednego szczytu do następnego: bruzdy 0,7-2 m, grządki 1,5-3 m, pagórki 20-100 m" + +msgid "Direction (deg)##waves" +msgstr "Kierunek (°)##waves" + +msgid "Which way the furrows or the ridges of the waves run, counterclockwise from the x axis of the scenery; the texture turned by the same angle lies along them" +msgstr "Kierunek bruzd albo grzbietów fal, przeciwnie do zegara od osi x scenerii; tekstura obrócona o ten sam kąt leży wzdłuż nich" + +msgid "as the texture" +msgstr "jak tekstura" + +msgid "Rounded" +msgstr "Zaokrąglony" + +msgid "Sharp ridges" +msgstr "Ostre grzbiety" + +msgid "Sharp valleys" +msgstr "Ostre doliny" + +msgid "Terraces" +msgstr "Tarasy" + +msgid "Flat tops" +msgstr "Płaskie wierzchy" + +msgid "Every wave a gentle curve, as before" +msgstr "Każda fala łagodnym łukiem, jak dotąd" + +msgid "Tops pointed, sides straight: ploughed ridges, a dune crest, a bank between fields" +msgstr "Szczyty ostre, zbocza proste: zagony po orce, grzbiet wydmy, miedza" + +msgid "Bottoms pointed: drainage ditches, gullies cut by water, the furrow left by a plough" +msgstr "Dna ostre: rowy melioracyjne, żleby wymyte przez wodę, bruzda po pługu" + +msgid "The slopes broken into flat steps: terraced fields on a hillside, a quarry, the shelves of a vineyard" +msgstr "Zbocza połamane na płaskie stopnie: pola tarasowe na stoku, kamieniołom, półki winnicy" + +msgid "Tops and bottoms cut flat with steep sides between: beds of a garden, fields on raised strips, plateaus" +msgstr "Wierzchy i dna ścięte płasko, strome boki między nimi: grządki, pola na wyniesionych pasach, płaskowyże" + +msgid "Profile##waves" +msgstr "Profil##waves" + +msgid "The cross-section of a wave; the rounded one makes the fields look soft, the others give them edges" +msgstr "Przekrój fali; zaokrąglony daje miękkie, obłe pola, pozostałe nadają im krawędzie" + +msgid "Sharpness##waves" +msgstr "Ostrość##waves" + +msgid "0: the profile barely changed from the rounded one; 1: its edges and corners as sharp as they get" +msgstr "0: profil prawie jak zaokrąglony; 1: krawędzie i narożniki najostrzejsze, jak się da" + +msgid "Steps##waves" +msgstr "Stopnie##waves" + +msgid "How many flat steps a slope is broken into, from the bottom of a wave to its top" +msgstr "Na ile płaskich stopni dzieli się zbocze, od dna fali do jej szczytu" + +msgid "Roughness##waves" +msgstr "Chropowatość##waves" + +msgid "Clods and hummocks of about 3 m over the whole surface, up to 20 cm high: a ploughed field, a trodden pasture.\nThe terrain under the surface gets a point every metre for them (and for waves shorter than 15 m), the files grow" +msgstr "Grudy i kępy wielkości około 3 m na całej powierzchni, do 20 cm wysokości: zaorane pole, wydeptane pastwisko.\nTeren pod powierzchnią dostaje dla nich punkt co metr (także dla fal krótszych niż 15 m), pliki rosną" + +msgid "Differences between them##waves" +msgstr "Zróżnicowanie##waves" + +msgid "0: every wave alike, as drawn; 1: waves of quite different heights and places, as nature has them" +msgstr "0: wszystkie fale jednakowe, jak od linijki; 1: fale o bardzo różnej wysokości i położeniu, jak w naturze" + +msgid "Fading in from the edge (m)##waves" +msgstr "Narastanie od krawędzi (m)##waves" + +msgid "Metres inside the outline over which the waves grow from nothing, so the ground around meets the surface without a step" +msgstr "Ile metrów w głąb obrysu fale narastają od zera, żeby teren dookoła łączył się z powierzchnią bez progu" + +msgid "left as it grows" +msgstr "zostaje, jak rośnie" + +msgid "taken away" +msgstr "usunięta" + +msgid "grown: %s" +msgstr "posadzona: %s" + +msgid "The 3D grass under the surface: left as it grows, taken away (gravel, a yard), or another kind of the grass palette grown there instead" +msgstr "Trawa 3D pod powierzchnią: zostaje, jak rośnie, jest usuwana (żwir, plac) albo w jej miejsce sadzony jest inny rodzaj z palety trawy" + +msgid "Filter by name, words apart by spaces..." +msgstr "Filtr po nazwie, słowa oddzielone spacjami..." + +msgid "%zu shown" +msgstr "pokazanych: %zu" + +msgid "Material of the palette to all shown" +msgstr "Materiał z palety dla wszystkich pokazanych" + +msgid "%s given to %zu surfaces, Ctrl+Z takes it back" +msgstr "%s nadany %zu powierzchniom, Ctrl+Z cofa" + +msgid "The material chosen in the palette, with its repeat and rotation, to all the surfaces the filter shows" +msgstr "Materiał wybrany w palecie, z jego powtarzaniem i obrotem, dla wszystkich powierzchni pokazanych przez filtr" + +msgid "%s, %zu points, %s" +msgstr "%s, %zu punktów, %s" + +msgid "Material##patch" +msgstr "Materiał##patch" + +msgid "From the palette##patch" +msgstr "Z palety##patch" + +msgid "Repeat (m)##patch" +msgstr "Powtarzanie (m)##patch" + +msgid "of the material" +msgstr "wg materiału" + +msgid "Turned by (deg)##patch" +msgstr "Obrót (st.)##patch" + +msgid "Transition (m)##patch" +msgstr "Szerokość przejścia (m)##patch" + +msgid "Noise of the edge (m)##patch" +msgstr "Szum krawędzi (m)##patch" + +msgid "Waves of the noise (m)##patch" +msgstr "Fale szumu (m)##patch" + +msgid "3D grass under it##patch" +msgstr "Trawa 3D pod spodem##patch" + +msgid "Lift (m)##patch" +msgstr "Uniesienie (m)##patch" + +msgid "Metres the surface lies over the heights taken from the terrain" +msgstr "Ile metrów powierzchnia leży nad wysokościami wziętymi z terenu" + +msgid "Outline it again##patch" +msgstr "Obrysuj ponownie##patch" + +msgid "Give back to the terrain##patch" +msgstr "Oddaj terenowi##patch" + +msgid "Surface removed, the ground under it has the first material of the palette again" +msgstr "Powierzchnia usunięta, teren pod nią ma z powrotem pierwszy materiał palety" + +msgid "Surface removed, the hole under it closed" +msgstr "Powierzchnię usunięto, dziura pod nią zamknięta" + +msgid "No formation modifier there" +msgstr "Brak tam modyfikatora torowiska" + +msgid "The slopes of %zu modifiers made natural, the terrain shaped anew. Ctrl+Z takes it back" +msgstr "Naturalne skarpy dla %zu modyfikatorów, teren ukształtowany od nowa. Ctrl+Z cofa" + +msgid "The slopes of %zu modifiers as designed again. Ctrl+Z takes it back" +msgstr "Skarpy %zu modyfikatorów znów według projektu. Ctrl+Z cofa" + +msgid "LMB adds a point of the outline, Shift+LMB takes the last one back. The field gets the material chosen in the palette and is kept in the list below, where its material can be changed later" +msgstr "LPM dodaje punkt obrysu, Shift+LPM cofa ostatni. Pole dostaje materiał wybrany w palecie i trafia na listę poniżej, gdzie jego materiał można później zmienić" + +msgid "Painted into the terrain##fields" +msgstr "Wmalowane w teren##fields" + +msgid "The material goes into the paint of the chunks: no seam, the edge blends into the ground around; a chunk holds up to 8 materials" +msgstr "Materiał trafia do malowania chunków: bez szwu, krawędź przechodzi w otoczenie; chunk mieści do 8 materiałów" + +msgid "A surface of its own##fields" +msgstr "Osobna powierzchnia##fields" + +msgid "The ground is cut away within the outline and the field drawn over the hole as a mesh of its own, following the heights of the terrain:\nit doesn't take one of the 8 materials of a chunk, but its edge is sharp and the seam can show" +msgstr "Grunt w obrysie zostaje wycięty, a pole rysowane nad dziurą jako osobna siatka po wysokościach terenu:\nnie zajmuje żadnego z 8 materiałów chunka, ale krawędź jest ostra i może być widać szew" + +msgid "Transition (m)##fields" +msgstr "Przejście (m)##fields" + +msgid "Metres across the edge the material passes into the one around over, half of them inside the field.\nThe paint of the terrain is kept every metre (every 0.5 m in the chunks converted to 0.5 m), narrower comes out in steps" +msgstr "Na ilu metrach w poprzek krawędzi materiał przechodzi w otoczenie, połowa z nich w środku pola.\nMalowanie terenu jest zapisywane co metr (co 0,5 m w chunkach przerobionych na 0,5 m), węższe wychodzi schodkami" + +msgid "Noise of the edge (m)##fields" +msgstr "Szum krawędzi (m)##fields" + +msgid "Waves of the noise (m)##fields" +msgstr "Fale szumu (m)##fields" + +msgid "3D grass under it##fields" +msgstr "Trawa 3D pod spodem##fields" + +msgid "Texture turned by (deg)##fields" +msgstr "Obrót tekstury (st.)##fields" + +msgid "Cut out the field" +msgstr "Wytnij pole" + +msgid "Clear the outline##fields" +msgstr "Wyczyść obrys##fields" + +msgid "The embankments and the cuttings of the formation modifiers not drawn with a ruler: the formation and the edges of the track bed stay as designed, the slopes and their foot wander, get gentler here and there and meet the ground softly" +msgstr "Nasypy i przekopy modyfikatorów torowiska nie jak spod linijki: korona i krawędzie torowiska zostają według projektu, a skarpy i ich podnóże falują, miejscami łagodnieją i miękko schodzą w teren" + +msgid "How far the foot of the slope goes in and out of the line of the slope" +msgstr "Jak daleko podnóże skarpy wychodzi przed linię skarpy i cofa się za nią" + +msgid "Around the camera##natural" +msgstr "Wokół kamery##natural" + +msgid "The whole scenery##natural" +msgstr "Cała sceneria##natural" + +msgid "m##natural" +msgstr "m##natural" + +msgid "The terrain under the modifiers is shaped anew; Ctrl+Z takes it back" +msgstr "Teren pod modyfikatorami zostaje ukształtowany od nowa; Ctrl+Z cofa" + +msgid "field %d" +msgstr "pole %d" + +msgid "Fields: %zu" +msgstr "Pola: %zu" + +msgid "Puts the outline of the field back as the outline being drawn" +msgstr "Przywraca obrys pola jako rysowany obrys" + +msgid "Fields" +msgstr "Pola" + +msgid "LMB adds a point of the outline of a field: a surface cut out of the terrain with a material of its own, the ground under it made wavy if wanted; Shift+LMB takes the last one back" +msgstr "LPM dodaje punkt obrysu pola: powierzchni wyciętej z terenu z własnym materiałem, z pofalowanym gruntem, jeśli chcesz; Shift+LPM cofa ostatni" diff --git a/scene/heightmapterrain.cpp b/scene/heightmapterrain.cpp index 29cb42175..78198a6c8 100644 --- a/scene/heightmapterrain.cpp +++ b/scene/heightmapterrain.cpp @@ -18,6 +18,9 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include +#include #include #include "zstd.h" @@ -184,6 +187,35 @@ int floor_div(int const Value, int const Divisor) return (Value >= 0 ? Value / Divisor : -((-Value + Divisor - 1) / Divisor)); } +// smooth noise of -1..1 in waves of about Scale metres, the same at the same place every time; Channel gives another one +double natural_noise(double const X, double const Z, double const Scale, int const Channel) +{ + auto const hash = [](std::int64_t const Ix, std::int64_t const Iz) { + auto h{static_cast(Ix) * 0x9E3779B97F4A7C15ull ^ static_cast(Iz) * 0xC2B2AE3D27D4EB4Full}; + h ^= h >> 31; + h *= 0xBF58476D1CE4E5B9ull; + h ^= h >> 29; + return static_cast(h & 0xffffff) / static_cast(0xffffff) * 2.0 - 1.0; + }; + auto const octave = [&](double const U, double const V) { + auto const iu{std::floor(U)}; + auto const iv{std::floor(V)}; + auto const fu{U - iu}; + auto const fv{V - iv}; + auto const su{fu * fu * (3.0 - 2.0 * fu)}; + auto const sv{fv * fv * (3.0 - 2.0 * fv)}; + auto const x{static_cast(iu)}; + auto const z{static_cast(iv)}; + auto const a{hash(x, z) + (hash(x + 1, z) - hash(x, z)) * su}; + auto const b{hash(x, z + 1) + (hash(x + 1, z + 1) - hash(x, z + 1)) * su}; + return a + (b - a) * sv; + }; + auto const scale{std::max(0.5, Scale)}; + auto const u{X / scale + Channel * 101.7}; + auto const v{Z / scale - Channel * 57.3}; + return std::clamp(0.7 * octave(u, v) + 0.3 * octave(u * 2.7 + 17.3, v * 2.7 - 9.1), -1.0, 1.0); +} + // the larger of two values, the corner between them rounded off over K double soft_max(double const A, double const B, double const K) { @@ -666,14 +698,30 @@ std::optional modifier_shape::evaluate(double const X, d if (false == found) return std::nullopt; // the formation under the axis, slopes from its edges down or up to the ground, the bends rounded off - auto const slope{std::max(0.1, m_modifier.slope)}; + auto slope{std::max(0.1, m_modifier.slope)}; auto const rounding{std::max(0.0, m_modifier.rounding)}; auto const ground{Ground}; - auto const beyond{soft_max(0.0, distance - halfwidth, rounding)}; + auto beyond{soft_max(0.0, distance - halfwidth, rounding)}; // the bends of the slopes round off only away from the formation: under it the ground is the formation itself, a cut or a // fill as shallow as the bend isn't let to sink or rise it - auto const bend{rounding / slope * std::clamp(beyond / std::max(rounding, 1e-6), 0.0, 1.0)}; - auto const target{ground > formation ? -soft_max(-ground, -(formation + beyond / slope), bend) : soft_max(ground, formation - beyond / slope, bend)}; + auto bend{rounding / slope * std::clamp(beyond / std::max(rounding, 1e-6), 0.0, 1.0)}; + auto const &natural{m_modifier.natural}; + // away from the edge of the formation only: the track bed keeps its width and its edges + auto const fade{natural.any() ? std::clamp(beyond / 3.0, 0.0, 1.0) : 0.0}; + if (fade > 0.0) + { + auto const smooth{fade * fade * (3.0 - 2.0 * fade)}; + beyond = std::max(0.0, beyond - natural.wander * natural_noise(X, Z, natural.scale, 1) * smooth); + slope *= 1.0 + std::max(0.0, natural.gentler) * (0.5 + 0.5 * natural_noise(X, Z, natural.scale * 0.7, 2)) * smooth; + bend += std::max(0.0, natural.soften) * std::min(std::abs(ground - formation), 6.0) * smooth; + } + auto target{ground > formation ? -soft_max(-ground, -(formation + beyond / slope), bend) : soft_max(ground, formation - beyond / slope, bend)}; + if (fade > 0.0 && natural.roughness > 0.0) + { + // bumps on the face of the slope, none where it meets the ground + auto const face{std::clamp(std::abs(target - ground) / 0.5, 0.0, 1.0)}; + target += natural.roughness * natural_noise(X, Z, 3.0, 3) * face * fade; + } return effect{target, distance - halfwidth, distance}; } @@ -747,6 +795,67 @@ bool load_manifest(std::string const &Path, manifest &Manifest, std::string *Err if (water.outline.size() >= 3) result.water.push_back(std::move(water)); } + if (auto const node{document["patches"]}; node && node.IsSequence()) + for (auto const &entry : node) + { + surface_patch patch; + if (auto const name{entry["name"]}) + patch.name = name.as(); + if (auto const material{entry["material"]}) + patch.material = material.as(); + if (auto const size{entry["size"]}) + patch.size = std::max(0.f, size.as()); + if (auto const rotation{entry["rotation"]}) + patch.rotation = rotation.as(); + if (auto const lift{entry["lift"]}) + patch.lift = lift.as(); + if (auto const outline{entry["outline"]}; outline && outline.IsSequence()) + for (auto const &point : outline) + if (point.IsSequence() && point.size() >= 2) + patch.outline.emplace_back(point[0].as(), point[1].as()); + if (auto const grid{entry["grid"]}; grid && grid.IsSequence() && grid.size() >= 5) + { + patch.origin = {grid[0].as(), grid[1].as()}; + patch.spacing = std::max(0.1, grid[2].as()); + patch.columns = std::max(0, grid[3].as()); + patch.rows = std::max(0, grid[4].as()); + } + if (auto const heights{entry["heights"]}; heights && heights.IsSequence()) + { + patch.heights.reserve(heights.size()); + for (auto const &height : heights) + patch.heights.push_back(height.as()); + } + if (auto const follow{entry["follow"]}) + patch.follow = follow.as(); + if (auto const paint{entry["paint"]}) + { + patch.paint = paint.as(); + patch.follow = patch.follow || patch.paint; + } + if (auto const node{entry["feather"]}) + patch.feather = std::max(0.f, node.as()); + if (auto const node{entry["noise"]}) + patch.noise = std::max(0.f, node.as()); + if (auto const node{entry["noise_scale"]}) + patch.noise_scale = std::max(0.5f, node.as()); + if (auto const node{entry["shape"]}) + patch.shape = node.as(); + if (auto const node{entry["grass"]}) + patch.grass = std::max(-2, node.as()); + if (patch.follow && !entry["grid"] && !entry["spacing"]) + patch.spacing = 2.0; + if (auto const spacing{entry["spacing"]}) + patch.spacing = std::max(0.1, spacing.as()); + if (patch.outline.size() >= 3 && (patch.follow || (patch.columns >= 2 && patch.rows >= 2 && patch.heights.size() == static_cast(patch.columns) * patch.rows))) + result.patches.push_back(std::move(patch)); + } + if (auto const node{document["patches_file"]}) + { + result.patches_file = node.as(); + auto const folder{std::filesystem::path(Path).parent_path()}; + load_patches((folder / result.patches_file).string(), result.patches); + } if (auto const node{document["modifiers"]}; node && node.IsSequence()) for (auto const &entry : node) { @@ -759,6 +868,20 @@ bool load_manifest(std::string const &Path, manifest &Manifest, std::string *Err item.reach = reach.as(); if (auto const rounding{entry["rounding"]}) item.rounding = rounding.as(); + // natural: {wander: , scale: , gentler: , soften: , roughness: } + if (auto const natural{entry["natural"]}; natural && natural.IsMap()) + { + auto const take = [&](char const *Key, double &Value) { + if (auto const node{natural[Key]}) + Value = std::max(0.0, node.as()); + }; + take("wander", item.natural.wander); + take("scale", item.natural.scale); + take("gentler", item.natural.gentler); + take("soften", item.natural.soften); + take("roughness", item.natural.roughness); + item.natural.scale = std::max(0.5, item.natural.scale); + } if (auto const open{entry["open_start"]}) item.open_start = open.as(); if (auto const open{entry["open_end"]}) @@ -853,6 +976,69 @@ bool save_manifest(std::string const &Path, manifest const &Manifest, std::strin } out << YAML::EndSeq; } + auto const sidecar{Manifest.patches_file.empty() && Manifest.patches.size() > patches_inline ? std::string{"patches.txt"} : Manifest.patches_file}; + if (false == sidecar.empty()) + { + out << YAML::Key << "patches_file" << YAML::Value << sidecar; + auto const folder{std::filesystem::path(Path).parent_path()}; + if (false == save_patches((folder / sidecar).string(), Manifest.patches)) + { + if (Error != nullptr) + *Error = "can't write " + sidecar; + return false; + } + } + // with the file, only the patches with heights of their own stay here + auto const inline_patch = [&](surface_patch const &Patch) { return sidecar.empty() || false == Patch.follow; }; + if (std::any_of(Manifest.patches.begin(), Manifest.patches.end(), inline_patch)) + { + out << YAML::Key << "patches" << YAML::Value << YAML::BeginSeq; + for (auto const &patch : Manifest.patches) + { + if (false == inline_patch(patch)) + continue; + out << YAML::BeginMap; + out << YAML::Key << "name" << YAML::Value << patch.name; + if (false == patch.material.empty()) + out << YAML::Key << "material" << YAML::Value << patch.material; + if (patch.size > 0.f) + out << YAML::Key << "size" << YAML::Value << patch.size; + if (patch.rotation != 0.f) + out << YAML::Key << "rotation" << YAML::Value << patch.rotation; + if (patch.lift != 0.f) + out << YAML::Key << "lift" << YAML::Value << patch.lift; + out << YAML::Key << "outline" << YAML::Value << YAML::BeginSeq; + for (auto const &point : patch.outline) + out << YAML::Flow << YAML::BeginSeq << point.x << point.y << YAML::EndSeq; + out << YAML::EndSeq; + if (false == patch.shape.empty()) + out << YAML::Key << "shape" << YAML::Value << patch.shape; + if (patch.grass != -2) + out << YAML::Key << "grass" << YAML::Value << patch.grass; + if (patch.paint) + { + out << YAML::Key << "paint" << YAML::Value << true; + out << YAML::Key << "feather" << YAML::Value << patch.feather; + out << YAML::Key << "noise" << YAML::Value << patch.noise; + out << YAML::Key << "noise_scale" << YAML::Value << patch.noise_scale; + } + else if (patch.follow) + { + out << YAML::Key << "follow" << YAML::Value << true; + out << YAML::Key << "spacing" << YAML::Value << patch.spacing; + } + else + { + out << YAML::Key << "grid" << YAML::Value << YAML::Flow << YAML::BeginSeq << patch.origin.x << patch.origin.y << patch.spacing << patch.columns << patch.rows << YAML::EndSeq; + out << YAML::Key << "heights" << YAML::Value << YAML::Flow << YAML::BeginSeq; + for (auto const height : patch.heights) + out << std::round(height * 1000.f) / 1000.f; + out << YAML::EndSeq; + } + out << YAML::EndMap; + } + out << YAML::EndSeq; + } if (false == Manifest.modifiers.empty()) { out << YAML::Key << "modifiers" << YAML::Value << YAML::BeginSeq; @@ -863,6 +1049,16 @@ bool save_manifest(std::string const &Path, manifest const &Manifest, std::strin out << YAML::Key << "slope" << YAML::Value << item.slope; out << YAML::Key << "reach" << YAML::Value << item.reach; out << YAML::Key << "rounding" << YAML::Value << item.rounding; + if (item.natural.any()) + { + out << YAML::Key << "natural" << YAML::Value << YAML::Flow << YAML::BeginMap; + out << YAML::Key << "wander" << YAML::Value << item.natural.wander; + out << YAML::Key << "scale" << YAML::Value << item.natural.scale; + out << YAML::Key << "gentler" << YAML::Value << item.natural.gentler; + out << YAML::Key << "soften" << YAML::Value << item.natural.soften; + out << YAML::Key << "roughness" << YAML::Value << item.natural.roughness; + out << YAML::EndMap; + } if (item.open_start) out << YAML::Key << "open_start" << YAML::Value << true; if (item.open_end) @@ -1295,6 +1491,119 @@ bool write_pack(std::string const &Path, pack_key const &Key, std::vector::max()}; + High = glm::dvec2{-std::numeric_limits::max()}; + for (auto const &point : outline) + { + Low = glm::min(Low, point); + High = glm::max(High, point); + } +} + +// the patches file: a line a patch, its fields apart by tabs: name, material, repeat, rotation, lift, spacing, kind (paint or +// surface), transition, noise, the waves of the noise, then the outline as x z pairs apart by spaces. Lines starting with # are +// left out. The patches of it follow the terrain. The files written before the kind came have the outline right after the spacing +bool load_patches(std::string const &Path, std::vector &Patches) +{ + std::ifstream file{Path}; + if (false == file.is_open()) + return false; + std::string line; + while (std::getline(file, line)) + { + if (line.empty() || line[0] == '#') + continue; + if (line.back() == '\r') + line.pop_back(); + std::vector fields; + std::size_t start{0}; + for (;;) + { + auto const tab{line.find('\t', start)}; + fields.push_back(line.substr(start, tab == std::string::npos ? std::string::npos : tab - start)); + if (tab == std::string::npos) + break; + start = tab + 1; + } + if (fields.size() < 7) + continue; + auto const kinded{fields.size() >= 11 && (fields[6] == "paint" || fields[6] == "surface")}; + surface_patch patch; + patch.follow = true; + patch.name = fields[0]; + patch.material = fields[1]; + patch.size = std::max(0.f, static_cast(std::atof(fields[2].c_str()))); + patch.rotation = static_cast(std::atof(fields[3].c_str())); + patch.lift = static_cast(std::atof(fields[4].c_str())); + patch.spacing = std::max(0.1, std::atof(fields[5].c_str())); + if (kinded) + { + patch.paint = fields[6] == "paint"; + patch.feather = std::max(0.f, static_cast(std::atof(fields[7].c_str()))); + patch.noise = std::max(0.f, static_cast(std::atof(fields[8].c_str()))); + patch.noise_scale = std::max(0.5f, static_cast(std::atof(fields[9].c_str()))); + } + std::istringstream points{fields[kinded ? 10 : 6]}; + if (kinded && fields.size() >= 12) + patch.shape = fields[11]; + if (kinded && fields.size() >= 13) + patch.grass = std::max(-2, std::atoi(fields[12].c_str())); + double x{0.0}; + double z{0.0}; + while (points >> x >> z) + patch.outline.emplace_back(x, z); + if (patch.outline.size() >= 3) + Patches.push_back(std::move(patch)); + } + return true; +} + +bool save_patches(std::string const &Path, std::vector const &Patches) +{ + std::ofstream file{Path, std::ios::trunc}; + if (false == file.is_open()) + return false; + file << "# surfaces cut out of the terrain: name, material, repeat, rotation, lift, spacing, kind (paint/surface), transition, noise, waves of the noise, outline x z ... (tabs between the fields)\n"; + char number[64]; + for (auto const &patch : Patches) + { + if (false == patch.follow) + continue; // the ones with heights of their own stay in the manifest + file << patch.name << '\t' << patch.material << '\t' << patch.size << '\t' << patch.rotation << '\t' << patch.lift << '\t' << patch.spacing << '\t' << (patch.paint ? "paint" : "surface") << '\t' + << patch.feather << '\t' << patch.noise << '\t' << patch.noise_scale << '\t'; + for (std::size_t i = 0; i < patch.outline.size(); ++i) + { + std::snprintf(number, sizeof(number), "%s%.2f %.2f", i > 0 ? " " : "", patch.outline[i].x, patch.outline[i].y); + file << number; + } + if (false == patch.shape.empty() || patch.grass != -2) + file << '\t' << patch.shape; + if (patch.grass != -2) + file << '\t' << patch.grass; + file << '\n'; + } + return static_cast(file); +} + +bool surface_patch::height(double const X, double const Z, double &Height) const +{ + if (columns < 2 || rows < 2 || heights.size() != static_cast(columns) * rows) + return false; + auto const u{(X - origin.x) / spacing}; + auto const v{(Z - origin.y) / spacing}; + if (u < -1e-6 || v < -1e-6 || u > columns - 1 + 1e-6 || v > rows - 1 + 1e-6) + return false; + auto const ix{std::clamp(static_cast(std::floor(u)), 0, columns - 2)}; + auto const iz{std::clamp(static_cast(std::floor(v)), 0, rows - 2)}; + auto const fx{std::clamp(u - ix, 0.0, 1.0)}; + auto const fz{std::clamp(v - iz, 0.0, 1.0)}; + auto const at = [&](int const Column, int const Row) { return static_cast(heights[static_cast(Row) * columns + Column]); }; + Height = (at(ix, iz) * (1.0 - fx) + at(ix + 1, iz) * fx) * (1.0 - fz) + (at(ix, iz + 1) * (1.0 - fx) + at(ix + 1, iz + 1) * fx) * fz + lift; + return true; +} + std::vector triangulate(std::vector const &Outline) { std::vector result; diff --git a/scene/heightmapterrain.h b/scene/heightmapterrain.h index 588e2f0d3..b41325fca 100644 --- a/scene/heightmapterrain.h +++ b/scene/heightmapterrain.h @@ -155,6 +155,43 @@ struct water_body std::vector outline; // x, z }; +// piece of the ground cut out of the terrain and drawn on its own with a material of its own (a yard, a platform of beaten earth, a +// field of other crops): the terrain is cut away within the outline, the heights it had there are kept on a grid of the piece, so it +// lies where the ground was and stays as it was cut whatever happens to the terrain later +struct surface_patch +{ + std::string name; + std::string material; // empty: the first material of the palette + float size{0.f}; // metres the texture repeats at; 0: the size given by the material, or 8 m + float rotation{0.f}; // degrees the texture is turned by, counterclockwise seen from above + float lift{0.f}; // metres the surface lies over the heights kept + std::vector outline; // x, z + glm::dvec2 origin{0.0}; // x, z of the first point of the grid + double spacing{1.0}; + int columns{0}; // points along x + int rows{0}; // points along z + std::vector heights; // rows of growing z + // the surface follows the terrain under it (its heights, holes or not) instead of heights of its own, on a grid of the spacing + // laid from 0; the grid and heights above are unused + bool follow{false}; + // painted into the terrain instead (follow is true too): no hole and no mesh of its own, the material laid into the paint of + // the chunks, blending over Feather metres across the outline, the edge shifted by up to Noise metres in waves of Noise_scale + bool paint{false}; + float feather{1.f}; + float noise{0.f}; + float noise_scale{4.f}; + // the points it was drawn with and the options of its outline (curves, handles, along a track), for it to be outlined again as + // it was drawn; empty: the outline itself + std::string shape; + // the 3D grass under a painted surface: -2 left as it grows, -1 taken away, 0 or more: that kind of the grass palette grown there + int grass{-2}; + + // height kept at specified point, interpolated between the points of the grid; false out of the grid + bool height(double X, double Z, double &Height) const; + // x, z of the corners of the box around the outline + void bounds(glm::dvec2 &Low, glm::dvec2 &High) const; +}; + // modifier of the terrain: a corridor along a line (axis of a track or a road) with a formation of specified // height and width, and slopes from its edges to the ground struct corridor_point @@ -174,6 +211,18 @@ struct modifier // portal of a tunnel; otherwise they go round it bool open_start{false}; bool open_end{false}; + // the slopes not drawn with a ruler: the formation and the edges of the track bed stay as designed, the slopes and their foot + // wander and roll as the earth does. All 0: the slopes as designed + struct natural_shape + { + double wander{0.0}; // metres the foot of the slopes wanders in and out by + double scale{15.0}; // about how long the waves of it are along the line, metres + double gentler{0.0}; // up to how much gentler the slopes get than designed, 0.2: up to 1:1.8 of 1:1.5 (never steeper) + double soften{0.0}; // the foot rounded off more, metres of the bend a metre of the height of the slope + double roughness{0.0}; // metres the face of the slope is bumpy by + bool any() const { return wander > 0.0 || gentler > 0.0 || soften > 0.0 || roughness > 0.0; } + }; + natural_shape natural; std::vector points; // rectangle (x, z) the modifier can change the ground in @@ -242,10 +291,18 @@ struct manifest bool compress{true}; // pack files store their data compressed with zstd float spacing{default_spacing}; // point spacing of new chunks std::vector water; + std::vector patches; + // file next to the manifest the patches are kept in, a line each (many of them, as cut along tracks, load faster so); empty: + // in the manifest, unless there are more than patches_inline + std::string patches_file; std::vector modifiers; std::vector grass; // the grass palette }; +// past this many the patches are saved to their own file (manifest::patches_file) +std::size_t constexpr patches_inline{200}; +bool load_patches(std::string const &Path, std::vector &Patches); +bool save_patches(std::string const &Path, std::vector const &Patches); bool load_manifest(std::string const &Path, manifest &Manifest, std::string *Error = nullptr); bool save_manifest(std::string const &Path, manifest const &Manifest, std::string *Error = nullptr);