biome_renderer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. #include "biome_renderer.h"
  2. #include "../../game/systems/building_collision_registry.h"
  3. #include "../gl/buffer.h"
  4. #include "../gl/render_constants.h"
  5. #include "../scene_renderer.h"
  6. #include "gl/resources.h"
  7. #include "ground/grass_gpu.h"
  8. #include "ground_utils.h"
  9. #include "map/terrain.h"
  10. #include <QDebug>
  11. #include <QElapsedTimer>
  12. #include <QVector2D>
  13. #include <algorithm>
  14. #include <cmath>
  15. #include <cstdint>
  16. #include <memory>
  17. #include <optional>
  18. #include <qelapsedtimer.h>
  19. #include <qglobal.h>
  20. #include <qvectornd.h>
  21. #include <vector>
  22. namespace {
  23. using std::uint32_t;
  24. using namespace Render::Ground;
  25. using namespace Render::GL::Geometry;
  26. inline auto valueNoise(float x, float z, uint32_t salt = 0U) -> float {
  27. int const x0 = int(std::floor(x));
  28. int const z0 = int(std::floor(z));
  29. int const x1 = x0 + 1;
  30. int const z1 = z0 + 1;
  31. float const tx = x - float(x0);
  32. float const tz = z - float(z0);
  33. float const n00 = hash_to_01(hash_coords(x0, z0, salt));
  34. float const n10 = hash_to_01(hash_coords(x1, z0, salt));
  35. float const n01 = hash_to_01(hash_coords(x0, z1, salt));
  36. float const n11 = hash_to_01(hash_coords(x1, z1, salt));
  37. float const nx0 = n00 * (1 - tx) + n10 * tx;
  38. float const nx1 = n01 * (1 - tx) + n11 * tx;
  39. return nx0 * (1 - tz) + nx1 * tz;
  40. }
  41. inline auto sectionFor(Game::Map::TerrainType type) -> int {
  42. switch (type) {
  43. case Game::Map::TerrainType::Mountain:
  44. return 2;
  45. case Game::Map::TerrainType::Hill:
  46. return 1;
  47. case Game::Map::TerrainType::Flat:
  48. default:
  49. return 0;
  50. }
  51. }
  52. } // namespace
  53. namespace Render::GL {
  54. BiomeRenderer::BiomeRenderer() = default;
  55. BiomeRenderer::~BiomeRenderer() = default;
  56. void BiomeRenderer::configure(const Game::Map::TerrainHeightMap &height_map,
  57. const Game::Map::BiomeSettings &biomeSettings) {
  58. m_width = height_map.getWidth();
  59. m_height = height_map.getHeight();
  60. m_tile_size = height_map.getTileSize();
  61. m_heightData = height_map.getHeightData();
  62. m_terrain_types = height_map.getTerrainTypes();
  63. m_biomeSettings = biomeSettings;
  64. m_noiseSeed = biomeSettings.seed;
  65. m_grassInstances.clear();
  66. m_grassInstanceBuffer.reset();
  67. m_grassInstanceCount = 0;
  68. m_grassInstancesDirty = false;
  69. m_grassParams.soilColor = m_biomeSettings.soilColor;
  70. m_grassParams.windStrength = m_biomeSettings.sway_strength;
  71. m_grassParams.windSpeed = m_biomeSettings.sway_speed;
  72. m_grassParams.light_direction = QVector3D(0.35F, 0.8F, 0.45F);
  73. m_grassParams.time = 0.0F;
  74. generateGrassInstances();
  75. }
  76. void BiomeRenderer::submit(Renderer &renderer, ResourceManager *resources) {
  77. Q_UNUSED(resources);
  78. if (m_grassInstanceCount > 0) {
  79. if (!m_grassInstanceBuffer) {
  80. m_grassInstanceBuffer = std::make_unique<Buffer>(Buffer::Type::Vertex);
  81. }
  82. if (m_grassInstancesDirty && m_grassInstanceBuffer) {
  83. m_grassInstanceBuffer->setData(m_grassInstances, Buffer::Usage::Static);
  84. m_grassInstancesDirty = false;
  85. }
  86. } else {
  87. m_grassInstanceBuffer.reset();
  88. return;
  89. }
  90. if (m_grassInstanceBuffer && m_grassInstanceCount > 0) {
  91. GrassBatchParams params = m_grassParams;
  92. params.time = renderer.getAnimationTime();
  93. renderer.grassBatch(m_grassInstanceBuffer.get(), m_grassInstanceCount,
  94. params);
  95. }
  96. }
  97. void BiomeRenderer::clear() {
  98. m_grassInstances.clear();
  99. m_grassInstanceBuffer.reset();
  100. m_grassInstanceCount = 0;
  101. m_grassInstancesDirty = false;
  102. }
  103. void BiomeRenderer::refreshGrass() { generateGrassInstances(); }
  104. void BiomeRenderer::generateGrassInstances() {
  105. QElapsedTimer timer;
  106. timer.start();
  107. m_grassInstances.clear();
  108. if (m_width < 2 || m_height < 2 || m_heightData.empty()) {
  109. m_grassInstanceCount = 0;
  110. m_grassInstancesDirty = false;
  111. return;
  112. }
  113. if (m_biomeSettings.patchDensity < 0.01F) {
  114. m_grassInstanceCount = 0;
  115. m_grassInstancesDirty = false;
  116. return;
  117. }
  118. const float half_width = m_width * 0.5F - 0.5F;
  119. const float half_height = m_height * 0.5F - 0.5F;
  120. const float tile_safe = std::max(0.001F, m_tile_size);
  121. const float edge_padding =
  122. std::clamp(m_biomeSettings.spawnEdgePadding, 0.0F, 0.5F);
  123. const float edge_margin_x = static_cast<float>(m_width) * edge_padding;
  124. const float edge_margin_z = static_cast<float>(m_height) * edge_padding;
  125. std::vector<QVector3D> normals(m_width * m_height,
  126. QVector3D(0.0F, 1.0F, 0.0F));
  127. auto sample_height_at = [&](float gx, float gz) -> float {
  128. gx = std::clamp(gx, 0.0F, float(m_width - 1));
  129. gz = std::clamp(gz, 0.0F, float(m_height - 1));
  130. int const x0 = int(std::floor(gx));
  131. int const z0 = int(std::floor(gz));
  132. int const x1 = std::min(x0 + 1, m_width - 1);
  133. int const z1 = std::min(z0 + 1, m_height - 1);
  134. float const tx = gx - float(x0);
  135. float const tz = gz - float(z0);
  136. float const h00 = m_heightData[z0 * m_width + x0];
  137. float const h10 = m_heightData[z0 * m_width + x1];
  138. float const h01 = m_heightData[z1 * m_width + x0];
  139. float const h11 = m_heightData[z1 * m_width + x1];
  140. float const h0 = h00 * (1.0F - tx) + h10 * tx;
  141. float const h1 = h01 * (1.0F - tx) + h11 * tx;
  142. return h0 * (1.0F - tz) + h1 * tz;
  143. };
  144. for (int z = 0; z < m_height; ++z) {
  145. for (int x = 0; x < m_width; ++x) {
  146. int const idx = z * m_width + x;
  147. float const gx0 = std::clamp(float(x) - 1.0F, 0.0F, float(m_width - 1));
  148. float const gx1 = std::clamp(float(x) + 1.0F, 0.0F, float(m_width - 1));
  149. float const gz0 = std::clamp(float(z) - 1.0F, 0.0F, float(m_height - 1));
  150. float const gz1 = std::clamp(float(z) + 1.0F, 0.0F, float(m_height - 1));
  151. float const hL = sample_height_at(gx0, float(z));
  152. float const hR = sample_height_at(gx1, float(z));
  153. float const hD = sample_height_at(float(x), gz0);
  154. float const hU = sample_height_at(float(x), gz1);
  155. QVector3D const dx(2.0F * m_tile_size, hR - hL, 0.0F);
  156. QVector3D const dz(0.0F, hU - hD, 2.0F * m_tile_size);
  157. QVector3D n = QVector3D::crossProduct(dz, dx);
  158. if (n.lengthSquared() > 0.0F) {
  159. n.normalize();
  160. } else {
  161. n = QVector3D(0, 1, 0);
  162. }
  163. normals[idx] = n;
  164. }
  165. }
  166. auto add_grass_blade = [&](float gx, float gz, uint32_t &state) {
  167. if (gx < edge_margin_x || gx > m_width - 1 - edge_margin_x ||
  168. gz < edge_margin_z || gz > m_height - 1 - edge_margin_z) {
  169. return false;
  170. }
  171. float const sgx = std::clamp(gx, 0.0F, float(m_width - 1));
  172. float const sgz = std::clamp(gz, 0.0F, float(m_height - 1));
  173. int const ix = std::clamp(int(std::floor(sgx + 0.5F)), 0, m_width - 1);
  174. int const iz = std::clamp(int(std::floor(sgz + 0.5F)), 0, m_height - 1);
  175. int const normal_idx = iz * m_width + ix;
  176. if (m_terrain_types[normal_idx] == Game::Map::TerrainType::Mountain ||
  177. m_terrain_types[normal_idx] == Game::Map::TerrainType::Hill) {
  178. return false;
  179. }
  180. if (m_terrain_types[normal_idx] == Game::Map::TerrainType::River) {
  181. return false;
  182. }
  183. constexpr int k_river_margin = 1;
  184. int near_river_count = 0;
  185. for (int dz = -k_river_margin; dz <= k_river_margin; ++dz) {
  186. for (int dx = -k_river_margin; dx <= k_river_margin; ++dx) {
  187. if (dx == 0 && dz == 0) {
  188. continue;
  189. }
  190. int const nx = ix + dx;
  191. int const nz = iz + dz;
  192. if (nx >= 0 && nx < m_width && nz >= 0 && nz < m_height) {
  193. int const nIdx = nz * m_width + nx;
  194. if (m_terrain_types[nIdx] == Game::Map::TerrainType::River) {
  195. near_river_count++;
  196. }
  197. }
  198. }
  199. }
  200. if (near_river_count > 0) {
  201. float const riverbank_density = 0.15F;
  202. if (rand_01(state) > riverbank_density) {
  203. return false;
  204. }
  205. }
  206. QVector3D const normal = normals[normal_idx];
  207. float const slope = 1.0F - std::clamp(normal.y(), 0.0F, 1.0F);
  208. if (slope > 0.92F) {
  209. return false;
  210. }
  211. float const world_x = (gx - half_width) * m_tile_size;
  212. float const world_z = (gz - half_height) * m_tile_size;
  213. float const world_y = sample_height_at(sgx, sgz);
  214. auto &building_registry =
  215. Game::Systems::BuildingCollisionRegistry::instance();
  216. if (building_registry.isPointInBuilding(world_x, world_z)) {
  217. return false;
  218. }
  219. float const lush_noise =
  220. valueNoise(world_x * 0.06F, world_z * 0.06F, m_noiseSeed ^ 0x9235U);
  221. float const dryness_noise =
  222. valueNoise(world_x * 0.12F, world_z * 0.12F, m_noiseSeed ^ 0x47d2U);
  223. float const dryness =
  224. std::clamp(dryness_noise * 0.6F + slope * 0.4F, 0.0F, 1.0F);
  225. QVector3D const lush_mix =
  226. m_biomeSettings.grassPrimary * (1.0F - lush_noise) +
  227. m_biomeSettings.grassSecondary * lush_noise;
  228. QVector3D const color =
  229. lush_mix * (1.0F - dryness) + m_biomeSettings.grassDry * dryness;
  230. float const height = remap(rand_01(state), m_biomeSettings.bladeHeightMin,
  231. m_biomeSettings.bladeHeightMax) *
  232. tile_safe * 0.5F;
  233. float const width = remap(rand_01(state), m_biomeSettings.bladeWidthMin,
  234. m_biomeSettings.bladeWidthMax) *
  235. tile_safe;
  236. float const sway_strength = remap(rand_01(state), 0.75F, 1.25F);
  237. float const sway_speed = remap(rand_01(state), 0.85F, 1.15F);
  238. float const sway_phase = rand_01(state) * MathConstants::k_two_pi;
  239. float const orientation = rand_01(state) * MathConstants::k_two_pi;
  240. GrassInstanceGpu instance;
  241. instance.posHeight = QVector4D(world_x, world_y, world_z, height);
  242. instance.colorWidth = QVector4D(color.x(), color.y(), color.z(), width);
  243. instance.swayParams =
  244. QVector4D(sway_strength, sway_speed, sway_phase, orientation);
  245. m_grassInstances.push_back(instance);
  246. return true;
  247. };
  248. auto quad_section = [&](Game::Map::TerrainType a, Game::Map::TerrainType b,
  249. Game::Map::TerrainType c, Game::Map::TerrainType d) {
  250. int const priority_a = sectionFor(a);
  251. int const priority_b = sectionFor(b);
  252. int const priority_c = sectionFor(c);
  253. int const priority_d = sectionFor(d);
  254. int result = priority_a;
  255. result = std::max(result, priority_b);
  256. result = std::max(result, priority_c);
  257. result = std::max(result, priority_d);
  258. return result;
  259. };
  260. const int chunk_size = DefaultChunkSize;
  261. for (int chunk_z = 0; chunk_z < m_height - 1; chunk_z += chunk_size) {
  262. int const chunk_max_z = std::min(chunk_z + chunk_size, m_height - 1);
  263. for (int chunk_x = 0; chunk_x < m_width - 1; chunk_x += chunk_size) {
  264. int const chunk_max_x = std::min(chunk_x + chunk_size, m_width - 1);
  265. int flat_count = 0;
  266. int hill_count = 0;
  267. int mountain_count = 0;
  268. float chunk_height_sum = 0.0F;
  269. float chunk_slope_sum = 0.0F;
  270. int sample_count = 0;
  271. for (int z = chunk_z; z < chunk_max_z && z < m_height - 1; ++z) {
  272. for (int x = chunk_x; x < chunk_max_x && x < m_width - 1; ++x) {
  273. int const idx0 = z * m_width + x;
  274. int const idx1 = idx0 + 1;
  275. int const idx2 = (z + 1) * m_width + x;
  276. int const idx3 = idx2 + 1;
  277. if (m_terrain_types[idx0] == Game::Map::TerrainType::Mountain ||
  278. m_terrain_types[idx1] == Game::Map::TerrainType::Mountain ||
  279. m_terrain_types[idx2] == Game::Map::TerrainType::Mountain ||
  280. m_terrain_types[idx3] == Game::Map::TerrainType::Mountain ||
  281. m_terrain_types[idx0] == Game::Map::TerrainType::River ||
  282. m_terrain_types[idx1] == Game::Map::TerrainType::River ||
  283. m_terrain_types[idx2] == Game::Map::TerrainType::River ||
  284. m_terrain_types[idx3] == Game::Map::TerrainType::River) {
  285. mountain_count++;
  286. } else if (m_terrain_types[idx0] == Game::Map::TerrainType::Hill ||
  287. m_terrain_types[idx1] == Game::Map::TerrainType::Hill ||
  288. m_terrain_types[idx2] == Game::Map::TerrainType::Hill ||
  289. m_terrain_types[idx3] == Game::Map::TerrainType::Hill) {
  290. hill_count++;
  291. } else {
  292. flat_count++;
  293. }
  294. float const quad_height = (m_heightData[idx0] + m_heightData[idx1] +
  295. m_heightData[idx2] + m_heightData[idx3]) *
  296. 0.25F;
  297. chunk_height_sum += quad_height;
  298. float const nY = (normals[idx0].y() + normals[idx1].y() +
  299. normals[idx2].y() + normals[idx3].y()) *
  300. 0.25F;
  301. chunk_slope_sum += 1.0F - std::clamp(nY, 0.0F, 1.0F);
  302. sample_count++;
  303. }
  304. }
  305. if (sample_count == 0) {
  306. continue;
  307. }
  308. const float usable_coverage =
  309. sample_count > 0
  310. ? float(flat_count + hill_count) / float(sample_count)
  311. : 0.0F;
  312. if (usable_coverage < 0.05F) {
  313. continue;
  314. }
  315. bool const is_primarily_flat = flat_count >= hill_count;
  316. float const avg_slope = chunk_slope_sum / float(sample_count);
  317. uint32_t state = hash_coords(chunk_x, chunk_z, m_noiseSeed ^ 0xC915872BU);
  318. float const slope_penalty =
  319. 1.0F - std::clamp(avg_slope * 1.35F, 0.0F, 0.75F);
  320. float const type_bias = 1.0F;
  321. constexpr float k_cluster_boost = 1.35F;
  322. float const expected_clusters =
  323. std::max(0.0F, m_biomeSettings.patchDensity * k_cluster_boost *
  324. slope_penalty * type_bias * usable_coverage);
  325. int cluster_count = static_cast<int>(std::floor(expected_clusters));
  326. float const frac = expected_clusters - float(cluster_count);
  327. if (rand_01(state) < frac) {
  328. cluster_count += 1;
  329. }
  330. if (cluster_count > 0) {
  331. auto chunk_span_x = float(chunk_max_x - chunk_x + 1);
  332. auto chunk_span_z = float(chunk_max_z - chunk_z + 1);
  333. float const scatter_base = std::max(0.25F, m_biomeSettings.patchJitter);
  334. auto pick_cluster_center =
  335. [&](uint32_t &rng) -> std::optional<QVector2D> {
  336. constexpr int k_max_attempts = 8;
  337. for (int attempt = 0; attempt < k_max_attempts; ++attempt) {
  338. float const candidate_gx =
  339. float(chunk_x) + rand_01(rng) * chunk_span_x;
  340. float const candidate_gz =
  341. float(chunk_z) + rand_01(rng) * chunk_span_z;
  342. int const cx =
  343. std::clamp(int(std::round(candidate_gx)), 0, m_width - 1);
  344. int const cz =
  345. std::clamp(int(std::round(candidate_gz)), 0, m_height - 1);
  346. int const center_idx = cz * m_width + cx;
  347. if (m_terrain_types[center_idx] ==
  348. Game::Map::TerrainType::Mountain ||
  349. m_terrain_types[center_idx] == Game::Map::TerrainType::River) {
  350. continue;
  351. }
  352. QVector3D const center_normal = normals[center_idx];
  353. float const center_slope =
  354. 1.0F - std::clamp(center_normal.y(), 0.0F, 1.0F);
  355. if (center_slope > 0.92F) {
  356. continue;
  357. }
  358. return QVector2D(candidate_gx, candidate_gz);
  359. }
  360. return std::nullopt;
  361. };
  362. for (int cluster = 0; cluster < cluster_count; ++cluster) {
  363. auto center = pick_cluster_center(state);
  364. if (!center) {
  365. continue;
  366. }
  367. float const center_gx = center->x();
  368. float const center_gz = center->y();
  369. int blades = 6 + static_cast<int>(rand_01(state) * 6.0F);
  370. blades = std::max(
  371. 4, int(std::round(blades * (0.85F + 0.3F * rand_01(state)))));
  372. float const scatter_radius =
  373. (0.45F + 0.55F * rand_01(state)) * scatter_base * tile_safe;
  374. for (int blade = 0; blade < blades; ++blade) {
  375. float const angle = rand_01(state) * MathConstants::k_two_pi;
  376. float const radius = scatter_radius * std::sqrt(rand_01(state));
  377. float const gx = center_gx + std::cos(angle) * radius / tile_safe;
  378. float const gz = center_gz + std::sin(angle) * radius / tile_safe;
  379. add_grass_blade(gx, gz, state);
  380. }
  381. }
  382. }
  383. }
  384. }
  385. const float background_density =
  386. std::max(0.0F, m_biomeSettings.backgroundBladeDensity);
  387. if (background_density > 0.0F) {
  388. for (int z = 0; z < m_height; ++z) {
  389. for (int x = 0; x < m_width; ++x) {
  390. int const idx = z * m_width + x;
  391. if (m_terrain_types[idx] == Game::Map::TerrainType::Mountain ||
  392. m_terrain_types[idx] == Game::Map::TerrainType::Hill ||
  393. m_terrain_types[idx] == Game::Map::TerrainType::River) {
  394. continue;
  395. }
  396. QVector3D const normal = normals[idx];
  397. float const slope = 1.0F - std::clamp(normal.y(), 0.0F, 1.0F);
  398. if (slope > 0.95F) {
  399. continue;
  400. }
  401. uint32_t state = hash_coords(
  402. x, z, m_noiseSeed ^ 0x51bda7U ^ static_cast<uint32_t>(idx));
  403. int base_count = static_cast<int>(std::floor(background_density));
  404. float const frac = background_density - float(base_count);
  405. if (rand_01(state) < frac) {
  406. base_count += 1;
  407. }
  408. for (int i = 0; i < base_count; ++i) {
  409. float const gx = float(x) + rand_01(state);
  410. float const gz = float(z) + rand_01(state);
  411. add_grass_blade(gx, gz, state);
  412. }
  413. }
  414. }
  415. }
  416. m_grassInstanceCount = m_grassInstances.size();
  417. m_grassInstancesDirty = m_grassInstanceCount > 0;
  418. int debug_flat_count = 0;
  419. int debug_hill_count = 0;
  420. int debug_mountain_count = 0;
  421. for (const auto &type : m_terrain_types) {
  422. if (type == Game::Map::TerrainType::Flat) {
  423. debug_flat_count++;
  424. } else if (type == Game::Map::TerrainType::Hill) {
  425. debug_hill_count++;
  426. } else if (type == Game::Map::TerrainType::Mountain) {
  427. debug_mountain_count++;
  428. }
  429. }
  430. }
  431. } // namespace Render::GL