scene_renderer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #include "scene_renderer.h"
  2. #include "../game/map/visibility_service.h"
  3. #include "entity/registry.h"
  4. #include "game/core/component.h"
  5. #include "game/core/world.h"
  6. #include "gl/backend.h"
  7. #include "gl/camera.h"
  8. #include "gl/primitives.h"
  9. #include "gl/resources.h"
  10. #include <QDebug>
  11. #include <algorithm>
  12. #include <cmath>
  13. namespace Render::GL {
  14. namespace {
  15. const QVector3D kAxisX(1.0f, 0.0f, 0.0f);
  16. const QVector3D kAxisY(0.0f, 1.0f, 0.0f);
  17. const QVector3D kAxisZ(0.0f, 0.0f, 1.0f);
  18. } // namespace
  19. Renderer::Renderer() { m_activeQueue = &m_queues[m_fillQueueIndex]; }
  20. Renderer::~Renderer() { shutdown(); }
  21. bool Renderer::initialize() {
  22. if (!m_backend)
  23. m_backend = std::make_shared<Backend>();
  24. m_backend->initialize();
  25. m_entityRegistry = std::make_unique<EntityRendererRegistry>();
  26. registerBuiltInEntityRenderers(*m_entityRegistry);
  27. return true;
  28. }
  29. void Renderer::shutdown() { m_backend.reset(); }
  30. void Renderer::beginFrame() {
  31. m_activeQueue = &m_queues[m_fillQueueIndex];
  32. m_activeQueue->clear();
  33. if (m_camera) {
  34. m_viewProj = m_camera->getProjectionMatrix() * m_camera->getViewMatrix();
  35. }
  36. if (m_backend)
  37. m_backend->beginFrame();
  38. }
  39. void Renderer::endFrame() {
  40. if (m_paused.load())
  41. return;
  42. if (m_backend && m_camera) {
  43. std::swap(m_fillQueueIndex, m_renderQueueIndex);
  44. DrawQueue &renderQueue = m_queues[m_renderQueueIndex];
  45. renderQueue.sortForBatching();
  46. m_backend->execute(renderQueue, *m_camera);
  47. }
  48. }
  49. void Renderer::setCamera(Camera *camera) { m_camera = camera; }
  50. void Renderer::setClearColor(float r, float g, float b, float a) {
  51. if (m_backend)
  52. m_backend->setClearColor(r, g, b, a);
  53. }
  54. void Renderer::setViewport(int width, int height) {
  55. m_viewportWidth = width;
  56. m_viewportHeight = height;
  57. if (m_backend)
  58. m_backend->setViewport(width, height);
  59. if (m_camera && height > 0) {
  60. float aspect = float(width) / float(height);
  61. m_camera->setPerspective(m_camera->getFOV(), aspect, m_camera->getNear(),
  62. m_camera->getFar());
  63. }
  64. }
  65. void Renderer::mesh(Mesh *mesh, const QMatrix4x4 &model, const QVector3D &color,
  66. Texture *texture, float alpha) {
  67. if (!mesh)
  68. return;
  69. if (mesh == getUnitCylinder() && (!texture) && (!m_currentShader)) {
  70. QVector3D start, end;
  71. float radius = 0.0f;
  72. if (detail::decomposeUnitCylinder(model, start, end, radius)) {
  73. cylinder(start, end, radius, color, alpha);
  74. return;
  75. }
  76. }
  77. MeshCmd cmd;
  78. cmd.mesh = mesh;
  79. cmd.texture = texture;
  80. cmd.model = model;
  81. cmd.mvp = m_viewProj * model;
  82. cmd.color = color;
  83. cmd.alpha = alpha;
  84. cmd.shader = m_currentShader;
  85. if (m_activeQueue)
  86. m_activeQueue->submit(cmd);
  87. }
  88. void Renderer::cylinder(const QVector3D &start, const QVector3D &end,
  89. float radius, const QVector3D &color, float alpha) {
  90. CylinderCmd cmd;
  91. cmd.start = start;
  92. cmd.end = end;
  93. cmd.radius = radius;
  94. cmd.color = color;
  95. cmd.alpha = alpha;
  96. if (m_activeQueue)
  97. m_activeQueue->submit(cmd);
  98. }
  99. void Renderer::fogBatch(const FogInstanceData *instances, std::size_t count) {
  100. if (!instances || count == 0 || !m_activeQueue)
  101. return;
  102. FogBatchCmd cmd;
  103. cmd.instances = instances;
  104. cmd.count = count;
  105. m_activeQueue->submit(cmd);
  106. }
  107. void Renderer::grassBatch(Buffer *instanceBuffer, std::size_t instanceCount,
  108. const GrassBatchParams &params) {
  109. if (!instanceBuffer || instanceCount == 0 || !m_activeQueue)
  110. return;
  111. GrassBatchCmd cmd;
  112. cmd.instanceBuffer = instanceBuffer;
  113. cmd.instanceCount = instanceCount;
  114. cmd.params = params;
  115. cmd.params.time = m_accumulatedTime;
  116. m_activeQueue->submit(cmd);
  117. }
  118. void Renderer::stoneBatch(Buffer *instanceBuffer, std::size_t instanceCount,
  119. const StoneBatchParams &params) {
  120. if (!instanceBuffer || instanceCount == 0 || !m_activeQueue)
  121. return;
  122. StoneBatchCmd cmd;
  123. cmd.instanceBuffer = instanceBuffer;
  124. cmd.instanceCount = instanceCount;
  125. cmd.params = params;
  126. m_activeQueue->submit(cmd);
  127. }
  128. void Renderer::plantBatch(Buffer *instanceBuffer, std::size_t instanceCount,
  129. const PlantBatchParams &params) {
  130. if (!instanceBuffer || instanceCount == 0 || !m_activeQueue)
  131. return;
  132. PlantBatchCmd cmd;
  133. cmd.instanceBuffer = instanceBuffer;
  134. cmd.instanceCount = instanceCount;
  135. cmd.params = params;
  136. cmd.params.time = m_accumulatedTime;
  137. m_activeQueue->submit(cmd);
  138. }
  139. void Renderer::pineBatch(Buffer *instanceBuffer, std::size_t instanceCount,
  140. const PineBatchParams &params) {
  141. if (!instanceBuffer || instanceCount == 0 || !m_activeQueue)
  142. return;
  143. PineBatchCmd cmd;
  144. cmd.instanceBuffer = instanceBuffer;
  145. cmd.instanceCount = instanceCount;
  146. cmd.params = params;
  147. cmd.params.time = m_accumulatedTime;
  148. m_activeQueue->submit(cmd);
  149. }
  150. void Renderer::terrainChunk(Mesh *mesh, const QMatrix4x4 &model,
  151. const TerrainChunkParams &params,
  152. std::uint16_t sortKey, bool depthWrite,
  153. float depthBias) {
  154. if (!mesh || !m_activeQueue)
  155. return;
  156. TerrainChunkCmd cmd;
  157. cmd.mesh = mesh;
  158. cmd.model = model;
  159. cmd.params = params;
  160. cmd.sortKey = sortKey;
  161. cmd.depthWrite = depthWrite;
  162. cmd.depthBias = depthBias;
  163. m_activeQueue->submit(cmd);
  164. }
  165. void Renderer::selectionRing(const QMatrix4x4 &model, float alphaInner,
  166. float alphaOuter, const QVector3D &color) {
  167. SelectionRingCmd cmd;
  168. cmd.model = model;
  169. cmd.mvp = m_viewProj * model;
  170. cmd.alphaInner = alphaInner;
  171. cmd.alphaOuter = alphaOuter;
  172. cmd.color = color;
  173. if (m_activeQueue)
  174. m_activeQueue->submit(cmd);
  175. }
  176. void Renderer::grid(const QMatrix4x4 &model, const QVector3D &color,
  177. float cellSize, float thickness, float extent) {
  178. GridCmd cmd;
  179. cmd.model = model;
  180. cmd.mvp = m_viewProj * model;
  181. cmd.color = color;
  182. cmd.cellSize = cellSize;
  183. cmd.thickness = thickness;
  184. cmd.extent = extent;
  185. if (m_activeQueue)
  186. m_activeQueue->submit(cmd);
  187. }
  188. void Renderer::selectionSmoke(const QMatrix4x4 &model, const QVector3D &color,
  189. float baseAlpha) {
  190. SelectionSmokeCmd cmd;
  191. cmd.model = model;
  192. cmd.mvp = m_viewProj * model;
  193. cmd.color = color;
  194. cmd.baseAlpha = baseAlpha;
  195. if (m_activeQueue)
  196. m_activeQueue->submit(cmd);
  197. }
  198. void Renderer::renderWorld(Engine::Core::World *world) {
  199. if (m_paused.load())
  200. return;
  201. if (!world)
  202. return;
  203. // Lock World's recursive mutex for entire render to prevent entities from being
  204. // deleted while we iterate. Recursive mutex allows World methods to lock again.
  205. std::lock_guard<std::recursive_mutex> guard(world->getEntityMutex());
  206. auto &vis = Game::Map::VisibilityService::instance();
  207. const bool visibilityEnabled = vis.isInitialized();
  208. auto renderableEntities =
  209. world->getEntitiesWith<Engine::Core::RenderableComponent>();
  210. for (auto entity : renderableEntities) {
  211. // Skip entities pending removal first, before accessing any components
  212. if (entity->hasComponent<Engine::Core::PendingRemovalComponent>()) {
  213. continue;
  214. }
  215. auto renderable = entity->getComponent<Engine::Core::RenderableComponent>();
  216. auto transform = entity->getComponent<Engine::Core::TransformComponent>();
  217. if (!renderable->visible || !transform) {
  218. continue;
  219. }
  220. auto *unitComp = entity->getComponent<Engine::Core::UnitComponent>();
  221. if (unitComp && unitComp->health <= 0) {
  222. continue;
  223. }
  224. if (unitComp && unitComp->ownerId != m_localOwnerId) {
  225. if (visibilityEnabled) {
  226. if (!vis.isVisibleWorld(transform->position.x, transform->position.z)) {
  227. continue;
  228. }
  229. }
  230. }
  231. QMatrix4x4 modelMatrix;
  232. modelMatrix.translate(transform->position.x, transform->position.y,
  233. transform->position.z);
  234. modelMatrix.rotate(transform->rotation.x, kAxisX);
  235. modelMatrix.rotate(transform->rotation.y, kAxisY);
  236. modelMatrix.rotate(transform->rotation.z, kAxisZ);
  237. modelMatrix.scale(transform->scale.x, transform->scale.y,
  238. transform->scale.z);
  239. bool drawnByRegistry = false;
  240. if (unitComp && !unitComp->unitType.empty() && m_entityRegistry) {
  241. auto fn = m_entityRegistry->get(unitComp->unitType);
  242. if (fn) {
  243. DrawContext ctx{resources(), entity, world, modelMatrix};
  244. ctx.selected =
  245. (m_selectedIds.find(entity->getId()) != m_selectedIds.end());
  246. ctx.hovered = (entity->getId() == m_hoveredEntityId);
  247. ctx.animationTime = m_accumulatedTime;
  248. ctx.backend = m_backend.get();
  249. fn(ctx, *this);
  250. drawnByRegistry = true;
  251. }
  252. }
  253. if (drawnByRegistry)
  254. continue;
  255. Mesh *meshToDraw = nullptr;
  256. ResourceManager *res = resources();
  257. switch (renderable->mesh) {
  258. case Engine::Core::RenderableComponent::MeshKind::Quad:
  259. meshToDraw = res ? res->quad() : nullptr;
  260. break;
  261. case Engine::Core::RenderableComponent::MeshKind::Plane:
  262. meshToDraw = res ? res->ground() : nullptr;
  263. break;
  264. case Engine::Core::RenderableComponent::MeshKind::Cube:
  265. meshToDraw = res ? res->unit() : nullptr;
  266. break;
  267. case Engine::Core::RenderableComponent::MeshKind::Capsule:
  268. meshToDraw = nullptr;
  269. break;
  270. case Engine::Core::RenderableComponent::MeshKind::Ring:
  271. meshToDraw = nullptr;
  272. break;
  273. case Engine::Core::RenderableComponent::MeshKind::None:
  274. default:
  275. break;
  276. }
  277. if (!meshToDraw && res)
  278. meshToDraw = res->unit();
  279. if (!meshToDraw && res)
  280. meshToDraw = res->quad();
  281. QVector3D color = QVector3D(renderable->color[0], renderable->color[1],
  282. renderable->color[2]);
  283. if (res) {
  284. Mesh *contactQuad = res->quad();
  285. Texture *white = res->white();
  286. if (contactQuad && white) {
  287. QMatrix4x4 contactBase;
  288. contactBase.translate(transform->position.x,
  289. transform->position.y + 0.03f,
  290. transform->position.z);
  291. contactBase.rotate(-90.0f, 1.0f, 0.0f, 0.0f);
  292. float footprint =
  293. std::max({transform->scale.x, transform->scale.z, 0.6f});
  294. float sizeRatio = 1.0f;
  295. if (auto *unit = entity->getComponent<Engine::Core::UnitComponent>()) {
  296. int mh = std::max(1, unit->maxHealth);
  297. sizeRatio = std::clamp(unit->health / float(mh), 0.0f, 1.0f);
  298. }
  299. float eased = 0.25f + 0.75f * sizeRatio;
  300. float baseScaleX = footprint * 0.55f * eased;
  301. float baseScaleY = footprint * 0.35f * eased;
  302. QVector3D col(0.03f, 0.03f, 0.03f);
  303. float centerAlpha = 0.32f * eased;
  304. float midAlpha = 0.16f * eased;
  305. float outerAlpha = 0.07f * eased;
  306. QMatrix4x4 c0 = contactBase;
  307. c0.scale(baseScaleX * 0.60f, baseScaleY * 0.60f, 1.0f);
  308. mesh(contactQuad, c0, col, white, centerAlpha);
  309. QMatrix4x4 c1 = contactBase;
  310. c1.scale(baseScaleX * 0.95f, baseScaleY * 0.95f, 1.0f);
  311. mesh(contactQuad, c1, col, white, midAlpha);
  312. QMatrix4x4 c2 = contactBase;
  313. c2.scale(baseScaleX * 1.35f, baseScaleY * 1.35f, 1.0f);
  314. mesh(contactQuad, c2, col, white, outerAlpha);
  315. }
  316. }
  317. mesh(meshToDraw, modelMatrix, color, res ? res->white() : nullptr, 1.0f);
  318. }
  319. }
  320. } // namespace Render::GL