biome_renderer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. }
  188. if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::River) {
  189. return false;
  190. }
  191. constexpr int kRiverMargin = 1;
  192. int nearRiverCount = 0;
  193. for (int dz = -kRiverMargin; dz <= kRiverMargin; ++dz) {
  194. for (int dx = -kRiverMargin; dx <= kRiverMargin; ++dx) {
  195. if (dx == 0 && dz == 0) {
  196. continue;
  197. }
  198. int nx = ix + dx;
  199. int nz = iz + dz;
  200. if (nx >= 0 && nx < m_width && nz >= 0 && nz < m_height) {
  201. int nIdx = nz * m_width + nx;
  202. if (m_terrainTypes[nIdx] == Game::Map::TerrainType::River) {
  203. nearRiverCount++;
  204. }
  205. }
  206. }
  207. }
  208. if (nearRiverCount > 0) {
  209. float riverbankDensity = 0.15f;
  210. if (rand01(state) > riverbankDensity) {
  211. return false;
  212. }
  213. }
  214. QVector3D normal = normals[normalIdx];
  215. float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
  216. if (slope > 0.92f) {
  217. return false;
  218. }
  219. float worldX = (gx - halfWidth) * m_tileSize;
  220. float worldZ = (gz - halfHeight) * m_tileSize;
  221. float worldY = sampleHeightAt(sgx, sgz);
  222. auto &buildingRegistry =
  223. Game::Systems::BuildingCollisionRegistry::instance();
  224. if (buildingRegistry.isPointInBuilding(worldX, worldZ)) {
  225. return false;
  226. }
  227. float lushNoise =
  228. valueNoise(worldX * 0.06f, worldZ * 0.06f, m_noiseSeed ^ 0x9235u);
  229. float drynessNoise =
  230. valueNoise(worldX * 0.12f, worldZ * 0.12f, m_noiseSeed ^ 0x47d2u);
  231. float dryness = std::clamp(drynessNoise * 0.6f + slope * 0.4f, 0.0f, 1.0f);
  232. QVector3D lushMix = m_biomeSettings.grassPrimary * (1.0f - lushNoise) +
  233. m_biomeSettings.grassSecondary * lushNoise;
  234. QVector3D color =
  235. lushMix * (1.0f - dryness) + m_biomeSettings.grassDry * dryness;
  236. float height = remap(rand01(state), m_biomeSettings.bladeHeightMin,
  237. m_biomeSettings.bladeHeightMax) *
  238. tileSafe * 0.5f;
  239. float width = remap(rand01(state), m_biomeSettings.bladeWidthMin,
  240. m_biomeSettings.bladeWidthMax) *
  241. tileSafe;
  242. float swayStrength = remap(rand01(state), 0.75f, 1.25f);
  243. float swaySpeed = remap(rand01(state), 0.85f, 1.15f);
  244. float swayPhase = rand01(state) * 6.2831853f;
  245. float orientation = rand01(state) * 6.2831853f;
  246. GrassInstanceGpu instance;
  247. instance.posHeight = QVector4D(worldX, worldY, worldZ, height);
  248. instance.colorWidth = QVector4D(color.x(), color.y(), color.z(), width);
  249. instance.swayParams =
  250. QVector4D(swayStrength, swaySpeed, swayPhase, orientation);
  251. m_grassInstances.push_back(instance);
  252. return true;
  253. };
  254. auto quadSection = [&](Game::Map::TerrainType a, Game::Map::TerrainType b,
  255. Game::Map::TerrainType c, Game::Map::TerrainType d) {
  256. int priorityA = sectionFor(a);
  257. int priorityB = sectionFor(b);
  258. int priorityC = sectionFor(c);
  259. int priorityD = sectionFor(d);
  260. int result = priorityA;
  261. result = std::max(result, priorityB);
  262. result = std::max(result, priorityC);
  263. result = std::max(result, priorityD);
  264. return result;
  265. };
  266. const int chunkSize = 16;
  267. for (int chunkZ = 0; chunkZ < m_height - 1; chunkZ += chunkSize) {
  268. int chunkMaxZ = std::min(chunkZ + chunkSize, m_height - 1);
  269. for (int chunkX = 0; chunkX < m_width - 1; chunkX += chunkSize) {
  270. int chunkMaxX = std::min(chunkX + chunkSize, m_width - 1);
  271. int flatCount = 0;
  272. int hillCount = 0;
  273. int mountainCount = 0;
  274. float chunkHeightSum = 0.0f;
  275. float chunkSlopeSum = 0.0f;
  276. int sampleCount = 0;
  277. for (int z = chunkZ; z < chunkMaxZ && z < m_height - 1; ++z) {
  278. for (int x = chunkX; x < chunkMaxX && x < m_width - 1; ++x) {
  279. int idx0 = z * m_width + x;
  280. int idx1 = idx0 + 1;
  281. int idx2 = (z + 1) * m_width + x;
  282. int idx3 = idx2 + 1;
  283. if (m_terrainTypes[idx0] == Game::Map::TerrainType::Mountain ||
  284. m_terrainTypes[idx1] == Game::Map::TerrainType::Mountain ||
  285. m_terrainTypes[idx2] == Game::Map::TerrainType::Mountain ||
  286. m_terrainTypes[idx3] == Game::Map::TerrainType::Mountain ||
  287. m_terrainTypes[idx0] == Game::Map::TerrainType::River ||
  288. m_terrainTypes[idx1] == Game::Map::TerrainType::River ||
  289. m_terrainTypes[idx2] == Game::Map::TerrainType::River ||
  290. m_terrainTypes[idx3] == Game::Map::TerrainType::River) {
  291. mountainCount++;
  292. } else if (m_terrainTypes[idx0] == Game::Map::TerrainType::Hill ||
  293. m_terrainTypes[idx1] == Game::Map::TerrainType::Hill ||
  294. m_terrainTypes[idx2] == Game::Map::TerrainType::Hill ||
  295. m_terrainTypes[idx3] == Game::Map::TerrainType::Hill) {
  296. hillCount++;
  297. } else {
  298. flatCount++;
  299. }
  300. float quadHeight = (m_heightData[idx0] + m_heightData[idx1] +
  301. m_heightData[idx2] + m_heightData[idx3]) *
  302. 0.25f;
  303. chunkHeightSum += quadHeight;
  304. float nY = (normals[idx0].y() + normals[idx1].y() +
  305. normals[idx2].y() + normals[idx3].y()) *
  306. 0.25f;
  307. chunkSlopeSum += 1.0f - std::clamp(nY, 0.0f, 1.0f);
  308. sampleCount++;
  309. }
  310. }
  311. if (sampleCount == 0) {
  312. continue;
  313. }
  314. const float usableCoverage =
  315. sampleCount > 0 ? float(flatCount + hillCount) / float(sampleCount)
  316. : 0.0f;
  317. if (usableCoverage < 0.05f) {
  318. continue;
  319. }
  320. bool isPrimarilyFlat = flatCount >= hillCount;
  321. float avgSlope = chunkSlopeSum / float(sampleCount);
  322. uint32_t state = hashCoords(chunkX, chunkZ, m_noiseSeed ^ 0xC915872Bu);
  323. float slopePenalty = 1.0f - std::clamp(avgSlope * 1.35f, 0.0f, 0.75f);
  324. float typeBias = 1.0f;
  325. constexpr float kClusterBoost = 1.35f;
  326. float expectedClusters =
  327. std::max(0.0f, m_biomeSettings.patchDensity * kClusterBoost *
  328. slopePenalty * typeBias * usableCoverage);
  329. int clusterCount = static_cast<int>(std::floor(expectedClusters));
  330. float frac = expectedClusters - float(clusterCount);
  331. if (rand01(state) < frac) {
  332. clusterCount += 1;
  333. }
  334. if (clusterCount > 0) {
  335. float chunkSpanX = float(chunkMaxX - chunkX + 1);
  336. float chunkSpanZ = float(chunkMaxZ - chunkZ + 1);
  337. float scatterBase = std::max(0.25f, m_biomeSettings.patchJitter);
  338. auto pickClusterCenter =
  339. [&](uint32_t &rng) -> std::optional<QVector2D> {
  340. constexpr int kMaxAttempts = 8;
  341. for (int attempt = 0; attempt < kMaxAttempts; ++attempt) {
  342. float candidateGX = float(chunkX) + rand01(rng) * chunkSpanX;
  343. float candidateGZ = float(chunkZ) + rand01(rng) * chunkSpanZ;
  344. int cx = std::clamp(int(std::round(candidateGX)), 0, m_width - 1);
  345. int cz = std::clamp(int(std::round(candidateGZ)), 0, m_height - 1);
  346. int centerIdx = cz * m_width + cx;
  347. if (m_terrainTypes[centerIdx] == Game::Map::TerrainType::Mountain ||
  348. m_terrainTypes[centerIdx] == Game::Map::TerrainType::River) {
  349. continue;
  350. }
  351. QVector3D centerNormal = normals[centerIdx];
  352. float centerSlope = 1.0f - std::clamp(centerNormal.y(), 0.0f, 1.0f);
  353. if (centerSlope > 0.92f) {
  354. continue;
  355. }
  356. return QVector2D(candidateGX, candidateGZ);
  357. }
  358. return std::nullopt;
  359. };
  360. for (int cluster = 0; cluster < clusterCount; ++cluster) {
  361. auto center = pickClusterCenter(state);
  362. if (!center) {
  363. continue;
  364. }
  365. float centerGX = center->x();
  366. float centerGZ = center->y();
  367. int blades = 6 + static_cast<int>(rand01(state) * 6.0f);
  368. blades = std::max(
  369. 4, int(std::round(blades * (0.85f + 0.3f * rand01(state)))));
  370. float scatterRadius =
  371. (0.45f + 0.55f * rand01(state)) * scatterBase * tileSafe;
  372. for (int blade = 0; blade < blades; ++blade) {
  373. float angle = rand01(state) * 6.2831853f;
  374. float radius = scatterRadius * std::sqrt(rand01(state));
  375. float gx = centerGX + std::cos(angle) * radius / tileSafe;
  376. float gz = centerGZ + std::sin(angle) * radius / tileSafe;
  377. addGrassBlade(gx, gz, state);
  378. }
  379. }
  380. }
  381. }
  382. }
  383. const float backgroundDensity =
  384. std::max(0.0f, m_biomeSettings.backgroundBladeDensity);
  385. if (backgroundDensity > 0.0f) {
  386. for (int z = 0; z < m_height; ++z) {
  387. for (int x = 0; x < m_width; ++x) {
  388. int idx = z * m_width + x;
  389. if (m_terrainTypes[idx] == Game::Map::TerrainType::Mountain ||
  390. m_terrainTypes[idx] == Game::Map::TerrainType::Hill ||
  391. m_terrainTypes[idx] == Game::Map::TerrainType::River) {
  392. continue;
  393. }
  394. QVector3D normal = normals[idx];
  395. float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
  396. if (slope > 0.95f) {
  397. continue;
  398. }
  399. uint32_t state = hashCoords(
  400. x, z, m_noiseSeed ^ 0x51bda7u ^ static_cast<uint32_t>(idx));
  401. int baseCount = static_cast<int>(std::floor(backgroundDensity));
  402. float frac = backgroundDensity - float(baseCount);
  403. if (rand01(state) < frac) {
  404. baseCount += 1;
  405. }
  406. for (int i = 0; i < baseCount; ++i) {
  407. float gx = float(x) + rand01(state);
  408. float gz = float(z) + rand01(state);
  409. addGrassBlade(gx, gz, state);
  410. }
  411. }
  412. }
  413. }
  414. m_grassInstanceCount = m_grassInstances.size();
  415. m_grassInstancesDirty = m_grassInstanceCount > 0;
  416. int debugFlatCount = 0;
  417. int debugHillCount = 0;
  418. int debugMountainCount = 0;
  419. for (const auto &type : m_terrainTypes) {
  420. if (type == Game::Map::TerrainType::Flat) {
  421. debugFlatCount++;
  422. } else if (type == Game::Map::TerrainType::Hill) {
  423. debugHillCount++;
  424. } else if (type == Game::Map::TerrainType::Mountain) {
  425. debugMountainCount++;
  426. }
  427. }
  428. }
  429. } // namespace Render::GL