biome_renderer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. #include "biome_renderer.h"
  2. #include "../../game/systems/building_collision_registry.h"
  3. #include "../gl/buffer.h"
  4. #include "../scene_renderer.h"
  5. #include <QDebug>
  6. #include <QElapsedTimer>
  7. #include <QVector2D>
  8. #include <algorithm>
  9. #include <array>
  10. #include <cmath>
  11. #include <optional>
  12. namespace {
  13. using std::uint32_t;
  14. inline uint32_t hashCoords(int x, int z, uint32_t salt = 0u) {
  15. uint32_t ux = static_cast<uint32_t>(x * 73856093);
  16. uint32_t uz = static_cast<uint32_t>(z * 19349663);
  17. return ux ^ uz ^ (salt * 83492791u);
  18. }
  19. inline float rand01(uint32_t &state) {
  20. state = state * 1664525u + 1013904223u;
  21. return static_cast<float>((state >> 8) & 0xFFFFFF) /
  22. static_cast<float>(0xFFFFFF);
  23. }
  24. inline float remap(float value, float minOut, float maxOut) {
  25. return minOut + (maxOut - minOut) * value;
  26. }
  27. inline float hashTo01(uint32_t h) {
  28. h ^= h >> 17;
  29. h *= 0xed5ad4bbu;
  30. h ^= h >> 11;
  31. h *= 0xac4c1b51u;
  32. h ^= h >> 15;
  33. h *= 0x31848babu;
  34. h ^= h >> 14;
  35. return (h & 0x00FFFFFFu) / float(0x01000000);
  36. }
  37. inline float valueNoise(float x, float z, uint32_t salt = 0u) {
  38. int x0 = int(std::floor(x)), z0 = int(std::floor(z));
  39. int x1 = x0 + 1, z1 = z0 + 1;
  40. float tx = x - float(x0), tz = z - float(z0);
  41. float n00 = hashTo01(hashCoords(x0, z0, salt));
  42. float n10 = hashTo01(hashCoords(x1, z0, salt));
  43. float n01 = hashTo01(hashCoords(x0, z1, salt));
  44. float n11 = hashTo01(hashCoords(x1, z1, salt));
  45. float nx0 = n00 * (1 - tx) + n10 * tx;
  46. float nx1 = n01 * (1 - tx) + n11 * tx;
  47. return nx0 * (1 - tz) + nx1 * tz;
  48. }
  49. inline int sectionFor(Game::Map::TerrainType type) {
  50. switch (type) {
  51. case Game::Map::TerrainType::Mountain:
  52. return 2;
  53. case Game::Map::TerrainType::Hill:
  54. return 1;
  55. case Game::Map::TerrainType::Flat:
  56. default:
  57. return 0;
  58. }
  59. }
  60. } // namespace
  61. namespace Render::GL {
  62. BiomeRenderer::BiomeRenderer() = default;
  63. BiomeRenderer::~BiomeRenderer() = default;
  64. void BiomeRenderer::configure(const Game::Map::TerrainHeightMap &heightMap,
  65. const Game::Map::BiomeSettings &biomeSettings) {
  66. m_width = heightMap.getWidth();
  67. m_height = heightMap.getHeight();
  68. m_tileSize = heightMap.getTileSize();
  69. m_heightData = heightMap.getHeightData();
  70. m_terrainTypes = heightMap.getTerrainTypes();
  71. m_biomeSettings = biomeSettings;
  72. m_noiseSeed = biomeSettings.seed;
  73. m_grassInstances.clear();
  74. m_grassInstanceBuffer.reset();
  75. m_grassInstanceCount = 0;
  76. m_grassInstancesDirty = false;
  77. m_grassParams.soilColor = m_biomeSettings.soilColor;
  78. m_grassParams.windStrength = m_biomeSettings.swayStrength;
  79. m_grassParams.windSpeed = m_biomeSettings.swaySpeed;
  80. m_grassParams.lightDirection = QVector3D(0.35f, 0.8f, 0.45f);
  81. m_grassParams.time = 0.0f;
  82. generateGrassInstances();
  83. }
  84. void BiomeRenderer::submit(Renderer &renderer, ResourceManager *resources) {
  85. Q_UNUSED(resources);
  86. if (m_grassInstanceCount > 0) {
  87. if (!m_grassInstanceBuffer) {
  88. m_grassInstanceBuffer = std::make_unique<Buffer>(Buffer::Type::Vertex);
  89. }
  90. if (m_grassInstancesDirty && m_grassInstanceBuffer) {
  91. m_grassInstanceBuffer->setData(m_grassInstances, Buffer::Usage::Static);
  92. m_grassInstancesDirty = false;
  93. }
  94. } else {
  95. m_grassInstanceBuffer.reset();
  96. return;
  97. }
  98. if (m_grassInstanceBuffer && m_grassInstanceCount > 0) {
  99. GrassBatchParams params = m_grassParams;
  100. params.time = renderer.getAnimationTime();
  101. renderer.grassBatch(m_grassInstanceBuffer.get(), m_grassInstanceCount,
  102. params);
  103. }
  104. }
  105. void BiomeRenderer::clear() {
  106. m_grassInstances.clear();
  107. m_grassInstanceBuffer.reset();
  108. m_grassInstanceCount = 0;
  109. m_grassInstancesDirty = false;
  110. }
  111. void BiomeRenderer::refreshGrass() { generateGrassInstances(); }
  112. void BiomeRenderer::generateGrassInstances() {
  113. QElapsedTimer timer;
  114. timer.start();
  115. m_grassInstances.clear();
  116. if (m_width < 2 || m_height < 2 || m_heightData.empty()) {
  117. m_grassInstanceCount = 0;
  118. m_grassInstancesDirty = false;
  119. return;
  120. }
  121. if (m_biomeSettings.patchDensity < 0.01f) {
  122. m_grassInstanceCount = 0;
  123. m_grassInstancesDirty = false;
  124. return;
  125. }
  126. const float halfWidth = m_width * 0.5f - 0.5f;
  127. const float halfHeight = m_height * 0.5f - 0.5f;
  128. const float tileSafe = std::max(0.001f, m_tileSize);
  129. const float edgePadding =
  130. std::clamp(m_biomeSettings.spawnEdgePadding, 0.0f, 0.5f);
  131. const float edgeMarginX = static_cast<float>(m_width) * edgePadding;
  132. const float edgeMarginZ = static_cast<float>(m_height) * edgePadding;
  133. std::vector<QVector3D> normals(m_width * m_height,
  134. QVector3D(0.0f, 1.0f, 0.0f));
  135. auto sampleHeightAt = [&](float gx, float gz) -> float {
  136. gx = std::clamp(gx, 0.0f, float(m_width - 1));
  137. gz = std::clamp(gz, 0.0f, float(m_height - 1));
  138. int x0 = int(std::floor(gx));
  139. int z0 = int(std::floor(gz));
  140. int x1 = std::min(x0 + 1, m_width - 1);
  141. int z1 = std::min(z0 + 1, m_height - 1);
  142. float tx = gx - float(x0);
  143. float tz = gz - float(z0);
  144. float h00 = m_heightData[z0 * m_width + x0];
  145. float h10 = m_heightData[z0 * m_width + x1];
  146. float h01 = m_heightData[z1 * m_width + x0];
  147. float h11 = m_heightData[z1 * m_width + x1];
  148. float h0 = h00 * (1.0f - tx) + h10 * tx;
  149. float h1 = h01 * (1.0f - tx) + h11 * tx;
  150. return h0 * (1.0f - tz) + h1 * tz;
  151. };
  152. for (int z = 0; z < m_height; ++z) {
  153. for (int x = 0; x < m_width; ++x) {
  154. int idx = z * m_width + x;
  155. float gx0 = std::clamp(float(x) - 1.0f, 0.0f, float(m_width - 1));
  156. float gx1 = std::clamp(float(x) + 1.0f, 0.0f, float(m_width - 1));
  157. float gz0 = std::clamp(float(z) - 1.0f, 0.0f, float(m_height - 1));
  158. float gz1 = std::clamp(float(z) + 1.0f, 0.0f, float(m_height - 1));
  159. float hL = sampleHeightAt(gx0, float(z));
  160. float hR = sampleHeightAt(gx1, float(z));
  161. float hD = sampleHeightAt(float(x), gz0);
  162. float hU = sampleHeightAt(float(x), gz1);
  163. QVector3D dx(2.0f * m_tileSize, hR - hL, 0.0f);
  164. QVector3D dz(0.0f, hU - hD, 2.0f * m_tileSize);
  165. QVector3D n = QVector3D::crossProduct(dz, dx);
  166. if (n.lengthSquared() > 0.0f) {
  167. n.normalize();
  168. } else {
  169. n = QVector3D(0, 1, 0);
  170. }
  171. normals[idx] = n;
  172. }
  173. }
  174. auto addGrassBlade = [&](float gx, float gz, uint32_t &state) {
  175. if (gx < edgeMarginX || gx > m_width - 1 - edgeMarginX ||
  176. gz < edgeMarginZ || gz > m_height - 1 - edgeMarginZ) {
  177. return false;
  178. }
  179. float sgx = std::clamp(gx, 0.0f, float(m_width - 1));
  180. float sgz = std::clamp(gz, 0.0f, float(m_height - 1));
  181. int ix = std::clamp(int(std::floor(sgx + 0.5f)), 0, m_width - 1);
  182. int iz = std::clamp(int(std::floor(sgz + 0.5f)), 0, m_height - 1);
  183. int normalIdx = iz * m_width + ix;
  184. if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::Mountain ||
  185. m_terrainTypes[normalIdx] == Game::Map::TerrainType::Hill)
  186. return false;
  187. if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::River)
  188. return false;
  189. constexpr int kRiverMargin = 1;
  190. int nearRiverCount = 0;
  191. for (int dz = -kRiverMargin; dz <= kRiverMargin; ++dz) {
  192. for (int dx = -kRiverMargin; dx <= kRiverMargin; ++dx) {
  193. if (dx == 0 && dz == 0)
  194. continue;
  195. int nx = ix + dx;
  196. int nz = iz + dz;
  197. if (nx >= 0 && nx < m_width && nz >= 0 && nz < m_height) {
  198. int nIdx = nz * m_width + nx;
  199. if (m_terrainTypes[nIdx] == Game::Map::TerrainType::River)
  200. nearRiverCount++;
  201. }
  202. }
  203. }
  204. if (nearRiverCount > 0) {
  205. float riverbankDensity = 0.15f;
  206. if (rand01(state) > riverbankDensity)
  207. return false;
  208. }
  209. QVector3D normal = normals[normalIdx];
  210. float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
  211. if (slope > 0.92f)
  212. return false;
  213. float worldX = (gx - halfWidth) * m_tileSize;
  214. float worldZ = (gz - halfHeight) * m_tileSize;
  215. float worldY = sampleHeightAt(sgx, sgz);
  216. auto &buildingRegistry =
  217. Game::Systems::BuildingCollisionRegistry::instance();
  218. if (buildingRegistry.isPointInBuilding(worldX, worldZ)) {
  219. return false;
  220. }
  221. float lushNoise =
  222. valueNoise(worldX * 0.06f, worldZ * 0.06f, m_noiseSeed ^ 0x9235u);
  223. float drynessNoise =
  224. valueNoise(worldX * 0.12f, worldZ * 0.12f, m_noiseSeed ^ 0x47d2u);
  225. float dryness = std::clamp(drynessNoise * 0.6f + slope * 0.4f, 0.0f, 1.0f);
  226. QVector3D lushMix = m_biomeSettings.grassPrimary * (1.0f - lushNoise) +
  227. m_biomeSettings.grassSecondary * lushNoise;
  228. QVector3D color =
  229. lushMix * (1.0f - dryness) + m_biomeSettings.grassDry * dryness;
  230. float height = remap(rand01(state), m_biomeSettings.bladeHeightMin,
  231. m_biomeSettings.bladeHeightMax) *
  232. tileSafe * 0.5f;
  233. float width = remap(rand01(state), m_biomeSettings.bladeWidthMin,
  234. m_biomeSettings.bladeWidthMax) *
  235. tileSafe;
  236. float swayStrength = remap(rand01(state), 0.75f, 1.25f);
  237. float swaySpeed = remap(rand01(state), 0.85f, 1.15f);
  238. float swayPhase = rand01(state) * 6.2831853f;
  239. float orientation = rand01(state) * 6.2831853f;
  240. GrassInstanceGpu instance;
  241. instance.posHeight = QVector4D(worldX, worldY, worldZ, height);
  242. instance.colorWidth = QVector4D(color.x(), color.y(), color.z(), width);
  243. instance.swayParams =
  244. QVector4D(swayStrength, swaySpeed, swayPhase, orientation);
  245. m_grassInstances.push_back(instance);
  246. return true;
  247. };
  248. auto quadSection = [&](Game::Map::TerrainType a, Game::Map::TerrainType b,
  249. Game::Map::TerrainType c, Game::Map::TerrainType d) {
  250. int priorityA = sectionFor(a);
  251. int priorityB = sectionFor(b);
  252. int priorityC = sectionFor(c);
  253. int priorityD = sectionFor(d);
  254. int result = priorityA;
  255. result = std::max(result, priorityB);
  256. result = std::max(result, priorityC);
  257. result = std::max(result, priorityD);
  258. return result;
  259. };
  260. const int chunkSize = 16;
  261. for (int chunkZ = 0; chunkZ < m_height - 1; chunkZ += chunkSize) {
  262. int chunkMaxZ = std::min(chunkZ + chunkSize, m_height - 1);
  263. for (int chunkX = 0; chunkX < m_width - 1; chunkX += chunkSize) {
  264. int chunkMaxX = std::min(chunkX + chunkSize, m_width - 1);
  265. int flatCount = 0;
  266. int hillCount = 0;
  267. int mountainCount = 0;
  268. float chunkHeightSum = 0.0f;
  269. float chunkSlopeSum = 0.0f;
  270. int sampleCount = 0;
  271. for (int z = chunkZ; z < chunkMaxZ && z < m_height - 1; ++z) {
  272. for (int x = chunkX; x < chunkMaxX && x < m_width - 1; ++x) {
  273. int idx0 = z * m_width + x;
  274. int idx1 = idx0 + 1;
  275. int idx2 = (z + 1) * m_width + x;
  276. int idx3 = idx2 + 1;
  277. if (m_terrainTypes[idx0] == Game::Map::TerrainType::Mountain ||
  278. m_terrainTypes[idx1] == Game::Map::TerrainType::Mountain ||
  279. m_terrainTypes[idx2] == Game::Map::TerrainType::Mountain ||
  280. m_terrainTypes[idx3] == Game::Map::TerrainType::Mountain ||
  281. m_terrainTypes[idx0] == Game::Map::TerrainType::River ||
  282. m_terrainTypes[idx1] == Game::Map::TerrainType::River ||
  283. m_terrainTypes[idx2] == Game::Map::TerrainType::River ||
  284. m_terrainTypes[idx3] == Game::Map::TerrainType::River) {
  285. mountainCount++;
  286. } else if (m_terrainTypes[idx0] == Game::Map::TerrainType::Hill ||
  287. m_terrainTypes[idx1] == Game::Map::TerrainType::Hill ||
  288. m_terrainTypes[idx2] == Game::Map::TerrainType::Hill ||
  289. m_terrainTypes[idx3] == Game::Map::TerrainType::Hill) {
  290. hillCount++;
  291. } else {
  292. flatCount++;
  293. }
  294. float quadHeight = (m_heightData[idx0] + m_heightData[idx1] +
  295. m_heightData[idx2] + m_heightData[idx3]) *
  296. 0.25f;
  297. chunkHeightSum += quadHeight;
  298. float nY = (normals[idx0].y() + normals[idx1].y() +
  299. normals[idx2].y() + normals[idx3].y()) *
  300. 0.25f;
  301. chunkSlopeSum += 1.0f - std::clamp(nY, 0.0f, 1.0f);
  302. sampleCount++;
  303. }
  304. }
  305. if (sampleCount == 0)
  306. continue;
  307. const float usableCoverage =
  308. sampleCount > 0 ? float(flatCount + hillCount) / float(sampleCount)
  309. : 0.0f;
  310. if (usableCoverage < 0.05f)
  311. continue;
  312. bool isPrimarilyFlat = flatCount >= hillCount;
  313. float avgSlope = chunkSlopeSum / float(sampleCount);
  314. uint32_t state = hashCoords(chunkX, chunkZ, m_noiseSeed ^ 0xC915872Bu);
  315. float slopePenalty = 1.0f - std::clamp(avgSlope * 1.35f, 0.0f, 0.75f);
  316. float typeBias = 1.0f;
  317. constexpr float kClusterBoost = 1.35f;
  318. float expectedClusters =
  319. std::max(0.0f, m_biomeSettings.patchDensity * kClusterBoost *
  320. slopePenalty * typeBias * usableCoverage);
  321. int clusterCount = static_cast<int>(std::floor(expectedClusters));
  322. float frac = expectedClusters - float(clusterCount);
  323. if (rand01(state) < frac)
  324. clusterCount += 1;
  325. if (clusterCount > 0) {
  326. float chunkSpanX = float(chunkMaxX - chunkX + 1);
  327. float chunkSpanZ = float(chunkMaxZ - chunkZ + 1);
  328. float scatterBase = std::max(0.25f, m_biomeSettings.patchJitter);
  329. auto pickClusterCenter =
  330. [&](uint32_t &rng) -> std::optional<QVector2D> {
  331. constexpr int kMaxAttempts = 8;
  332. for (int attempt = 0; attempt < kMaxAttempts; ++attempt) {
  333. float candidateGX = float(chunkX) + rand01(rng) * chunkSpanX;
  334. float candidateGZ = float(chunkZ) + rand01(rng) * chunkSpanZ;
  335. int cx = std::clamp(int(std::round(candidateGX)), 0, m_width - 1);
  336. int cz = std::clamp(int(std::round(candidateGZ)), 0, m_height - 1);
  337. int centerIdx = cz * m_width + cx;
  338. if (m_terrainTypes[centerIdx] == Game::Map::TerrainType::Mountain ||
  339. m_terrainTypes[centerIdx] == Game::Map::TerrainType::River)
  340. continue;
  341. QVector3D centerNormal = normals[centerIdx];
  342. float centerSlope = 1.0f - std::clamp(centerNormal.y(), 0.0f, 1.0f);
  343. if (centerSlope > 0.92f)
  344. continue;
  345. return QVector2D(candidateGX, candidateGZ);
  346. }
  347. return std::nullopt;
  348. };
  349. for (int cluster = 0; cluster < clusterCount; ++cluster) {
  350. auto center = pickClusterCenter(state);
  351. if (!center)
  352. continue;
  353. float centerGX = center->x();
  354. float centerGZ = center->y();
  355. int blades = 6 + static_cast<int>(rand01(state) * 6.0f);
  356. blades = std::max(
  357. 4, int(std::round(blades * (0.85f + 0.3f * rand01(state)))));
  358. float scatterRadius =
  359. (0.45f + 0.55f * rand01(state)) * scatterBase * tileSafe;
  360. for (int blade = 0; blade < blades; ++blade) {
  361. float angle = rand01(state) * 6.2831853f;
  362. float radius = scatterRadius * std::sqrt(rand01(state));
  363. float gx = centerGX + std::cos(angle) * radius / tileSafe;
  364. float gz = centerGZ + std::sin(angle) * radius / tileSafe;
  365. addGrassBlade(gx, gz, state);
  366. }
  367. }
  368. }
  369. }
  370. }
  371. const float backgroundDensity =
  372. std::max(0.0f, m_biomeSettings.backgroundBladeDensity);
  373. if (backgroundDensity > 0.0f) {
  374. for (int z = 0; z < m_height; ++z) {
  375. for (int x = 0; x < m_width; ++x) {
  376. int idx = z * m_width + x;
  377. if (m_terrainTypes[idx] == Game::Map::TerrainType::Mountain ||
  378. m_terrainTypes[idx] == Game::Map::TerrainType::Hill ||
  379. m_terrainTypes[idx] == Game::Map::TerrainType::River)
  380. continue;
  381. QVector3D normal = normals[idx];
  382. float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
  383. if (slope > 0.95f)
  384. continue;
  385. uint32_t state = hashCoords(
  386. x, z, m_noiseSeed ^ 0x51bda7u ^ static_cast<uint32_t>(idx));
  387. int baseCount = static_cast<int>(std::floor(backgroundDensity));
  388. float frac = backgroundDensity - float(baseCount);
  389. if (rand01(state) < frac)
  390. baseCount += 1;
  391. for (int i = 0; i < baseCount; ++i) {
  392. float gx = float(x) + rand01(state);
  393. float gz = float(z) + rand01(state);
  394. addGrassBlade(gx, gz, state);
  395. }
  396. }
  397. }
  398. }
  399. m_grassInstanceCount = m_grassInstances.size();
  400. m_grassInstancesDirty = m_grassInstanceCount > 0;
  401. int debugFlatCount = 0;
  402. int debugHillCount = 0;
  403. int debugMountainCount = 0;
  404. for (const auto &type : m_terrainTypes) {
  405. if (type == Game::Map::TerrainType::Flat)
  406. debugFlatCount++;
  407. else if (type == Game::Map::TerrainType::Hill)
  408. debugHillCount++;
  409. else if (type == Game::Map::TerrainType::Mountain)
  410. debugMountainCount++;
  411. }
  412. }
  413. } // namespace Render::GL