Ver Fonte

apply clang tidy fixes

djeada há 1 mês atrás
pai
commit
7792ba2206
86 ficheiros alterados com 1904 adições e 812 exclusões
  1. 1 1
      .clang_format
  2. 2 0
      CMakeLists.txt
  3. 35 30
      Makefile
  4. 8 4
      app/controllers/action_vfx.cpp
  5. 24 12
      app/controllers/command_controller.cpp
  6. 124 62
      app/core/game_engine.cpp
  7. 8 4
      app/models/cursor_manager.cpp
  8. 2 1
      app/models/hover_tracker.cpp
  9. 26 13
      app/models/selected_units_model.cpp
  10. 44 23
      game/audio/MiniaudioBackend.cpp
  11. 24 12
      game/audio/MusicPlayer.cpp
  12. 2 1
      game/audio/Sound.cpp
  13. 1 3
      game/core/system.cpp
  14. 8 4
      game/core/world.cpp
  15. 15 8
      game/map/map_catalog.cpp
  16. 77 39
      game/map/map_loader.cpp
  17. 4 2
      game/map/map_transformer.cpp
  18. 9 5
      game/map/skirmish_loader.cpp
  19. 42 21
      game/map/terrain.cpp
  20. 18 9
      game/map/terrain_service.cpp
  21. 34 18
      game/map/visibility_service.cpp
  22. 6 3
      game/systems/ai_system.cpp
  23. 18 9
      game/systems/ai_system/ai_command_applier.cpp
  24. 6 3
      game/systems/ai_system/ai_command_filter.cpp
  25. 2 1
      game/systems/ai_system/ai_reasoner.cpp
  26. 4 2
      game/systems/ai_system/ai_snapshot_builder.cpp
  27. 2 1
      game/systems/ai_system/ai_tactical.cpp
  28. 22 11
      game/systems/ai_system/behaviors/attack_behavior.cpp
  29. 28 14
      game/systems/ai_system/behaviors/defend_behavior.cpp
  30. 24 12
      game/systems/ai_system/behaviors/gather_behavior.cpp
  31. 14 7
      game/systems/ai_system/behaviors/production_behavior.cpp
  32. 18 9
      game/systems/ai_system/behaviors/retreat_behavior.cpp
  33. 2 1
      game/systems/arrow_system.cpp
  34. 12 6
      game/systems/camera_controller.cpp
  35. 4 2
      game/systems/camera_follow_system.cpp
  36. 6 3
      game/systems/camera_service.cpp
  37. 12 6
      game/systems/capture_system.cpp
  38. 4 2
      game/systems/combat_system.cpp
  39. 70 54
      game/systems/command_service.cpp
  40. 4 2
      game/systems/formation_system.cpp
  41. 2 1
      game/systems/global_stats_registry.cpp
  42. 4 2
      game/systems/nation_registry.cpp
  43. 18 9
      game/systems/owner_registry.cpp
  44. 10 5
      game/systems/patrol_system.cpp
  45. 32 16
      game/systems/picking_service.cpp
  46. 22 11
      game/systems/production_service.cpp
  47. 6 3
      game/systems/production_system.cpp
  48. 30 15
      game/systems/selection_system.cpp
  49. 2 1
      game/systems/terrain_alignment_system.cpp
  50. 8 4
      game/systems/troop_count_registry.cpp
  51. 10 5
      game/systems/victory_service.cpp
  52. 1 1
      game/units/spawn_type.h
  53. 22 11
      game/units/unit.cpp
  54. 18 9
      game/visuals/visual_catalog.cpp
  55. 6 3
      render/entity/archer_renderer.cpp
  56. 13 7
      render/entity/barracks_renderer.cpp
  57. 7 4
      render/entity/horse_renderer.cpp
  58. 10 5
      render/entity/knight_renderer.cpp
  59. 4 2
      render/entity/mounted_knight_renderer.cpp
  60. 2 1
      render/entity/registry.cpp
  61. 12 6
      render/entity/spearman_renderer.cpp
  62. 6 3
      render/geom/arrow.cpp
  63. 6 3
      render/geom/patrol_flags.cpp
  64. 2 1
      render/geom/selection_disc.cpp
  65. 2 1
      render/geom/selection_ring.cpp
  66. 204 103
      render/gl/backend.cpp
  67. 111 57
      render/gl/camera.cpp
  68. 4 2
      render/gl/primitives.cpp
  69. 4 2
      render/gl/shader.cpp
  70. 34 18
      render/ground/biome_renderer.cpp
  71. 2 1
      render/ground/bridge_renderer.cpp
  72. 6 3
      render/ground/firecamp_renderer.cpp
  73. 12 6
      render/ground/fog_renderer.cpp
  74. 2 1
      render/ground/ground_renderer.cpp
  75. 8 4
      render/ground/pine_renderer.cpp
  76. 18 9
      render/ground/plant_renderer.cpp
  77. 2 1
      render/ground/river_renderer.cpp
  78. 10 5
      render/ground/riverbank_asset_renderer.cpp
  79. 4 2
      render/ground/riverbank_renderer.cpp
  80. 14 7
      render/ground/stone_renderer.cpp
  81. 21 11
      render/ground/terrain_renderer.cpp
  82. 8 4
      render/humanoid_base.cpp
  83. 2 1
      render/humanoid_math.cpp
  84. 48 24
      render/scene_renderer.cpp
  85. 365 0
      scripts/run-clang-tidy-fixes.sh
  86. 4 2
      ui/gl_view.cpp

+ 1 - 1
.clang_format

@@ -22,6 +22,7 @@ BreakBeforeBraces: Attach
 BreakBeforeBinaryOperators: NonAssignment
 BreakBeforeBinaryOperators: NonAssignment
 ConstructorInitializerAllOnOneLineOrOnePerLine: true
 ConstructorInitializerAllOnOneLineOrOnePerLine: true
 BreakConstructorInitializers: BeforeComma
 BreakConstructorInitializers: BeforeComma
+InsertBraces: true
 
 
 # No pretty alignment games
 # No pretty alignment games
 AlignOperands: false
 AlignOperands: false
@@ -58,4 +59,3 @@ SpacesBeforeTrailingComments: 1
 
 
 # Templates
 # Templates
 AlwaysBreakTemplateDeclarations: Yes
 AlwaysBreakTemplateDeclarations: Yes
-

+ 2 - 0
CMakeLists.txt

@@ -1,6 +1,8 @@
 cmake_minimum_required(VERSION 3.21)
 cmake_minimum_required(VERSION 3.21)
 project(StandardOfIron VERSION 1.0.0 LANGUAGES CXX)
 project(StandardOfIron VERSION 1.0.0 LANGUAGES CXX)
 
 
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+
 # ---- Clang-Tidy integration ----
 # ---- Clang-Tidy integration ----
 find_program(CLANG_TIDY_EXE NAMES clang-tidy)
 find_program(CLANG_TIDY_EXE NAMES clang-tidy)
 option(ENABLE_CLANG_TIDY "Enable clang-tidy analysis" ON)
 option(ENABLE_CLANG_TIDY "Enable clang-tidy analysis" ON)

+ 35 - 30
Makefile

@@ -10,6 +10,17 @@ BINARY_NAME := standard_of_iron
 MAP_EDITOR_BINARY := map_editor
 MAP_EDITOR_BINARY := map_editor
 DEFAULT_LANG ?= en
 DEFAULT_LANG ?= en
 
 
+# Clang-tidy auto-fixer (git-only by default; --all scans whole project)
+CLANG_TIDY_FIXER := scripts/run-clang-tidy-fixes.sh
+
+# Optional knobs (override on the command line)
+# e.g. make tidy CLANG_TIDY_JOBS=2 CLANG_TIDY_AUTO_FIX_CHECKS="-*,bugprone-*"
+CLANG_TIDY_JOBS ?=
+CLANG_TIDY_AUTO_FIX_CHECKS ?=
+CLANG_TIDY_FIX_PATHS ?=
+# Base for git diff (fallback is origin/main inside the script if unset)
+CLANG_TIDY_GIT_BASE ?=
+
 # Formatting config
 # Formatting config
 CLANG_FORMAT ?= clang-format
 CLANG_FORMAT ?= clang-format
 # Try to find qmlformat in common Qt installation paths if not in PATH
 # Try to find qmlformat in common Qt installation paths if not in PATH
@@ -44,8 +55,8 @@ help:
 	@echo "  $(GREEN)test$(RESET)          - Run tests (if any)"
 	@echo "  $(GREEN)test$(RESET)          - Run tests (if any)"
 	@echo "  $(GREEN)format$(RESET)        - Format all code (C++, QML, shaders)"
 	@echo "  $(GREEN)format$(RESET)        - Format all code (C++, QML, shaders)"
 	@echo "  $(GREEN)format-check$(RESET)  - Verify formatting (CI-friendly, no changes)"
 	@echo "  $(GREEN)format-check$(RESET)  - Verify formatting (CI-friendly, no changes)"
-	@echo "  $(GREEN)tidy$(RESET)          - Run clang-tidy on changed files"
-	@echo "  $(GREEN)tidy-all$(RESET)      - Run clang-tidy on all source files"
+	@echo "  $(GREEN)tidy$(RESET)          - Run clang-tidy fixes on changed files (git diff vs origin/main)"
+	@echo "  $(GREEN)tidy-all$(RESET)      - Run clang-tidy fixes on the whole project"
 	@echo "  $(GREEN)check-deps$(RESET)    - Check if dependencies are installed"
 	@echo "  $(GREEN)check-deps$(RESET)    - Check if dependencies are installed"
 	@echo "  $(GREEN)dev$(RESET)           - Set up development environment (install + configure + build)"
 	@echo "  $(GREEN)dev$(RESET)           - Set up development environment (install + configure + build)"
 	@echo "  $(GREEN)all$(RESET)           - Full build (configure + build)"
 	@echo "  $(GREEN)all$(RESET)           - Full build (configure + build)"
@@ -176,6 +187,9 @@ format:
 		echo "$(RED)scripts/remove-comments.sh not found$(RESET)"; exit 1; \
 		echo "$(RED)scripts/remove-comments.sh not found$(RESET)"; exit 1; \
 	fi
 	fi
 
 
+	@echo "$(BOLD)$(BLUE)Applying clang-tidy auto fixes (git-only, nice)...$(RESET)"
+	@bash $(CLANG_TIDY_FIXER) --nice --build-dir="$(BUILD_DIR)" --default-lang="$(DEFAULT_LANG)" $(if $(CLANG_TIDY_AUTO_FIX_CHECKS),--checks="$(CLANG_TIDY_AUTO_FIX_CHECKS)")
+
 	@echo "$(BOLD)$(BLUE)Formatting C/C++ files with clang-format...$(RESET)"
 	@echo "$(BOLD)$(BLUE)Formatting C/C++ files with clang-format...$(RESET)"
 	@if command -v $(CLANG_FORMAT) >/dev/null 2>&1; then \
 	@if command -v $(CLANG_FORMAT) >/dev/null 2>&1; then \
 		find . -type f \( $(FMT_GLOBS) \) $(EXCLUDE_FIND) -print0 \
 		find . -type f \( $(FMT_GLOBS) \) $(EXCLUDE_FIND) -print0 \
@@ -234,39 +248,29 @@ format-check:
 		exit 1; \
 		exit 1; \
 	fi
 	fi
 
 
-# ---- Static analysis: clang-tidy ----
+# ---- Static analysis: clang-tidy (driven by fixer script) ----
 .PHONY: tidy tidy-all
 .PHONY: tidy tidy-all
 
 
-TIDY_EXE := $(shell command -v clang-tidy 2>/dev/null)
-TIDY_FILES := $(shell find . -type f \( -name "*.cpp" -o -name "*.hpp" -o -name "*.h" -o -name "*.cc" \) \
-              -not -path "./$(BUILD_DIR)/*" -not -path "./third_party/*")
-
 tidy:
 tidy:
-	@if [ -z "$(TIDY_EXE)" ]; then \
-		echo "$(RED)clang-tidy not found. Please install it.$(RESET)"; \
-		exit 1; \
-	fi
-	@echo "$(BOLD)$(BLUE)Running clang-tidy on modified files...$(RESET)"
-	@if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then \
-		FILES=$$(git diff --name-only --diff-filter=ACMRTUXB HEAD | grep -E '\.cpp$$|\.hpp$$|\.h$$' || true); \
-		if [ -z "$$FILES" ]; then \
-			echo "$(YELLOW)No modified C++ files to analyze.$(RESET)"; \
-		else \
-			echo "$(BLUE)Analyzing changed files:$(RESET) $$FILES"; \
-			$(TIDY_EXE) $$FILES -- -p=$(BUILD_DIR); \
-		fi \
-	else \
-		echo "$(YELLOW)Not a git repo, skipping incremental tidy.$(RESET)"; \
-	fi
+	@echo "$(BOLD)$(BLUE)Running clang-tidy fixes on changed files (vs $${CLANG_TIDY_GIT_BASE:-origin/main})...$(RESET)"
+	@bash $(CLANG_TIDY_FIXER) \
+		--nice \
+		--build-dir="$(BUILD_DIR)" \
+		--default-lang="$(DEFAULT_LANG)" \
+		$(if $(CLANG_TIDY_JOBS),--jobs="$(CLANG_TIDY_JOBS)") \
+		$(if $(CLANG_TIDY_FIX_PATHS),--paths="$(CLANG_TIDY_FIX_PATHS)") \
+		$(if $(CLANG_TIDY_AUTO_FIX_CHECKS),--checks="$(CLANG_TIDY_AUTO_FIX_CHECKS)")
 
 
 tidy-all:
 tidy-all:
-	@if [ -z "$(TIDY_EXE)" ]; then \
-		echo "$(RED)clang-tidy not found. Please install it.$(RESET)"; \
-		exit 1; \
-	fi
-	@echo "$(BOLD)$(BLUE)Running clang-tidy on all source files...$(RESET)"
-	@$(TIDY_EXE) $(TIDY_FILES) -- -p=$(BUILD_DIR)
-	@echo "$(GREEN)✓ clang-tidy analysis complete$(RESET)"
+	@echo "$(BOLD)$(BLUE)Running clang-tidy fixes on ALL source files...$(RESET)"
+	@bash $(CLANG_TIDY_FIXER) \
+		--all \
+		--nice \
+		--build-dir="$(BUILD_DIR)" \
+		--default-lang="$(DEFAULT_LANG)" \
+		$(if $(CLANG_TIDY_JOBS),--jobs="$(CLANG_TIDY_JOBS)") \
+		$(if $(CLANG_TIDY_FIX_PATHS),--paths="$(CLANG_TIDY_FIX_PATHS)") \
+		$(if $(CLANG_TIDY_AUTO_FIX_CHECKS),--checks="$(CLANG_TIDY_AUTO_FIX_CHECKS)")
 
 
 # Debug build
 # Debug build
 .PHONY: debug
 .PHONY: debug
@@ -318,3 +322,4 @@ quickstart:
 	@echo "3. Run the game: $(BLUE)make run$(RESET)"
 	@echo "3. Run the game: $(BLUE)make run$(RESET)"
 	@echo ""
 	@echo ""
 	@echo "Or use the shortcut: $(BLUE)make dev$(RESET)"
 	@echo "Or use the shortcut: $(BLUE)make dev$(RESET)"
+

+ 8 - 4
app/controllers/action_vfx.cpp

@@ -9,21 +9,25 @@ namespace App::Controllers {
 
 
 void ActionVFX::spawnAttackArrow(Engine::Core::World *world,
 void ActionVFX::spawnAttackArrow(Engine::Core::World *world,
                                  Engine::Core::EntityID targetId) {
                                  Engine::Core::EntityID targetId) {
-  if (!world)
+  if (!world) {
     return;
     return;
+  }
 
 
   auto *arrowSystem = world->getSystem<Game::Systems::ArrowSystem>();
   auto *arrowSystem = world->getSystem<Game::Systems::ArrowSystem>();
-  if (!arrowSystem)
+  if (!arrowSystem) {
     return;
     return;
+  }
 
 
   auto *targetEntity = world->getEntity(targetId);
   auto *targetEntity = world->getEntity(targetId);
-  if (!targetEntity)
+  if (!targetEntity) {
     return;
     return;
+  }
 
 
   auto *targetTrans =
   auto *targetTrans =
       targetEntity->getComponent<Engine::Core::TransformComponent>();
       targetEntity->getComponent<Engine::Core::TransformComponent>();
-  if (!targetTrans)
+  if (!targetTrans) {
     return;
     return;
+  }
 
 
   QVector3D targetPos(targetTrans->position.x, targetTrans->position.y + 1.0f,
   QVector3D targetPos(targetTrans->position.x, targetTrans->position.y + 1.0f,
                       targetTrans->position.z);
                       targetTrans->position.z);

+ 24 - 12
app/controllers/command_controller.cpp

@@ -70,13 +70,15 @@ CommandResult CommandController::onStopCommand() {
   }
   }
 
 
   const auto &selected = m_selectionSystem->getSelectedUnits();
   const auto &selected = m_selectionSystem->getSelectedUnits();
-  if (selected.empty())
+  if (selected.empty()) {
     return result;
     return result;
+  }
 
 
   for (auto id : selected) {
   for (auto id : selected) {
     auto *entity = m_world->getEntity(id);
     auto *entity = m_world->getEntity(id);
-    if (!entity)
+    if (!entity) {
       continue;
       continue;
+    }
 
 
     resetMovement(entity);
     resetMovement(entity);
     entity->removeComponent<Engine::Core::AttackTargetComponent>();
     entity->removeComponent<Engine::Core::AttackTargetComponent>();
@@ -106,19 +108,22 @@ CommandResult CommandController::onHoldCommand() {
   }
   }
 
 
   const auto &selected = m_selectionSystem->getSelectedUnits();
   const auto &selected = m_selectionSystem->getSelectedUnits();
-  if (selected.empty())
+  if (selected.empty()) {
     return result;
     return result;
+  }
 
 
   for (auto id : selected) {
   for (auto id : selected) {
     auto *entity = m_world->getEntity(id);
     auto *entity = m_world->getEntity(id);
-    if (!entity)
+    if (!entity) {
       continue;
       continue;
+    }
 
 
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
 
 
     if (!unit || (unit->spawnType != Game::Units::SpawnType::Archer &&
     if (!unit || (unit->spawnType != Game::Units::SpawnType::Archer &&
-                  unit->spawnType != Game::Units::SpawnType::Spearman))
+                  unit->spawnType != Game::Units::SpawnType::Spearman)) {
       continue;
       continue;
+    }
 
 
     auto *holdMode = entity->getComponent<Engine::Core::HoldModeComponent>();
     auto *holdMode = entity->getComponent<Engine::Core::HoldModeComponent>();
 
 
@@ -203,12 +208,14 @@ CommandResult CommandController::onPatrolClick(qreal sx, qreal sy,
 
 
   for (auto id : selected) {
   for (auto id : selected) {
     auto *entity = m_world->getEntity(id);
     auto *entity = m_world->getEntity(id);
-    if (!entity)
+    if (!entity) {
       continue;
       continue;
+    }
 
 
     auto *building = entity->getComponent<Engine::Core::BuildingComponent>();
     auto *building = entity->getComponent<Engine::Core::BuildingComponent>();
-    if (building)
+    if (building) {
       continue;
       continue;
+    }
 
 
     auto *patrol = entity->getComponent<Engine::Core::PatrolComponent>();
     auto *patrol = entity->getComponent<Engine::Core::PatrolComponent>();
     if (!patrol) {
     if (!patrol) {
@@ -240,14 +247,16 @@ CommandResult CommandController::setRallyAtScreen(qreal sx, qreal sy,
                                                   void *camera,
                                                   void *camera,
                                                   int localOwnerId) {
                                                   int localOwnerId) {
   CommandResult result;
   CommandResult result;
-  if (!m_world || !m_selectionSystem || !m_pickingService || !camera)
+  if (!m_world || !m_selectionSystem || !m_pickingService || !camera) {
     return result;
     return result;
+  }
 
 
   auto *cam = static_cast<Render::GL::Camera *>(camera);
   auto *cam = static_cast<Render::GL::Camera *>(camera);
   QVector3D hit;
   QVector3D hit;
   if (!m_pickingService->screenToGround(QPointF(sx, sy), *cam, viewportWidth,
   if (!m_pickingService->screenToGround(QPointF(sx, sy), *cam, viewportWidth,
-                                        viewportHeight, hit))
+                                        viewportHeight, hit)) {
     return result;
     return result;
+  }
 
 
   Game::Systems::ProductionService::setRallyForFirstSelectedBarracks(
   Game::Systems::ProductionService::setRallyForFirstSelectedBarracks(
       *m_world, m_selectionSystem->getSelectedUnits(), localOwnerId, hit.x(),
       *m_world, m_selectionSystem->getSelectedUnits(), localOwnerId, hit.x(),
@@ -259,12 +268,14 @@ CommandResult CommandController::setRallyAtScreen(qreal sx, qreal sy,
 
 
 void CommandController::recruitNearSelected(const QString &unitType,
 void CommandController::recruitNearSelected(const QString &unitType,
                                             int localOwnerId) {
                                             int localOwnerId) {
-  if (!m_world || !m_selectionSystem)
+  if (!m_world || !m_selectionSystem) {
     return;
     return;
+  }
 
 
   const auto &sel = m_selectionSystem->getSelectedUnits();
   const auto &sel = m_selectionSystem->getSelectedUnits();
-  if (sel.empty())
+  if (sel.empty()) {
     return;
     return;
+  }
 
 
   auto result =
   auto result =
       Game::Systems::ProductionService::startProductionForFirstSelectedBarracks(
       Game::Systems::ProductionService::startProductionForFirstSelectedBarracks(
@@ -287,8 +298,9 @@ bool CommandController::anySelectedInHoldMode() const {
   const auto &selected = m_selectionSystem->getSelectedUnits();
   const auto &selected = m_selectionSystem->getSelectedUnits();
   for (Engine::Core::EntityID entityId : selected) {
   for (Engine::Core::EntityID entityId : selected) {
     Engine::Core::Entity *entity = m_world->getEntity(entityId);
     Engine::Core::Entity *entity = m_world->getEntity(entityId);
-    if (!entity)
+    if (!entity) {
       continue;
       continue;
+    }
 
 
     auto *holdMode = entity->getComponent<Engine::Core::HoldModeComponent>();
     auto *holdMode = entity->getComponent<Engine::Core::HoldModeComponent>();
     if (holdMode && holdMode->active) {
     if (holdMode && holdMode->active) {

+ 124 - 62
app/core/game_engine.cpp

@@ -274,8 +274,9 @@ GameEngine::~GameEngine() {
 }
 }
 
 
 void GameEngine::onMapClicked(qreal sx, qreal sy) {
 void GameEngine::onMapClicked(qreal sx, qreal sy) {
-  if (!m_window)
+  if (!m_window) {
     return;
     return;
+  }
   ensureInitialized();
   ensureInitialized();
   if (m_selectionController && m_camera) {
   if (m_selectionController && m_camera) {
     m_selectionController->onClickSelect(sx, sy, false, m_viewport.width,
     m_selectionController->onClickSelect(sx, sy, false, m_viewport.width,
@@ -285,12 +286,14 @@ void GameEngine::onMapClicked(qreal sx, qreal sy) {
 }
 }
 
 
 void GameEngine::onRightClick(qreal sx, qreal sy) {
 void GameEngine::onRightClick(qreal sx, qreal sy) {
-  if (!m_window)
+  if (!m_window) {
     return;
     return;
+  }
   ensureInitialized();
   ensureInitialized();
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
-  if (!selectionSystem)
+  if (!selectionSystem) {
     return;
     return;
+  }
 
 
   if (m_cursorManager->mode() == CursorMode::Patrol ||
   if (m_cursorManager->mode() == CursorMode::Patrol ||
       m_cursorManager->mode() == CursorMode::Attack) {
       m_cursorManager->mode() == CursorMode::Attack) {
@@ -309,18 +312,21 @@ void GameEngine::onRightClick(qreal sx, qreal sy) {
 }
 }
 
 
 void GameEngine::onAttackClick(qreal sx, qreal sy) {
 void GameEngine::onAttackClick(qreal sx, qreal sy) {
-  if (!m_window)
+  if (!m_window) {
     return;
     return;
+  }
   ensureInitialized();
   ensureInitialized();
-  if (!m_commandController || !m_camera)
+  if (!m_commandController || !m_camera) {
     return;
     return;
+  }
 
 
   auto result = m_commandController->onAttackClick(
   auto result = m_commandController->onAttackClick(
       sx, sy, m_viewport.width, m_viewport.height, m_camera.get());
       sx, sy, m_viewport.width, m_viewport.height, m_camera.get());
 
 
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
-  if (!selectionSystem || !m_pickingService || !m_camera || !m_world)
+  if (!selectionSystem || !m_pickingService || !m_camera || !m_world) {
     return;
     return;
+  }
 
 
   const auto &selected = selectionSystem->getSelectedUnits();
   const auto &selected = selectionSystem->getSelectedUnits();
   if (!selected.empty()) {
   if (!selected.empty()) {
@@ -351,8 +357,9 @@ void GameEngine::resetMovement(Engine::Core::Entity *entity) {
 }
 }
 
 
 void GameEngine::onStopCommand() {
 void GameEngine::onStopCommand() {
-  if (!m_commandController)
+  if (!m_commandController) {
     return;
     return;
+  }
   ensureInitialized();
   ensureInitialized();
 
 
   auto result = m_commandController->onStopCommand();
   auto result = m_commandController->onStopCommand();
@@ -362,8 +369,9 @@ void GameEngine::onStopCommand() {
 }
 }
 
 
 void GameEngine::onHoldCommand() {
 void GameEngine::onHoldCommand() {
-  if (!m_commandController)
+  if (!m_commandController) {
     return;
     return;
+  }
   ensureInitialized();
   ensureInitialized();
 
 
   auto result = m_commandController->onHoldCommand();
   auto result = m_commandController->onHoldCommand();
@@ -373,14 +381,16 @@ void GameEngine::onHoldCommand() {
 }
 }
 
 
 bool GameEngine::anySelectedInHoldMode() const {
 bool GameEngine::anySelectedInHoldMode() const {
-  if (!m_commandController)
+  if (!m_commandController) {
     return false;
     return false;
+  }
   return m_commandController->anySelectedInHoldMode();
   return m_commandController->anySelectedInHoldMode();
 }
 }
 
 
 void GameEngine::onPatrolClick(qreal sx, qreal sy) {
 void GameEngine::onPatrolClick(qreal sx, qreal sy) {
-  if (!m_commandController || !m_camera)
+  if (!m_commandController || !m_camera) {
     return;
     return;
+  }
   ensureInitialized();
   ensureInitialized();
 
 
   auto result = m_commandController->onPatrolClick(
   auto result = m_commandController->onPatrolClick(
@@ -391,8 +401,9 @@ void GameEngine::onPatrolClick(qreal sx, qreal sy) {
 }
 }
 
 
 void GameEngine::updateCursor(Qt::CursorShape newCursor) {
 void GameEngine::updateCursor(Qt::CursorShape newCursor) {
-  if (!m_window)
+  if (!m_window) {
     return;
     return;
+  }
   if (m_runtime.currentCursor != newCursor) {
   if (m_runtime.currentCursor != newCursor) {
     m_runtime.currentCursor = newCursor;
     m_runtime.currentCursor = newCursor;
     m_window->setCursor(newCursor);
     m_window->setCursor(newCursor);
@@ -408,8 +419,9 @@ void GameEngine::setError(const QString &errorMessage) {
 }
 }
 
 
 void GameEngine::setCursorMode(CursorMode mode) {
 void GameEngine::setCursorMode(CursorMode mode) {
-  if (!m_cursorManager)
+  if (!m_cursorManager) {
     return;
     return;
+  }
   m_cursorManager->setMode(mode);
   m_cursorManager->setMode(mode);
   m_cursorManager->updateCursorShape(m_window);
   m_cursorManager->updateCursorShape(m_window);
 }
 }
@@ -419,29 +431,34 @@ void GameEngine::setCursorMode(const QString &mode) {
 }
 }
 
 
 QString GameEngine::cursorMode() const {
 QString GameEngine::cursorMode() const {
-  if (!m_cursorManager)
+  if (!m_cursorManager) {
     return "normal";
     return "normal";
+  }
   return m_cursorManager->modeString();
   return m_cursorManager->modeString();
 }
 }
 
 
 qreal GameEngine::globalCursorX() const {
 qreal GameEngine::globalCursorX() const {
-  if (!m_cursorManager)
+  if (!m_cursorManager) {
     return 0;
     return 0;
+  }
   return m_cursorManager->globalCursorX(m_window);
   return m_cursorManager->globalCursorX(m_window);
 }
 }
 
 
 qreal GameEngine::globalCursorY() const {
 qreal GameEngine::globalCursorY() const {
-  if (!m_cursorManager)
+  if (!m_cursorManager) {
     return 0;
     return 0;
+  }
   return m_cursorManager->globalCursorY(m_window);
   return m_cursorManager->globalCursorY(m_window);
 }
 }
 
 
 void GameEngine::setHoverAtScreen(qreal sx, qreal sy) {
 void GameEngine::setHoverAtScreen(qreal sx, qreal sy) {
-  if (!m_window)
+  if (!m_window) {
     return;
     return;
+  }
   ensureInitialized();
   ensureInitialized();
-  if (!m_hoverTracker || !m_camera || !m_world)
+  if (!m_hoverTracker || !m_camera || !m_world) {
     return;
     return;
+  }
 
 
   m_cursorManager->updateCursorShape(m_window);
   m_cursorManager->updateCursorShape(m_window);
 
 
@@ -450,8 +467,9 @@ void GameEngine::setHoverAtScreen(qreal sx, qreal sy) {
 }
 }
 
 
 void GameEngine::onClickSelect(qreal sx, qreal sy, bool additive) {
 void GameEngine::onClickSelect(qreal sx, qreal sy, bool additive) {
-  if (!m_window)
+  if (!m_window) {
     return;
     return;
+  }
   ensureInitialized();
   ensureInitialized();
   if (m_selectionController && m_camera) {
   if (m_selectionController && m_camera) {
     m_selectionController->onClickSelect(sx, sy, additive, m_viewport.width,
     m_selectionController->onClickSelect(sx, sy, additive, m_viewport.width,
@@ -462,8 +480,9 @@ void GameEngine::onClickSelect(qreal sx, qreal sy, bool additive) {
 
 
 void GameEngine::onAreaSelected(qreal x1, qreal y1, qreal x2, qreal y2,
 void GameEngine::onAreaSelected(qreal x1, qreal y1, qreal x2, qreal y2,
                                 bool additive) {
                                 bool additive) {
-  if (!m_window)
+  if (!m_window) {
     return;
     return;
+  }
   ensureInitialized();
   ensureInitialized();
   if (m_selectionController && m_camera) {
   if (m_selectionController && m_camera) {
     m_selectionController->onAreaSelected(
     m_selectionController->onAreaSelected(
@@ -588,8 +607,9 @@ void GameEngine::update(float dt) {
 
 
 void GameEngine::render(int pixelWidth, int pixelHeight) {
 void GameEngine::render(int pixelWidth, int pixelHeight) {
 
 
-  if (!m_renderer || !m_world || !m_runtime.initialized || m_runtime.loading)
+  if (!m_renderer || !m_world || !m_runtime.initialized || m_runtime.loading) {
     return;
     return;
+  }
   if (pixelWidth > 0 && pixelHeight > 0) {
   if (pixelWidth > 0 && pixelHeight > 0) {
     m_viewport.width = pixelWidth;
     m_viewport.width = pixelWidth;
     m_viewport.height = pixelHeight;
     m_viewport.height = pixelHeight;
@@ -604,18 +624,22 @@ void GameEngine::render(int pixelWidth, int pixelHeight) {
   m_renderer->beginFrame();
   m_renderer->beginFrame();
   if (auto *res = m_renderer->resources()) {
   if (auto *res = m_renderer->resources()) {
     for (auto *pass : m_passes) {
     for (auto *pass : m_passes) {
-      if (pass)
+      if (pass) {
         pass->submit(*m_renderer, res);
         pass->submit(*m_renderer, res);
+      }
     }
     }
   }
   }
-  if (m_renderer && m_hoverTracker)
+  if (m_renderer && m_hoverTracker) {
     m_renderer->setHoveredEntityId(m_hoverTracker->getLastHoveredEntity());
     m_renderer->setHoveredEntityId(m_hoverTracker->getLastHoveredEntity());
-  if (m_renderer)
+  }
+  if (m_renderer) {
     m_renderer->setLocalOwnerId(m_runtime.localOwnerId);
     m_renderer->setLocalOwnerId(m_runtime.localOwnerId);
+  }
   m_renderer->renderWorld(m_world.get());
   m_renderer->renderWorld(m_world.get());
   if (auto *arrowSystem = m_world->getSystem<Game::Systems::ArrowSystem>()) {
   if (auto *arrowSystem = m_world->getSystem<Game::Systems::ArrowSystem>()) {
-    if (auto *res = m_renderer->resources())
+    if (auto *res = m_renderer->resources()) {
       Render::GL::renderArrows(m_renderer.get(), res, *arrowSystem);
       Render::GL::renderArrows(m_renderer.get(), res, *arrowSystem);
+    }
   }
   }
 
 
   if (auto *res = m_renderer->resources()) {
   if (auto *res = m_renderer->resources()) {
@@ -652,8 +676,9 @@ bool GameEngine::worldToScreen(const QVector3D &world,
 
 
 void GameEngine::syncSelectionFlags() {
 void GameEngine::syncSelectionFlags() {
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
-  if (!m_world || !selectionSystem)
+  if (!m_world || !selectionSystem) {
     return;
     return;
+  }
 
 
   App::Utils::sanitizeSelection(m_world.get(), selectionSystem);
   App::Utils::sanitizeSelection(m_world.get(), selectionSystem);
 
 
@@ -666,24 +691,27 @@ void GameEngine::syncSelectionFlags() {
 
 
 void GameEngine::cameraMove(float dx, float dz) {
 void GameEngine::cameraMove(float dx, float dz) {
   ensureInitialized();
   ensureInitialized();
-  if (!m_camera || !m_cameraService)
+  if (!m_camera || !m_cameraService) {
     return;
     return;
+  }
 
 
   m_cameraService->move(*m_camera, dx, dz);
   m_cameraService->move(*m_camera, dx, dz);
 }
 }
 
 
 void GameEngine::cameraElevate(float dy) {
 void GameEngine::cameraElevate(float dy) {
   ensureInitialized();
   ensureInitialized();
-  if (!m_camera || !m_cameraService)
+  if (!m_camera || !m_cameraService) {
     return;
     return;
+  }
 
 
   m_cameraService->elevate(*m_camera, dy);
   m_cameraService->elevate(*m_camera, dy);
 }
 }
 
 
 void GameEngine::resetCamera() {
 void GameEngine::resetCamera() {
   ensureInitialized();
   ensureInitialized();
-  if (!m_camera || !m_world || !m_cameraService)
+  if (!m_camera || !m_world || !m_cameraService) {
     return;
     return;
+  }
 
 
   m_cameraService->resetCamera(*m_camera, *m_world, m_runtime.localOwnerId,
   m_cameraService->resetCamera(*m_camera, *m_world, m_runtime.localOwnerId,
                                m_level.playerUnitId);
                                m_level.playerUnitId);
@@ -691,30 +719,34 @@ void GameEngine::resetCamera() {
 
 
 void GameEngine::cameraZoom(float delta) {
 void GameEngine::cameraZoom(float delta) {
   ensureInitialized();
   ensureInitialized();
-  if (!m_camera || !m_cameraService)
+  if (!m_camera || !m_cameraService) {
     return;
     return;
+  }
 
 
   m_cameraService->zoom(*m_camera, delta);
   m_cameraService->zoom(*m_camera, delta);
 }
 }
 
 
 float GameEngine::cameraDistance() const {
 float GameEngine::cameraDistance() const {
-  if (!m_camera || !m_cameraService)
+  if (!m_camera || !m_cameraService) {
     return 0.0f;
     return 0.0f;
+  }
   return m_cameraService->getDistance(*m_camera);
   return m_cameraService->getDistance(*m_camera);
 }
 }
 
 
 void GameEngine::cameraYaw(float degrees) {
 void GameEngine::cameraYaw(float degrees) {
   ensureInitialized();
   ensureInitialized();
-  if (!m_camera || !m_cameraService)
+  if (!m_camera || !m_cameraService) {
     return;
     return;
+  }
 
 
   m_cameraService->yaw(*m_camera, degrees);
   m_cameraService->yaw(*m_camera, degrees);
 }
 }
 
 
 void GameEngine::cameraOrbit(float yawDeg, float pitchDeg) {
 void GameEngine::cameraOrbit(float yawDeg, float pitchDeg) {
   ensureInitialized();
   ensureInitialized();
-  if (!m_camera || !m_cameraService)
+  if (!m_camera || !m_cameraService) {
     return;
     return;
+  }
 
 
   if (!std::isfinite(yawDeg) || !std::isfinite(pitchDeg)) {
   if (!std::isfinite(yawDeg) || !std::isfinite(pitchDeg)) {
     qWarning() << "GameEngine::cameraOrbit received invalid input, ignoring:"
     qWarning() << "GameEngine::cameraOrbit received invalid input, ignoring:"
@@ -726,8 +758,9 @@ void GameEngine::cameraOrbit(float yawDeg, float pitchDeg) {
 }
 }
 
 
 void GameEngine::cameraOrbitDirection(int direction, bool shift) {
 void GameEngine::cameraOrbitDirection(int direction, bool shift) {
-  if (!m_camera || !m_cameraService)
+  if (!m_camera || !m_cameraService) {
     return;
     return;
+  }
 
 
   m_cameraService->orbitDirection(*m_camera, direction, shift);
   m_cameraService->orbitDirection(*m_camera, direction, shift);
 }
 }
@@ -735,16 +768,18 @@ void GameEngine::cameraOrbitDirection(int direction, bool shift) {
 void GameEngine::cameraFollowSelection(bool enable) {
 void GameEngine::cameraFollowSelection(bool enable) {
   ensureInitialized();
   ensureInitialized();
   m_followSelectionEnabled = enable;
   m_followSelectionEnabled = enable;
-  if (!m_camera || !m_world || !m_cameraService)
+  if (!m_camera || !m_world || !m_cameraService) {
     return;
     return;
+  }
 
 
   m_cameraService->followSelection(*m_camera, *m_world, enable);
   m_cameraService->followSelection(*m_camera, *m_world, enable);
 }
 }
 
 
 void GameEngine::cameraSetFollowLerp(float alpha) {
 void GameEngine::cameraSetFollowLerp(float alpha) {
   ensureInitialized();
   ensureInitialized();
-  if (!m_camera || !m_cameraService)
+  if (!m_camera || !m_cameraService) {
     return;
     return;
+  }
 
 
   m_cameraService->setFollowLerp(*m_camera, alpha);
   m_cameraService->setFollowLerp(*m_camera, alpha);
 }
 }
@@ -754,8 +789,9 @@ QObject *GameEngine::selectedUnitsModel() { return m_selectedUnitsModel; }
 QObject *GameEngine::audioSystem() { return m_audioSystemProxy.get(); }
 QObject *GameEngine::audioSystem() { return m_audioSystemProxy.get(); }
 
 
 bool GameEngine::hasUnitsSelected() const {
 bool GameEngine::hasUnitsSelected() const {
-  if (!m_selectionController)
+  if (!m_selectionController) {
     return false;
     return false;
+  }
   return m_selectionController->hasUnitsSelected();
   return m_selectionController->hasUnitsSelected();
 }
 }
 
 
@@ -764,15 +800,17 @@ int GameEngine::playerTroopCount() const {
 }
 }
 
 
 bool GameEngine::hasSelectedType(const QString &type) const {
 bool GameEngine::hasSelectedType(const QString &type) const {
-  if (!m_selectionController)
+  if (!m_selectionController) {
     return false;
     return false;
+  }
   return m_selectionController->hasSelectedType(type);
   return m_selectionController->hasSelectedType(type);
 }
 }
 
 
 void GameEngine::recruitNearSelected(const QString &unitType) {
 void GameEngine::recruitNearSelected(const QString &unitType) {
   ensureInitialized();
   ensureInitialized();
-  if (!m_commandController)
+  if (!m_commandController) {
     return;
     return;
+  }
   m_commandController->recruitNearSelected(unitType, m_runtime.localOwnerId);
   m_commandController->recruitNearSelected(unitType, m_runtime.localOwnerId);
 }
 }
 
 
@@ -785,11 +823,13 @@ QVariantMap GameEngine::getSelectedProductionState() const {
   m["producedCount"] = 0;
   m["producedCount"] = 0;
   m["maxUnits"] = 0;
   m["maxUnits"] = 0;
   m["villagerCost"] = 1;
   m["villagerCost"] = 1;
-  if (!m_world)
+  if (!m_world) {
     return m;
     return m;
+  }
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
-  if (!selectionSystem)
+  if (!selectionSystem) {
     return m;
     return m;
+  }
   Game::Systems::ProductionState st;
   Game::Systems::ProductionState st;
   Game::Systems::ProductionService::getSelectedBarracksState(
   Game::Systems::ProductionService::getSelectedBarracksState(
       *m_world, selectionSystem->getSelectedUnits(), m_runtime.localOwnerId,
       *m_world, selectionSystem->getSelectedUnits(), m_runtime.localOwnerId,
@@ -816,15 +856,18 @@ QVariantMap GameEngine::getSelectedProductionState() const {
 }
 }
 
 
 QString GameEngine::getSelectedUnitsCommandMode() const {
 QString GameEngine::getSelectedUnitsCommandMode() const {
-  if (!m_world)
+  if (!m_world) {
     return "normal";
     return "normal";
+  }
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
   auto *selectionSystem = m_world->getSystem<Game::Systems::SelectionSystem>();
-  if (!selectionSystem)
+  if (!selectionSystem) {
     return "normal";
     return "normal";
+  }
 
 
   const auto &sel = selectionSystem->getSelectedUnits();
   const auto &sel = selectionSystem->getSelectedUnits();
-  if (sel.empty())
+  if (sel.empty()) {
     return "normal";
     return "normal";
+  }
 
 
   int attackingCount = 0;
   int attackingCount = 0;
   int patrollingCount = 0;
   int patrollingCount = 0;
@@ -832,40 +875,49 @@ QString GameEngine::getSelectedUnitsCommandMode() const {
 
 
   for (auto id : sel) {
   for (auto id : sel) {
     auto *e = m_world->getEntity(id);
     auto *e = m_world->getEntity(id);
-    if (!e)
+    if (!e) {
       continue;
       continue;
+    }
 
 
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
-    if (!u)
+    if (!u) {
       continue;
       continue;
-    if (u->spawnType == Game::Units::SpawnType::Barracks)
+    }
+    if (u->spawnType == Game::Units::SpawnType::Barracks) {
       continue;
       continue;
+    }
 
 
     totalUnits++;
     totalUnits++;
 
 
-    if (e->getComponent<Engine::Core::AttackTargetComponent>())
+    if (e->getComponent<Engine::Core::AttackTargetComponent>()) {
       attackingCount++;
       attackingCount++;
+    }
 
 
     auto *patrol = e->getComponent<Engine::Core::PatrolComponent>();
     auto *patrol = e->getComponent<Engine::Core::PatrolComponent>();
-    if (patrol && patrol->patrolling)
+    if (patrol && patrol->patrolling) {
       patrollingCount++;
       patrollingCount++;
+    }
   }
   }
 
 
-  if (totalUnits == 0)
+  if (totalUnits == 0) {
     return "normal";
     return "normal";
+  }
 
 
-  if (patrollingCount == totalUnits)
+  if (patrollingCount == totalUnits) {
     return "patrol";
     return "patrol";
-  if (attackingCount == totalUnits)
+  }
+  if (attackingCount == totalUnits) {
     return "attack";
     return "attack";
+  }
 
 
   return "normal";
   return "normal";
 }
 }
 
 
 void GameEngine::setRallyAtScreen(qreal sx, qreal sy) {
 void GameEngine::setRallyAtScreen(qreal sx, qreal sy) {
   ensureInitialized();
   ensureInitialized();
-  if (!m_commandController || !m_camera)
+  if (!m_commandController || !m_camera) {
     return;
     return;
+  }
   m_commandController->setRallyAtScreen(sx, sy, m_viewport.width,
   m_commandController->setRallyAtScreen(sx, sy, m_viewport.width,
                                         m_viewport.height, m_camera.get(),
                                         m_viewport.height, m_camera.get(),
                                         m_runtime.localOwnerId);
                                         m_runtime.localOwnerId);
@@ -1167,19 +1219,22 @@ QVariantList GameEngine::getOwnerInfo() const {
 void GameEngine::getSelectedUnitIds(
 void GameEngine::getSelectedUnitIds(
     std::vector<Engine::Core::EntityID> &out) const {
     std::vector<Engine::Core::EntityID> &out) const {
   out.clear();
   out.clear();
-  if (!m_selectionController)
+  if (!m_selectionController) {
     return;
     return;
+  }
   m_selectionController->getSelectedUnitIds(out);
   m_selectionController->getSelectedUnitIds(out);
 }
 }
 
 
 bool GameEngine::getUnitInfo(Engine::Core::EntityID id, QString &name,
 bool GameEngine::getUnitInfo(Engine::Core::EntityID id, QString &name,
                              int &health, int &maxHealth, bool &isBuilding,
                              int &health, int &maxHealth, bool &isBuilding,
                              bool &alive) const {
                              bool &alive) const {
-  if (!m_world)
+  if (!m_world) {
     return false;
     return false;
+  }
   auto *e = m_world->getEntity(id);
   auto *e = m_world->getEntity(id);
-  if (!e)
+  if (!e) {
     return false;
     return false;
+  }
   isBuilding = e->hasComponent<Engine::Core::BuildingComponent>();
   isBuilding = e->hasComponent<Engine::Core::BuildingComponent>();
   if (auto *u = e->getComponent<Engine::Core::UnitComponent>()) {
   if (auto *u = e->getComponent<Engine::Core::UnitComponent>()) {
     name = QString::fromStdString(Game::Units::spawnTypeToString(u->spawnType));
     name = QString::fromStdString(Game::Units::spawnTypeToString(u->spawnType));
@@ -1268,8 +1323,9 @@ void GameEngine::rebuildEntityCache() {
   auto entities = m_world->getEntitiesWith<Engine::Core::UnitComponent>();
   auto entities = m_world->getEntitiesWith<Engine::Core::UnitComponent>();
   for (auto *e : entities) {
   for (auto *e : entities) {
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
-    if (!unit || unit->health <= 0)
+    if (!unit || unit->health <= 0) {
       continue;
       continue;
+    }
 
 
     if (unit->ownerId == m_runtime.localOwnerId) {
     if (unit->ownerId == m_runtime.localOwnerId) {
       if (unit->spawnType == Game::Units::SpawnType::Barracks) {
       if (unit->spawnType == Game::Units::SpawnType::Barracks) {
@@ -1298,8 +1354,9 @@ void GameEngine::rebuildEntityCache() {
 }
 }
 
 
 void GameEngine::rebuildRegistriesAfterLoad() {
 void GameEngine::rebuildRegistriesAfterLoad() {
-  if (!m_world)
+  if (!m_world) {
     return;
     return;
+  }
 
 
   auto &ownerRegistry = Game::Systems::OwnerRegistry::instance();
   auto &ownerRegistry = Game::Systems::OwnerRegistry::instance();
   m_runtime.localOwnerId = ownerRegistry.getLocalPlayerId();
   m_runtime.localOwnerId = ownerRegistry.getLocalPlayerId();
@@ -1324,8 +1381,9 @@ void GameEngine::rebuildRegistriesAfterLoad() {
   auto units = m_world->getEntitiesWith<Engine::Core::UnitComponent>();
   auto units = m_world->getEntitiesWith<Engine::Core::UnitComponent>();
   for (auto *entity : units) {
   for (auto *entity : units) {
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
-    if (!unit)
+    if (!unit) {
       continue;
       continue;
+    }
     if (unit->ownerId == m_runtime.localOwnerId) {
     if (unit->ownerId == m_runtime.localOwnerId) {
       m_level.playerUnitId = entity->getId();
       m_level.playerUnitId = entity->getId();
       break;
       break;
@@ -1341,15 +1399,17 @@ void GameEngine::rebuildRegistriesAfterLoad() {
 void GameEngine::rebuildBuildingCollisions() {
 void GameEngine::rebuildBuildingCollisions() {
   auto &registry = Game::Systems::BuildingCollisionRegistry::instance();
   auto &registry = Game::Systems::BuildingCollisionRegistry::instance();
   registry.clear();
   registry.clear();
-  if (!m_world)
+  if (!m_world) {
     return;
     return;
+  }
 
 
   auto buildings = m_world->getEntitiesWith<Engine::Core::BuildingComponent>();
   auto buildings = m_world->getEntitiesWith<Engine::Core::BuildingComponent>();
   for (auto *entity : buildings) {
   for (auto *entity : buildings) {
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
-    if (!transform || !unit)
+    if (!transform || !unit) {
       continue;
       continue;
+    }
 
 
     registry.registerBuilding(
     registry.registerBuilding(
         entity->getId(), Game::Units::spawnTypeToString(unit->spawnType),
         entity->getId(), Game::Units::spawnTypeToString(unit->spawnType),
@@ -1424,8 +1484,9 @@ QByteArray GameEngine::captureScreenshot() const {
 }
 }
 
 
 void GameEngine::restoreEnvironmentFromMetadata(const QJsonObject &metadata) {
 void GameEngine::restoreEnvironmentFromMetadata(const QJsonObject &metadata) {
-  if (!m_world)
+  if (!m_world) {
     return;
     return;
+  }
 
 
   const auto fallbackGridWidth = metadata.value("gridWidth").toInt(50);
   const auto fallbackGridWidth = metadata.value("gridWidth").toInt(50);
   const auto fallbackGridHeight = metadata.value("gridHeight").toInt(50);
   const auto fallbackGridHeight = metadata.value("gridHeight").toInt(50);
@@ -1568,8 +1629,9 @@ bool GameEngine::hasPatrolPreviewWaypoint() const {
 }
 }
 
 
 QVector3D GameEngine::getPatrolPreviewWaypoint() const {
 QVector3D GameEngine::getPatrolPreviewWaypoint() const {
-  if (!m_commandController)
+  if (!m_commandController) {
     return QVector3D();
     return QVector3D();
+  }
   return m_commandController->getPatrolFirstWaypoint();
   return m_commandController->getPatrolFirstWaypoint();
 }
 }
 
 

+ 8 - 4
app/models/cursor_manager.cpp

@@ -6,8 +6,9 @@
 CursorManager::CursorManager(QObject *parent) : QObject(parent) {}
 CursorManager::CursorManager(QObject *parent) : QObject(parent) {}
 
 
 void CursorManager::setMode(CursorMode mode) {
 void CursorManager::setMode(CursorMode mode) {
-  if (m_cursorMode == mode)
+  if (m_cursorMode == mode) {
     return;
     return;
+  }
 
 
   if (m_cursorMode == CursorMode::Patrol && mode != CursorMode::Patrol) {
   if (m_cursorMode == CursorMode::Patrol && mode != CursorMode::Patrol) {
     m_hasFirstWaypoint = false;
     m_hasFirstWaypoint = false;
@@ -24,8 +25,9 @@ void CursorManager::setMode(const QString &mode) {
 }
 }
 
 
 void CursorManager::updateCursorShape(QQuickWindow *window) {
 void CursorManager::updateCursorShape(QQuickWindow *window) {
-  if (!window)
+  if (!window) {
     return;
     return;
+  }
 
 
   Qt::CursorShape desiredCursor =
   Qt::CursorShape desiredCursor =
       (m_cursorMode == CursorMode::Normal) ? Qt::ArrowCursor : Qt::BlankCursor;
       (m_cursorMode == CursorMode::Normal) ? Qt::ArrowCursor : Qt::BlankCursor;
@@ -37,16 +39,18 @@ void CursorManager::updateCursorShape(QQuickWindow *window) {
 }
 }
 
 
 qreal CursorManager::globalCursorX(QQuickWindow *window) const {
 qreal CursorManager::globalCursorX(QQuickWindow *window) const {
-  if (!window)
+  if (!window) {
     return 0;
     return 0;
+  }
   QPoint globalPos = QCursor::pos();
   QPoint globalPos = QCursor::pos();
   QPoint localPos = window->mapFromGlobal(globalPos);
   QPoint localPos = window->mapFromGlobal(globalPos);
   return localPos.x();
   return localPos.x();
 }
 }
 
 
 qreal CursorManager::globalCursorY(QQuickWindow *window) const {
 qreal CursorManager::globalCursorY(QQuickWindow *window) const {
-  if (!window)
+  if (!window) {
     return 0;
     return 0;
+  }
   QPoint globalPos = QCursor::pos();
   QPoint globalPos = QCursor::pos();
   QPoint localPos = window->mapFromGlobal(globalPos);
   QPoint localPos = window->mapFromGlobal(globalPos);
   return localPos.y();
   return localPos.y();

+ 2 - 1
app/models/hover_tracker.cpp

@@ -9,8 +9,9 @@ Engine::Core::EntityID
 HoverTracker::updateHover(float sx, float sy, Engine::Core::World &world,
 HoverTracker::updateHover(float sx, float sy, Engine::Core::World &world,
                           const Render::GL::Camera &camera, int viewportWidth,
                           const Render::GL::Camera &camera, int viewportWidth,
                           int viewportHeight) {
                           int viewportHeight) {
-  if (!m_pickingService)
+  if (!m_pickingService) {
     return 0;
     return 0;
+  }
 
 
   if (sx < 0 || sy < 0 || sx >= viewportWidth || sy >= viewportHeight) {
   if (sx < 0 || sy < 0 || sx >= viewportWidth || sy >= viewportHeight) {
     m_hoveredEntityId = 0;
     m_hoveredEntityId = 0;

+ 26 - 13
app/models/selected_units_model.cpp

@@ -9,35 +9,44 @@ SelectedUnitsModel::SelectedUnitsModel(GameEngine *engine, QObject *parent)
     : QAbstractListModel(parent), m_engine(engine) {}
     : QAbstractListModel(parent), m_engine(engine) {}
 
 
 int SelectedUnitsModel::rowCount(const QModelIndex &parent) const {
 int SelectedUnitsModel::rowCount(const QModelIndex &parent) const {
-  if (parent.isValid())
+  if (parent.isValid()) {
     return 0;
     return 0;
+  }
   return static_cast<int>(m_ids.size());
   return static_cast<int>(m_ids.size());
 }
 }
 
 
 QVariant SelectedUnitsModel::data(const QModelIndex &index, int role) const {
 QVariant SelectedUnitsModel::data(const QModelIndex &index, int role) const {
   if (!index.isValid() || index.row() < 0 ||
   if (!index.isValid() || index.row() < 0 ||
-      index.row() >= static_cast<int>(m_ids.size()))
+      index.row() >= static_cast<int>(m_ids.size())) {
     return {};
     return {};
+  }
   auto id = m_ids[index.row()];
   auto id = m_ids[index.row()];
-  if (!m_engine)
+  if (!m_engine) {
     return {};
     return {};
+  }
   QString name;
   QString name;
   int hp = 0, maxHp = 0;
   int hp = 0, maxHp = 0;
   bool isB = false, alive = false;
   bool isB = false, alive = false;
-  if (role == UnitIdRole)
+  if (role == UnitIdRole) {
     return QVariant::fromValue<int>(static_cast<int>(id));
     return QVariant::fromValue<int>(static_cast<int>(id));
-  if (!m_engine->getUnitInfo(id, name, hp, maxHp, isB, alive))
+  }
+  if (!m_engine->getUnitInfo(id, name, hp, maxHp, isB, alive)) {
     return {};
     return {};
-  if (role == NameRole)
+  }
+  if (role == NameRole) {
     return name;
     return name;
-  if (role == HealthRole)
+  }
+  if (role == HealthRole) {
     return hp;
     return hp;
-  if (role == MaxHealthRole)
+  }
+  if (role == MaxHealthRole) {
     return maxHp;
     return maxHp;
-  if (role == HealthRatioRole)
+  }
+  if (role == HealthRatioRole) {
     return (maxHp > 0 ? static_cast<double>(std::clamp(hp, 0, maxHp)) /
     return (maxHp > 0 ? static_cast<double>(std::clamp(hp, 0, maxHp)) /
                             static_cast<double>(maxHp)
                             static_cast<double>(maxHp)
                       : 0.0);
                       : 0.0);
+  }
   return {};
   return {};
 }
 }
 
 
@@ -50,8 +59,9 @@ QHash<int, QByteArray> SelectedUnitsModel::roleNames() const {
 }
 }
 
 
 void SelectedUnitsModel::refresh() {
 void SelectedUnitsModel::refresh() {
-  if (!m_engine)
+  if (!m_engine) {
     return;
     return;
+  }
   std::vector<Engine::Core::EntityID> ids;
   std::vector<Engine::Core::EntityID> ids;
   m_engine->getSelectedUnitIds(ids);
   m_engine->getSelectedUnitIds(ids);
 
 
@@ -73,12 +83,15 @@ void SelectedUnitsModel::refresh() {
     QString nm;
     QString nm;
     int hp = 0, maxHp = 0;
     int hp = 0, maxHp = 0;
     bool isB = false, alive = false;
     bool isB = false, alive = false;
-    if (!m_engine->getUnitInfo(id, nm, hp, maxHp, isB, alive))
+    if (!m_engine->getUnitInfo(id, nm, hp, maxHp, isB, alive)) {
       continue;
       continue;
-    if (isB)
+    }
+    if (isB) {
       continue;
       continue;
-    if (!alive)
+    }
+    if (!alive) {
       continue;
       continue;
+    }
     m_ids.push_back(id);
     m_ids.push_back(id);
   }
   }
   endResetModel();
   endResetModel();

+ 44 - 23
game/audio/MiniaudioBackend.cpp

@@ -61,12 +61,14 @@ bool MiniaudioBackend::initialize(int deviceRate, int outChannels,
   }
   }
 
 
   m_channels.resize(std::max(1, musicChannels));
   m_channels.resize(std::max(1, musicChannels));
-  for (auto &ch : m_channels)
+  for (auto &ch : m_channels) {
     ch = Channel{};
     ch = Channel{};
+  }
 
 
   m_soundEffects.resize(32);
   m_soundEffects.resize(32);
-  for (auto &sfx : m_soundEffects)
+  for (auto &sfx : m_soundEffects) {
     sfx = SoundEffect{};
     sfx = SoundEffect{};
+  }
 
 
   if (ma_device_start(m_device) != MA_SUCCESS) {
   if (ma_device_start(m_device) != MA_SUCCESS) {
     qWarning() << "MiniaudioBackend: Failed to start audio device";
     qWarning() << "MiniaudioBackend: Failed to start audio device";
@@ -92,8 +94,9 @@ void MiniaudioBackend::shutdown() {
 }
 }
 
 
 void MiniaudioBackend::stopDevice() {
 void MiniaudioBackend::stopDevice() {
-  if (!m_device)
+  if (!m_device) {
     return;
     return;
+  }
   auto *wrap = reinterpret_cast<DeviceWrapper *>(m_device->pUserData);
   auto *wrap = reinterpret_cast<DeviceWrapper *>(m_device->pUserData);
   ma_device_stop(m_device);
   ma_device_stop(m_device);
   ma_device_uninit(m_device);
   ma_device_uninit(m_device);
@@ -123,8 +126,9 @@ bool MiniaudioBackend::predecode(const QString &id, const QString &path) {
       pcm.resize(old + samples);
       pcm.resize(old + samples);
       std::memcpy(pcm.data() + old, buffer, samples * sizeof(float));
       std::memcpy(pcm.data() + old, buffer, samples * sizeof(float));
     }
     }
-    if (r == MA_AT_END)
+    if (r == MA_AT_END) {
       break;
       break;
+    }
     if (r != MA_SUCCESS) {
     if (r != MA_SUCCESS) {
       ma_decoder_uninit(&dec);
       ma_decoder_uninit(&dec);
       return false;
       return false;
@@ -143,8 +147,9 @@ bool MiniaudioBackend::predecode(const QString &id, const QString &path) {
 void MiniaudioBackend::play(int channel, const QString &id, float volume,
 void MiniaudioBackend::play(int channel, const QString &id, float volume,
                             bool loop, int fadeMs) {
                             bool loop, int fadeMs) {
   QMutexLocker lk(&m_mutex);
   QMutexLocker lk(&m_mutex);
-  if (channel < 0 || channel >= m_channels.size())
+  if (channel < 0 || channel >= m_channels.size()) {
     return;
     return;
+  }
   auto it = m_tracks.find(id);
   auto it = m_tracks.find(id);
   if (it == m_tracks.end()) {
   if (it == m_tracks.end()) {
     lk.unlock();
     lk.unlock();
@@ -174,11 +179,13 @@ void MiniaudioBackend::play(int channel, const QString &id, float volume,
 
 
 void MiniaudioBackend::stop(int channel, int fadeMs) {
 void MiniaudioBackend::stop(int channel, int fadeMs) {
   QMutexLocker lk(&m_mutex);
   QMutexLocker lk(&m_mutex);
-  if (channel < 0 || channel >= m_channels.size())
+  if (channel < 0 || channel >= m_channels.size()) {
     return;
     return;
+  }
   auto &ch = m_channels[channel];
   auto &ch = m_channels[channel];
-  if (!ch.active)
+  if (!ch.active) {
     return;
     return;
+  }
   const unsigned fadeSamples = std::max(1u, unsigned((fadeMs * m_rate) / 1000));
   const unsigned fadeSamples = std::max(1u, unsigned((fadeMs * m_rate) / 1000));
   ch.tgtVol = 0.0f;
   ch.tgtVol = 0.0f;
   ch.fadeSamples = fadeSamples;
   ch.fadeSamples = fadeSamples;
@@ -188,22 +195,26 @@ void MiniaudioBackend::stop(int channel, int fadeMs) {
 
 
 void MiniaudioBackend::pause(int channel) {
 void MiniaudioBackend::pause(int channel) {
   QMutexLocker lk(&m_mutex);
   QMutexLocker lk(&m_mutex);
-  if (channel >= 0 && channel < m_channels.size())
+  if (channel >= 0 && channel < m_channels.size()) {
     m_channels[channel].paused = true;
     m_channels[channel].paused = true;
+  }
 }
 }
 void MiniaudioBackend::resume(int channel) {
 void MiniaudioBackend::resume(int channel) {
   QMutexLocker lk(&m_mutex);
   QMutexLocker lk(&m_mutex);
-  if (channel >= 0 && channel < m_channels.size())
+  if (channel >= 0 && channel < m_channels.size()) {
     m_channels[channel].paused = false;
     m_channels[channel].paused = false;
+  }
 }
 }
 
 
 void MiniaudioBackend::setVolume(int channel, float volume, int fadeMs) {
 void MiniaudioBackend::setVolume(int channel, float volume, int fadeMs) {
   QMutexLocker lk(&m_mutex);
   QMutexLocker lk(&m_mutex);
-  if (channel < 0 || channel >= m_channels.size())
+  if (channel < 0 || channel >= m_channels.size()) {
     return;
     return;
+  }
   auto &ch = m_channels[channel];
   auto &ch = m_channels[channel];
-  if (!ch.active)
+  if (!ch.active) {
     return;
     return;
+  }
   ch.tgtVol = std::clamp(volume, 0.0f, 1.0f);
   ch.tgtVol = std::clamp(volume, 0.0f, 1.0f);
   const unsigned fadeSamples = std::max(1u, unsigned((fadeMs * m_rate) / 1000));
   const unsigned fadeSamples = std::max(1u, unsigned((fadeMs * m_rate) / 1000));
   ch.fadeSamples = fadeSamples;
   ch.fadeSamples = fadeSamples;
@@ -214,8 +225,9 @@ void MiniaudioBackend::stopAll(int fadeMs) {
   QMutexLocker lk(&m_mutex);
   QMutexLocker lk(&m_mutex);
   const unsigned fadeSamples = std::max(1u, unsigned((fadeMs * m_rate) / 1000));
   const unsigned fadeSamples = std::max(1u, unsigned((fadeMs * m_rate) / 1000));
   for (auto &ch : m_channels) {
   for (auto &ch : m_channels) {
-    if (!ch.active)
+    if (!ch.active) {
       continue;
       continue;
+    }
     ch.tgtVol = 0.0f;
     ch.tgtVol = 0.0f;
     ch.fadeSamples = fadeSamples;
     ch.fadeSamples = fadeSamples;
     ch.volStep = (ch.tgtVol - ch.curVol) / float(fadeSamples);
     ch.volStep = (ch.tgtVol - ch.curVol) / float(fadeSamples);
@@ -230,15 +242,18 @@ void MiniaudioBackend::setMasterVolume(float volume, int) {
 
 
 bool MiniaudioBackend::anyChannelPlaying() const {
 bool MiniaudioBackend::anyChannelPlaying() const {
   QMutexLocker lk(&m_mutex);
   QMutexLocker lk(&m_mutex);
-  for (const auto &ch : m_channels)
-    if (ch.active && !ch.paused)
+  for (const auto &ch : m_channels) {
+    if (ch.active && !ch.paused) {
       return true;
       return true;
+    }
+  }
   return false;
   return false;
 }
 }
 bool MiniaudioBackend::channelPlaying(int channel) const {
 bool MiniaudioBackend::channelPlaying(int channel) const {
   QMutexLocker lk(&m_mutex);
   QMutexLocker lk(&m_mutex);
-  if (channel < 0 || channel >= m_channels.size())
+  if (channel < 0 || channel >= m_channels.size()) {
     return false;
     return false;
+  }
   const auto &ch = m_channels[channel];
   const auto &ch = m_channels[channel];
   return ch.active && !ch.paused;
   return ch.active && !ch.paused;
 }
 }
@@ -268,8 +283,9 @@ void MiniaudioBackend::playSound(const QString &id, float volume, bool loop) {
 
 
 int MiniaudioBackend::findFreeSoundSlot() const {
 int MiniaudioBackend::findFreeSoundSlot() const {
   for (int i = 0; i < m_soundEffects.size(); ++i) {
   for (int i = 0; i < m_soundEffects.size(); ++i) {
-    if (!m_soundEffects[i].active)
+    if (!m_soundEffects[i].active) {
       return i;
       return i;
+    }
   }
   }
   return -1;
   return -1;
 }
 }
@@ -282,8 +298,9 @@ void MiniaudioBackend::onAudio(float *out, unsigned frames) {
   QMutexLocker lk(&m_mutex);
   QMutexLocker lk(&m_mutex);
 
 
   for (auto &ch : m_channels) {
   for (auto &ch : m_channels) {
-    if (!ch.active || ch.paused || ch.track == nullptr)
+    if (!ch.active || ch.paused || ch.track == nullptr) {
       continue;
       continue;
+    }
 
 
     const auto *pcm = ch.track->pcm.constData();
     const auto *pcm = ch.track->pcm.constData();
     unsigned framesLeft = frames;
     unsigned framesLeft = frames;
@@ -293,10 +310,11 @@ void MiniaudioBackend::onAudio(float *out, unsigned frames) {
 
 
     while (framesLeft > 0) {
     while (framesLeft > 0) {
       if (pos >= ch.track->frames) {
       if (pos >= ch.track->frames) {
-        if (ch.looping)
+        if (ch.looping) {
           pos = 0;
           pos = 0;
-        else
+        } else {
           break;
           break;
+        }
       }
       }
       const unsigned canCopy = std::min(framesLeft, ch.track->frames - pos);
       const unsigned canCopy = std::min(framesLeft, ch.track->frames - pos);
       const float *src = pcm + pos * 2;
       const float *src = pcm + pos * 2;
@@ -311,8 +329,9 @@ void MiniaudioBackend::onAudio(float *out, unsigned frames) {
         if (ch.fadeSamples > 0) {
         if (ch.fadeSamples > 0) {
           ch.curVol += ch.volStep;
           ch.curVol += ch.volStep;
           --ch.fadeSamples;
           --ch.fadeSamples;
-          if (ch.fadeSamples == 0)
+          if (ch.fadeSamples == 0) {
             ch.curVol = ch.tgtVol;
             ch.curVol = ch.tgtVol;
+          }
         }
         }
       }
       }
       pos += canCopy;
       pos += canCopy;
@@ -333,8 +352,9 @@ void MiniaudioBackend::onAudio(float *out, unsigned frames) {
   }
   }
 
 
   for (auto &sfx : m_soundEffects) {
   for (auto &sfx : m_soundEffects) {
-    if (!sfx.active || sfx.track == nullptr)
+    if (!sfx.active || sfx.track == nullptr) {
       continue;
       continue;
+    }
 
 
     const auto *pcm = sfx.track->pcm.constData();
     const auto *pcm = sfx.track->pcm.constData();
     unsigned framesLeft = frames;
     unsigned framesLeft = frames;
@@ -370,9 +390,10 @@ void MiniaudioBackend::onAudio(float *out, unsigned frames) {
   }
   }
 
 
   for (unsigned i = 0; i < samples; ++i) {
   for (unsigned i = 0; i < samples; ++i) {
-    if (out[i] > 1.0f)
+    if (out[i] > 1.0f) {
       out[i] = 1.0f;
       out[i] = 1.0f;
-    else if (out[i] < -1.0f)
+    } else if (out[i] < -1.0f) {
       out[i] = -1.0f;
       out[i] = -1.0f;
+    }
   }
   }
 }
 }

+ 24 - 12
game/audio/MusicPlayer.cpp

@@ -24,8 +24,9 @@ MusicPlayer::MusicPlayer() : QObject(nullptr) {}
 MusicPlayer::~MusicPlayer() { shutdown(); }
 MusicPlayer::~MusicPlayer() { shutdown(); }
 
 
 bool MusicPlayer::initialize(int musicChannels) {
 bool MusicPlayer::initialize(int musicChannels) {
-  if (m_initialized)
+  if (m_initialized) {
     return true;
     return true;
+  }
   if (!QCoreApplication::instance()) {
   if (!QCoreApplication::instance()) {
     qWarning() << "MusicPlayer: no Q(Gui)Application instance";
     qWarning() << "MusicPlayer: no Q(Gui)Application instance";
     return false;
     return false;
@@ -48,8 +49,9 @@ bool MusicPlayer::initialize(int musicChannels) {
 }
 }
 
 
 void MusicPlayer::shutdown() {
 void MusicPlayer::shutdown() {
-  if (!m_initialized)
+  if (!m_initialized) {
     return;
     return;
+  }
 
 
   if (QCoreApplication::instance() &&
   if (QCoreApplication::instance() &&
       QThread::currentThread() != QCoreApplication::instance()->thread()) {
       QThread::currentThread() != QCoreApplication::instance()->thread()) {
@@ -135,8 +137,9 @@ int MusicPlayer::play(const std::string &id, float vol, bool loop, int channel,
 }
 }
 
 
 void MusicPlayer::stop(int ch, int ms) {
 void MusicPlayer::stop(int ch, int ms) {
-  if (!m_initialized || !m_backend)
+  if (!m_initialized || !m_backend) {
     return;
     return;
+  }
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
     QMetaObject::invokeMethod(
     QMetaObject::invokeMethod(
         this, [this, ch, ms]() { stop_gui(ch, ms); }, Qt::QueuedConnection);
         this, [this, ch, ms]() { stop_gui(ch, ms); }, Qt::QueuedConnection);
@@ -145,8 +148,9 @@ void MusicPlayer::stop(int ch, int ms) {
   stop_gui(ch, ms);
   stop_gui(ch, ms);
 }
 }
 void MusicPlayer::pause(int ch) {
 void MusicPlayer::pause(int ch) {
-  if (!m_initialized || !m_backend)
+  if (!m_initialized || !m_backend) {
     return;
     return;
+  }
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
     QMetaObject::invokeMethod(
     QMetaObject::invokeMethod(
         this, [this, ch]() { pause_gui(ch); }, Qt::QueuedConnection);
         this, [this, ch]() { pause_gui(ch); }, Qt::QueuedConnection);
@@ -155,8 +159,9 @@ void MusicPlayer::pause(int ch) {
   pause_gui(ch);
   pause_gui(ch);
 }
 }
 void MusicPlayer::resume(int ch) {
 void MusicPlayer::resume(int ch) {
-  if (!m_initialized || !m_backend)
+  if (!m_initialized || !m_backend) {
     return;
     return;
+  }
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
     QMetaObject::invokeMethod(
     QMetaObject::invokeMethod(
         this, [this, ch]() { resume_gui(ch); }, Qt::QueuedConnection);
         this, [this, ch]() { resume_gui(ch); }, Qt::QueuedConnection);
@@ -165,8 +170,9 @@ void MusicPlayer::resume(int ch) {
   resume_gui(ch);
   resume_gui(ch);
 }
 }
 void MusicPlayer::setVolume(int ch, float v, int ms) {
 void MusicPlayer::setVolume(int ch, float v, int ms) {
-  if (!m_initialized || !m_backend)
+  if (!m_initialized || !m_backend) {
     return;
     return;
+  }
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
     QMetaObject::invokeMethod(
     QMetaObject::invokeMethod(
         this, [this, ch, v, ms]() { setVolume_gui(ch, v, ms); },
         this, [this, ch, v, ms]() { setVolume_gui(ch, v, ms); },
@@ -176,8 +182,9 @@ void MusicPlayer::setVolume(int ch, float v, int ms) {
   setVolume_gui(ch, v, ms);
   setVolume_gui(ch, v, ms);
 }
 }
 void MusicPlayer::stopAll(int ms) {
 void MusicPlayer::stopAll(int ms) {
-  if (!m_initialized || !m_backend)
+  if (!m_initialized || !m_backend) {
     return;
     return;
+  }
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
     QMetaObject::invokeMethod(
     QMetaObject::invokeMethod(
         this, [this, ms]() { stopAll_gui(ms); }, Qt::QueuedConnection);
         this, [this, ms]() { stopAll_gui(ms); }, Qt::QueuedConnection);
@@ -186,8 +193,9 @@ void MusicPlayer::stopAll(int ms) {
   stopAll_gui(ms);
   stopAll_gui(ms);
 }
 }
 void MusicPlayer::setMasterVolume(float v, int ms) {
 void MusicPlayer::setMasterVolume(float v, int ms) {
-  if (!m_initialized || !m_backend)
+  if (!m_initialized || !m_backend) {
     return;
     return;
+  }
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
   if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
     QMetaObject::invokeMethod(
     QMetaObject::invokeMethod(
         this, [this, v, ms]() { setMasterVolume_gui(v, ms); },
         this, [this, v, ms]() { setMasterVolume_gui(v, ms); },
@@ -208,18 +216,22 @@ void MusicPlayer::ensureOnGuiThread(const char *where) const {
   requireGuiThread(where);
   requireGuiThread(where);
 }
 }
 int MusicPlayer::findFreeChannel() const {
 int MusicPlayer::findFreeChannel() const {
-  if (!m_backend)
+  if (!m_backend) {
     return 0;
     return 0;
-  for (int i = 0; i < m_channelCount; ++i)
-    if (!m_backend->channelPlaying(i))
+  }
+  for (int i = 0; i < m_channelCount; ++i) {
+    if (!m_backend->channelPlaying(i)) {
       return i;
       return i;
+    }
+  }
   return 0;
   return 0;
 }
 }
 
 
 void MusicPlayer::play_gui(const std::string &id, float vol, bool loop, int ch,
 void MusicPlayer::play_gui(const std::string &id, float vol, bool loop, int ch,
                            int fadeMs) {
                            int fadeMs) {
-  if (!m_backend)
+  if (!m_backend) {
     return;
     return;
+  }
   auto it = m_tracks.find(id);
   auto it = m_tracks.find(id);
   if (it == m_tracks.end()) {
   if (it == m_tracks.end()) {
     qWarning() << "Unknown trackId:" << QString::fromStdString(id);
     qWarning() << "Unknown trackId:" << QString::fromStdString(id);

+ 2 - 1
game/audio/Sound.cpp

@@ -29,8 +29,9 @@ Sound::Sound(const std::string &filePath, MiniaudioBackend *backend)
 Sound::~Sound() {}
 Sound::~Sound() {}
 
 
 void Sound::setBackend(MiniaudioBackend *backend) {
 void Sound::setBackend(MiniaudioBackend *backend) {
-  if (m_backend == backend)
+  if (m_backend == backend) {
     return;
     return;
+  }
 
 
   m_backend = backend;
   m_backend = backend;
 
 

+ 1 - 3
game/core/system.cpp

@@ -2,8 +2,6 @@
 
 
 namespace Engine::Core {
 namespace Engine::Core {
 namespace {
 namespace {
-[[maybe_unused]] void systemTypeAnchor() {
-  (void)sizeof(System *);
-}
+[[maybe_unused]] void systemTypeAnchor() { (void)sizeof(System *); }
 } // namespace
 } // namespace
 } // namespace Engine::Core
 } // namespace Engine::Core

+ 8 - 4
game/core/world.cpp

@@ -68,8 +68,9 @@ std::vector<Entity *> World::getUnitsOwnedBy(int ownerId) const {
   result.reserve(m_entities.size());
   result.reserve(m_entities.size());
   for (auto &[entityId, entity] : m_entities) {
   for (auto &[entityId, entity] : m_entities) {
     auto *unit = entity->getComponent<UnitComponent>();
     auto *unit = entity->getComponent<UnitComponent>();
-    if (!unit)
+    if (!unit) {
       continue;
       continue;
+    }
     if (unit->ownerId == ownerId) {
     if (unit->ownerId == ownerId) {
       result.push_back(entity.get());
       result.push_back(entity.get());
     }
     }
@@ -83,8 +84,9 @@ std::vector<Entity *> World::getUnitsNotOwnedBy(int ownerId) const {
   result.reserve(m_entities.size());
   result.reserve(m_entities.size());
   for (auto &[entityId, entity] : m_entities) {
   for (auto &[entityId, entity] : m_entities) {
     auto *unit = entity->getComponent<UnitComponent>();
     auto *unit = entity->getComponent<UnitComponent>();
-    if (!unit)
+    if (!unit) {
       continue;
       continue;
+    }
     if (unit->ownerId != ownerId) {
     if (unit->ownerId != ownerId) {
       result.push_back(entity.get());
       result.push_back(entity.get());
     }
     }
@@ -100,8 +102,9 @@ std::vector<Entity *> World::getAlliedUnits(int ownerId) const {
 
 
   for (auto &[entityId, entity] : m_entities) {
   for (auto &[entityId, entity] : m_entities) {
     auto *unit = entity->getComponent<UnitComponent>();
     auto *unit = entity->getComponent<UnitComponent>();
-    if (!unit)
+    if (!unit) {
       continue;
       continue;
+    }
 
 
     if (unit->ownerId == ownerId ||
     if (unit->ownerId == ownerId ||
         ownerRegistry.areAllies(ownerId, unit->ownerId)) {
         ownerRegistry.areAllies(ownerId, unit->ownerId)) {
@@ -119,8 +122,9 @@ std::vector<Entity *> World::getEnemyUnits(int ownerId) const {
 
 
   for (auto &[entityId, entity] : m_entities) {
   for (auto &[entityId, entity] : m_entities) {
     auto *unit = entity->getComponent<UnitComponent>();
     auto *unit = entity->getComponent<UnitComponent>();
-    if (!unit)
+    if (!unit) {
       continue;
       continue;
+    }
 
 
     if (ownerRegistry.areEnemies(ownerId, unit->ownerId)) {
     if (ownerRegistry.areEnemies(ownerId, unit->ownerId)) {
       result.push_back(entity.get());
       result.push_back(entity.get());

+ 15 - 8
game/map/map_catalog.cpp

@@ -22,8 +22,9 @@ QVariantList MapCatalog::availableMaps() {
   const QString mapsRoot =
   const QString mapsRoot =
       Utils::Resources::resolveResourcePath(QStringLiteral(":/assets/maps"));
       Utils::Resources::resolveResourcePath(QStringLiteral(":/assets/maps"));
   QDir mapsDir(mapsRoot);
   QDir mapsDir(mapsRoot);
-  if (!mapsDir.exists())
+  if (!mapsDir.exists()) {
     return list;
     return list;
+  }
 
 
   QStringList files =
   QStringList files =
       mapsDir.entryList(QStringList() << "*.json", QDir::Files, QDir::Name);
       mapsDir.entryList(QStringList() << "*.json", QDir::Files, QDir::Name);
@@ -40,10 +41,12 @@ QVariantList MapCatalog::availableMaps() {
       QJsonDocument doc = QJsonDocument::fromJson(data, &err);
       QJsonDocument doc = QJsonDocument::fromJson(data, &err);
       if (err.error == QJsonParseError::NoError && doc.isObject()) {
       if (err.error == QJsonParseError::NoError && doc.isObject()) {
         QJsonObject obj = doc.object();
         QJsonObject obj = doc.object();
-        if (obj.contains("name") && obj["name"].isString())
+        if (obj.contains("name") && obj["name"].isString()) {
           name = obj["name"].toString();
           name = obj["name"].toString();
-        if (obj.contains("description") && obj["description"].isString())
+        }
+        if (obj.contains("description") && obj["description"].isString()) {
           desc = obj["description"].toString();
           desc = obj["description"].toString();
+        }
 
 
         if (obj.contains("spawns") && obj["spawns"].isArray()) {
         if (obj.contains("spawns") && obj["spawns"].isArray()) {
           QJsonArray spawns = obj["spawns"].toArray();
           QJsonArray spawns = obj["spawns"].toArray();
@@ -107,8 +110,9 @@ QVariantList MapCatalog::availableMaps() {
 }
 }
 
 
 void MapCatalog::loadMapsAsync() {
 void MapCatalog::loadMapsAsync() {
-  if (m_loading)
+  if (m_loading) {
     return;
     return;
+  }
 
 
   m_maps.clear();
   m_maps.clear();
   m_pendingFiles.clear();
   m_pendingFiles.clear();
@@ -182,10 +186,12 @@ QVariantMap MapCatalog::loadSingleMap(const QString &path) {
     QJsonDocument doc = QJsonDocument::fromJson(data, &err);
     QJsonDocument doc = QJsonDocument::fromJson(data, &err);
     if (err.error == QJsonParseError::NoError && doc.isObject()) {
     if (err.error == QJsonParseError::NoError && doc.isObject()) {
       QJsonObject obj = doc.object();
       QJsonObject obj = doc.object();
-      if (obj.contains("name") && obj["name"].isString())
+      if (obj.contains("name") && obj["name"].isString()) {
         name = obj["name"].toString();
         name = obj["name"].toString();
-      if (obj.contains("description") && obj["description"].isString())
+      }
+      if (obj.contains("description") && obj["description"].isString()) {
         desc = obj["description"].toString();
         desc = obj["description"].toString();
+      }
 
 
       if (obj.contains("spawns") && obj["spawns"].isArray()) {
       if (obj.contains("spawns") && obj["spawns"].isArray()) {
         QJsonArray spawns = obj["spawns"].toArray();
         QJsonArray spawns = obj["spawns"].toArray();
@@ -237,10 +243,11 @@ QVariantMap MapCatalog::loadSingleMap(const QString &path) {
     QString thumbCandidate = Utils::Resources::resolveResourcePath(
     QString thumbCandidate = Utils::Resources::resolveResourcePath(
         QString(":/assets/maps/%1_thumb.png").arg(baseName));
         QString(":/assets/maps/%1_thumb.png").arg(baseName));
 
 
-    if (QFileInfo::exists(thumbCandidate))
+    if (QFileInfo::exists(thumbCandidate)) {
       thumbnail = thumbCandidate;
       thumbnail = thumbCandidate;
-    else
+    } else {
       thumbnail = "";
       thumbnail = "";
+    }
   }
   }
   entry["thumbnail"] = thumbnail;
   entry["thumbnail"] = thumbnail;
 
 

+ 77 - 39
game/map/map_loader.cpp

@@ -12,12 +12,15 @@
 namespace Game::Map {
 namespace Game::Map {
 
 
 static bool readGrid(const QJsonObject &obj, GridDefinition &grid) {
 static bool readGrid(const QJsonObject &obj, GridDefinition &grid) {
-  if (obj.contains("width"))
+  if (obj.contains("width")) {
     grid.width = obj.value("width").toInt(grid.width);
     grid.width = obj.value("width").toInt(grid.width);
-  if (obj.contains("height"))
+  }
+  if (obj.contains("height")) {
     grid.height = obj.value("height").toInt(grid.height);
     grid.height = obj.value("height").toInt(grid.height);
-  if (obj.contains("tileSize"))
+  }
+  if (obj.contains("tileSize")) {
     grid.tileSize = float(obj.value("tileSize").toDouble(grid.tileSize));
     grid.tileSize = float(obj.value("tileSize").toDouble(grid.tileSize));
+  }
   return grid.width > 0 && grid.height > 0 && grid.tileSize > 0.0f;
   return grid.width > 0 && grid.height > 0 && grid.tileSize > 0.0f;
 }
 }
 
 
@@ -29,16 +32,21 @@ static bool readCamera(const QJsonObject &obj, CameraDefinition &cam) {
                     float(arr[2].toDouble(0.0))};
                     float(arr[2].toDouble(0.0))};
     }
     }
   }
   }
-  if (obj.contains("distance"))
+  if (obj.contains("distance")) {
     cam.distance = float(obj.value("distance").toDouble(cam.distance));
     cam.distance = float(obj.value("distance").toDouble(cam.distance));
-  if (obj.contains("tiltDeg"))
+  }
+  if (obj.contains("tiltDeg")) {
     cam.tiltDeg = float(obj.value("tiltDeg").toDouble(cam.tiltDeg));
     cam.tiltDeg = float(obj.value("tiltDeg").toDouble(cam.tiltDeg));
-  if (obj.contains("fovY"))
+  }
+  if (obj.contains("fovY")) {
     cam.fovY = float(obj.value("fovY").toDouble(cam.fovY));
     cam.fovY = float(obj.value("fovY").toDouble(cam.fovY));
-  if (obj.contains("near"))
+  }
+  if (obj.contains("near")) {
     cam.nearPlane = float(obj.value("near").toDouble(cam.nearPlane));
     cam.nearPlane = float(obj.value("near").toDouble(cam.nearPlane));
-  if (obj.contains("far"))
+  }
+  if (obj.contains("far")) {
     cam.farPlane = float(obj.value("far").toDouble(cam.farPlane));
     cam.farPlane = float(obj.value("far").toDouble(cam.farPlane));
+  }
   if (obj.contains("yaw") || obj.contains("yawDeg")) {
   if (obj.contains("yaw") || obj.contains("yawDeg")) {
 
 
     const QString k = obj.contains("yaw") ? "yaw" : "yawDeg";
     const QString k = obj.contains("yaw") ? "yaw" : "yawDeg";
@@ -49,25 +57,30 @@ static bool readCamera(const QJsonObject &obj, CameraDefinition &cam) {
 
 
 static QVector3D readVector3(const QJsonValue &value,
 static QVector3D readVector3(const QJsonValue &value,
                              const QVector3D &fallback) {
                              const QVector3D &fallback) {
-  if (!value.isArray())
+  if (!value.isArray()) {
     return fallback;
     return fallback;
+  }
   auto arr = value.toArray();
   auto arr = value.toArray();
-  if (arr.size() != 3)
+  if (arr.size() != 3) {
     return fallback;
     return fallback;
+  }
   return QVector3D(float(arr[0].toDouble(fallback.x())),
   return QVector3D(float(arr[0].toDouble(fallback.x())),
                    float(arr[1].toDouble(fallback.y())),
                    float(arr[1].toDouble(fallback.y())),
                    float(arr[2].toDouble(fallback.z())));
                    float(arr[2].toDouble(fallback.z())));
 }
 }
 
 
 static void readBiome(const QJsonObject &obj, BiomeSettings &out) {
 static void readBiome(const QJsonObject &obj, BiomeSettings &out) {
-  if (obj.contains("seed"))
+  if (obj.contains("seed")) {
     out.seed = static_cast<std::uint32_t>(
     out.seed = static_cast<std::uint32_t>(
         std::max(0.0, obj.value("seed").toDouble(out.seed)));
         std::max(0.0, obj.value("seed").toDouble(out.seed)));
-  if (obj.contains("patchDensity"))
+  }
+  if (obj.contains("patchDensity")) {
     out.patchDensity =
     out.patchDensity =
         float(obj.value("patchDensity").toDouble(out.patchDensity));
         float(obj.value("patchDensity").toDouble(out.patchDensity));
-  if (obj.contains("patchJitter"))
+  }
+  if (obj.contains("patchJitter")) {
     out.patchJitter = float(obj.value("patchJitter").toDouble(out.patchJitter));
     out.patchJitter = float(obj.value("patchJitter").toDouble(out.patchJitter));
+  }
   if (obj.contains("bladeHeight")) {
   if (obj.contains("bladeHeight")) {
     auto arr = obj.value("bladeHeight").toArray();
     auto arr = obj.value("bladeHeight").toArray();
     if (arr.size() == 2) {
     if (arr.size() == 2) {
@@ -82,15 +95,18 @@ static void readBiome(const QJsonObject &obj, BiomeSettings &out) {
       out.bladeWidthMax = float(arr[1].toDouble(out.bladeWidthMax));
       out.bladeWidthMax = float(arr[1].toDouble(out.bladeWidthMax));
     }
     }
   }
   }
-  if (obj.contains("backgroundBladeDensity"))
+  if (obj.contains("backgroundBladeDensity")) {
     out.backgroundBladeDensity =
     out.backgroundBladeDensity =
         float(obj.value("backgroundBladeDensity")
         float(obj.value("backgroundBladeDensity")
                   .toDouble(out.backgroundBladeDensity));
                   .toDouble(out.backgroundBladeDensity));
-  if (obj.contains("swayStrength"))
+  }
+  if (obj.contains("swayStrength")) {
     out.swayStrength =
     out.swayStrength =
         float(obj.value("swayStrength").toDouble(out.swayStrength));
         float(obj.value("swayStrength").toDouble(out.swayStrength));
-  if (obj.contains("swaySpeed"))
+  }
+  if (obj.contains("swaySpeed")) {
     out.swaySpeed = float(obj.value("swaySpeed").toDouble(out.swaySpeed));
     out.swaySpeed = float(obj.value("swaySpeed").toDouble(out.swaySpeed));
+  }
   if (obj.contains("heightNoise")) {
   if (obj.contains("heightNoise")) {
     auto arr = obj.value("heightNoise").toArray();
     auto arr = obj.value("heightNoise").toArray();
     if (arr.size() == 2) {
     if (arr.size() == 2) {
@@ -101,57 +117,74 @@ static void readBiome(const QJsonObject &obj, BiomeSettings &out) {
     }
     }
   }
   }
 
 
-  if (obj.contains("grassPrimary"))
+  if (obj.contains("grassPrimary")) {
     out.grassPrimary = readVector3(obj.value("grassPrimary"), out.grassPrimary);
     out.grassPrimary = readVector3(obj.value("grassPrimary"), out.grassPrimary);
-  if (obj.contains("grassSecondary"))
+  }
+  if (obj.contains("grassSecondary")) {
     out.grassSecondary =
     out.grassSecondary =
         readVector3(obj.value("grassSecondary"), out.grassSecondary);
         readVector3(obj.value("grassSecondary"), out.grassSecondary);
-  if (obj.contains("grassDry"))
+  }
+  if (obj.contains("grassDry")) {
     out.grassDry = readVector3(obj.value("grassDry"), out.grassDry);
     out.grassDry = readVector3(obj.value("grassDry"), out.grassDry);
-  if (obj.contains("soilColor"))
+  }
+  if (obj.contains("soilColor")) {
     out.soilColor = readVector3(obj.value("soilColor"), out.soilColor);
     out.soilColor = readVector3(obj.value("soilColor"), out.soilColor);
-  if (obj.contains("rockLow"))
+  }
+  if (obj.contains("rockLow")) {
     out.rockLow = readVector3(obj.value("rockLow"), out.rockLow);
     out.rockLow = readVector3(obj.value("rockLow"), out.rockLow);
-  if (obj.contains("rockHigh"))
+  }
+  if (obj.contains("rockHigh")) {
     out.rockHigh = readVector3(obj.value("rockHigh"), out.rockHigh);
     out.rockHigh = readVector3(obj.value("rockHigh"), out.rockHigh);
-  if (obj.contains("terrainMacroNoiseScale"))
+  }
+  if (obj.contains("terrainMacroNoiseScale")) {
     out.terrainMacroNoiseScale =
     out.terrainMacroNoiseScale =
         float(obj.value("terrainMacroNoiseScale")
         float(obj.value("terrainMacroNoiseScale")
                   .toDouble(out.terrainMacroNoiseScale));
                   .toDouble(out.terrainMacroNoiseScale));
-  if (obj.contains("terrainDetailNoiseScale"))
+  }
+  if (obj.contains("terrainDetailNoiseScale")) {
     out.terrainDetailNoiseScale =
     out.terrainDetailNoiseScale =
         float(obj.value("terrainDetailNoiseScale")
         float(obj.value("terrainDetailNoiseScale")
                   .toDouble(out.terrainDetailNoiseScale));
                   .toDouble(out.terrainDetailNoiseScale));
-  if (obj.contains("terrainSoilHeight"))
+  }
+  if (obj.contains("terrainSoilHeight")) {
     out.terrainSoilHeight =
     out.terrainSoilHeight =
         float(obj.value("terrainSoilHeight").toDouble(out.terrainSoilHeight));
         float(obj.value("terrainSoilHeight").toDouble(out.terrainSoilHeight));
-  if (obj.contains("terrainSoilSharpness"))
+  }
+  if (obj.contains("terrainSoilSharpness")) {
     out.terrainSoilSharpness = float(
     out.terrainSoilSharpness = float(
         obj.value("terrainSoilSharpness").toDouble(out.terrainSoilSharpness));
         obj.value("terrainSoilSharpness").toDouble(out.terrainSoilSharpness));
-  if (obj.contains("terrainRockThreshold"))
+  }
+  if (obj.contains("terrainRockThreshold")) {
     out.terrainRockThreshold = float(
     out.terrainRockThreshold = float(
         obj.value("terrainRockThreshold").toDouble(out.terrainRockThreshold));
         obj.value("terrainRockThreshold").toDouble(out.terrainRockThreshold));
-  if (obj.contains("terrainRockSharpness"))
+  }
+  if (obj.contains("terrainRockSharpness")) {
     out.terrainRockSharpness = float(
     out.terrainRockSharpness = float(
         obj.value("terrainRockSharpness").toDouble(out.terrainRockSharpness));
         obj.value("terrainRockSharpness").toDouble(out.terrainRockSharpness));
-  if (obj.contains("terrainAmbientBoost"))
+  }
+  if (obj.contains("terrainAmbientBoost")) {
     out.terrainAmbientBoost = float(
     out.terrainAmbientBoost = float(
         obj.value("terrainAmbientBoost").toDouble(out.terrainAmbientBoost));
         obj.value("terrainAmbientBoost").toDouble(out.terrainAmbientBoost));
-  if (obj.contains("terrainRockDetailStrength"))
+  }
+  if (obj.contains("terrainRockDetailStrength")) {
     out.terrainRockDetailStrength =
     out.terrainRockDetailStrength =
         float(obj.value("terrainRockDetailStrength")
         float(obj.value("terrainRockDetailStrength")
                   .toDouble(out.terrainRockDetailStrength));
                   .toDouble(out.terrainRockDetailStrength));
-  if (obj.contains("backgroundSwayVariance"))
+  }
+  if (obj.contains("backgroundSwayVariance")) {
     out.backgroundSwayVariance =
     out.backgroundSwayVariance =
         float(obj.value("backgroundSwayVariance")
         float(obj.value("backgroundSwayVariance")
                   .toDouble(out.backgroundSwayVariance));
                   .toDouble(out.backgroundSwayVariance));
-  if (obj.contains("backgroundScatterRadius"))
+  }
+  if (obj.contains("backgroundScatterRadius")) {
     out.backgroundScatterRadius =
     out.backgroundScatterRadius =
         float(obj.value("backgroundScatterRadius")
         float(obj.value("backgroundScatterRadius")
                   .toDouble(out.backgroundScatterRadius));
                   .toDouble(out.backgroundScatterRadius));
-  if (obj.contains("plantDensity"))
+  }
+  if (obj.contains("plantDensity")) {
     out.plantDensity =
     out.plantDensity =
         float(obj.value("plantDensity").toDouble(out.plantDensity));
         float(obj.value("plantDensity").toDouble(out.plantDensity));
+  }
 }
 }
 
 
 static void readVictoryConfig(const QJsonObject &obj, VictoryConfig &out) {
 static void readVictoryConfig(const QJsonObject &obj, VictoryConfig &out) {
@@ -388,8 +421,9 @@ bool MapLoader::loadFromJsonFile(const QString &path, MapDefinition &outMap,
                                  QString *outError) {
                                  QString *outError) {
   QFile f(path);
   QFile f(path);
   if (!f.open(QIODevice::ReadOnly)) {
   if (!f.open(QIODevice::ReadOnly)) {
-    if (outError)
+    if (outError) {
       *outError = QString("Failed to open map file: %1").arg(path);
       *outError = QString("Failed to open map file: %1").arg(path);
+    }
     return false;
     return false;
   }
   }
   auto data = f.readAll();
   auto data = f.readAll();
@@ -398,15 +432,17 @@ bool MapLoader::loadFromJsonFile(const QString &path, MapDefinition &outMap,
   QJsonParseError perr;
   QJsonParseError perr;
   auto doc = QJsonDocument::fromJson(data, &perr);
   auto doc = QJsonDocument::fromJson(data, &perr);
   if (perr.error != QJsonParseError::NoError) {
   if (perr.error != QJsonParseError::NoError) {
-    if (outError)
+    if (outError) {
       *outError = QString("JSON parse error at %1: %2")
       *outError = QString("JSON parse error at %1: %2")
                       .arg(perr.offset)
                       .arg(perr.offset)
                       .arg(perr.errorString());
                       .arg(perr.errorString());
+    }
     return false;
     return false;
   }
   }
   if (!doc.isObject()) {
   if (!doc.isObject()) {
-    if (outError)
+    if (outError) {
       *outError = "Map JSON root must be an object";
       *outError = "Map JSON root must be an object";
+    }
     return false;
     return false;
   }
   }
   auto root = doc.object();
   auto root = doc.object();
@@ -415,10 +451,11 @@ bool MapLoader::loadFromJsonFile(const QString &path, MapDefinition &outMap,
 
 
   if (root.contains("coordSystem")) {
   if (root.contains("coordSystem")) {
     const QString cs = root.value("coordSystem").toString().trimmed().toLower();
     const QString cs = root.value("coordSystem").toString().trimmed().toLower();
-    if (cs == "world")
+    if (cs == "world") {
       outMap.coordSystem = CoordSystem::World;
       outMap.coordSystem = CoordSystem::World;
-    else
+    } else {
       outMap.coordSystem = CoordSystem::Grid;
       outMap.coordSystem = CoordSystem::Grid;
+    }
   }
   }
 
 
   if (root.contains("maxTroopsPerPlayer")) {
   if (root.contains("maxTroopsPerPlayer")) {
@@ -427,8 +464,9 @@ bool MapLoader::loadFromJsonFile(const QString &path, MapDefinition &outMap,
 
 
   if (root.contains("grid") && root.value("grid").isObject()) {
   if (root.contains("grid") && root.value("grid").isObject()) {
     if (!readGrid(root.value("grid").toObject(), outMap.grid)) {
     if (!readGrid(root.value("grid").toObject(), outMap.grid)) {
-      if (outError)
+      if (outError) {
         *outError = "Invalid grid definition";
         *outError = "Invalid grid definition";
+      }
       return false;
       return false;
     }
     }
   }
   }

+ 4 - 2
game/map/map_transformer.cpp

@@ -122,8 +122,9 @@ MapTransformer::applyToWorld(const MapDefinition &def,
         for (int ox = -r; ox <= r && !found; ++ox) {
         for (int ox = -r; ox <= r && !found; ++ox) {
           for (int oz = -r; oz <= r && !found; ++oz) {
           for (int oz = -r; oz <= r && !found; ++oz) {
 
 
-            if (std::abs(ox) != r && std::abs(oz) != r)
+            if (std::abs(ox) != r && std::abs(oz) != r) {
               continue;
               continue;
+            }
             float candX = worldX + float(ox) * tile;
             float candX = worldX + float(ox) * tile;
             float candZ = worldZ + float(oz) * tile;
             float candZ = worldZ + float(oz) * tile;
             if (!terrain.isForbiddenWorld(candX, candZ)) {
             if (!terrain.isForbiddenWorld(candX, candZ)) {
@@ -164,8 +165,9 @@ MapTransformer::applyToWorld(const MapDefinition &def,
       continue;
       continue;
     }
     }
 
 
-    if (!e)
+    if (!e) {
       continue;
       continue;
+    }
 
 
     if (auto *r = e->getComponent<Engine::Core::RenderableComponent>()) {
     if (auto *r = e->getComponent<Engine::Core::RenderableComponent>()) {
       if (visuals) {
       if (visuals) {

+ 9 - 5
game/map/skirmish_loader.cpp

@@ -233,12 +233,14 @@ SkirmishLoadResult SkirmishLoader::start(const QString &mapPath,
   auto &terrainService = Game::Map::TerrainService::instance();
   auto &terrainService = Game::Map::TerrainService::instance();
 
 
   if (m_ground) {
   if (m_ground) {
-    if (lr.ok)
+    if (lr.ok) {
       m_ground->configure(lr.tileSize, lr.gridWidth, lr.gridHeight);
       m_ground->configure(lr.tileSize, lr.gridWidth, lr.gridHeight);
-    else
+    } else {
       m_ground->configureExtent(50.0f);
       m_ground->configureExtent(50.0f);
-    if (terrainService.isInitialized())
+    }
+    if (terrainService.isInitialized()) {
       m_ground->setBiome(terrainService.biomeSettings());
       m_ground->setBiome(terrainService.biomeSettings());
+    }
   }
   }
 
 
   if (m_terrain) {
   if (m_terrain) {
@@ -360,11 +362,13 @@ SkirmishLoadResult SkirmishLoader::start(const QString &mapPath,
 
 
   auto candidates = m_world.getEntitiesWith<Engine::Core::UnitComponent>();
   auto candidates = m_world.getEntitiesWith<Engine::Core::UnitComponent>();
   for (auto *e : candidates) {
   for (auto *e : candidates) {
-    if (!e)
+    if (!e) {
       continue;
       continue;
+    }
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
-    if (!u)
+    if (!u) {
       continue;
       continue;
+    }
     if (u->spawnType == Game::Units::SpawnType::Barracks &&
     if (u->spawnType == Game::Units::SpawnType::Barracks &&
         u->ownerId == playerOwnerId && u->health > 0) {
         u->ownerId == playerOwnerId && u->health > 0) {
       focusEntity = e;
       focusEntity = e;

+ 42 - 21
game/map/terrain.cpp

@@ -248,12 +248,14 @@ void TerrainHeightMap::buildFromFeatures(
 
 
           for (int oz = -1; oz <= 1; ++oz) {
           for (int oz = -1; oz <= 1; ++oz) {
             for (int ox = -1; ox <= 1; ++ox) {
             for (int ox = -1; ox <= 1; ++ox) {
-              if (ox == 0 && oz == 0)
+              if (ox == 0 && oz == 0) {
                 continue;
                 continue;
+              }
               int nx = ix + ox;
               int nx = ix + ox;
               int nz = iz + oz;
               int nz = iz + oz;
-              if (!inBounds(nx, nz))
+              if (!inBounds(nx, nz)) {
                 continue;
                 continue;
+              }
 
 
               const float nDx = float(nx) - gridCenterX;
               const float nDx = float(nx) - gridCenterX;
               const float nDz = float(nz) - gridCenterZ;
               const float nDz = float(nz) - gridCenterZ;
@@ -307,13 +309,15 @@ void TerrainHeightMap::buildFromFeatures(
         const float dx = float(x) - gridCenterX;
         const float dx = float(x) - gridCenterX;
         const float dz = float(z) - gridCenterZ;
         const float dz = float(z) - gridCenterZ;
         const float dist = std::sqrt(dx * dx + dz * dz);
         const float dist = std::sqrt(dx * dx + dz * dz);
-        if (dist > flatRadius)
+        if (dist > flatRadius) {
           continue;
           continue;
+        }
 
 
         float t = dist / std::max(flatRadius, 0.0001f);
         float t = dist / std::max(flatRadius, 0.0001f);
         float height = feature.height * (1.0f - t);
         float height = feature.height * (1.0f - t);
-        if (height <= 0.0f)
+        if (height <= 0.0f) {
           continue;
           continue;
+        }
 
 
         int idx = indexAt(x, z);
         int idx = indexAt(x, z);
         if (height > m_heights[idx]) {
         if (height > m_heights[idx]) {
@@ -338,8 +342,9 @@ float TerrainHeightMap::getHeightAt(float worldX, float worldZ) const {
   int x1 = x0 + 1;
   int x1 = x0 + 1;
   int z1 = z0 + 1;
   int z1 = z0 + 1;
 
 
-  if (!inBounds(x0, z0))
+  if (!inBounds(x0, z0)) {
     return 0.0f;
     return 0.0f;
+  }
 
 
   float tx = gx - x0;
   float tx = gx - x0;
   float tz = gz - z0;
   float tz = gz - z0;
@@ -356,22 +361,26 @@ float TerrainHeightMap::getHeightAt(float worldX, float worldZ) const {
 }
 }
 
 
 float TerrainHeightMap::getHeightAtGrid(int gridX, int gridZ) const {
 float TerrainHeightMap::getHeightAtGrid(int gridX, int gridZ) const {
-  if (!inBounds(gridX, gridZ))
+  if (!inBounds(gridX, gridZ)) {
     return 0.0f;
     return 0.0f;
+  }
   return m_heights[indexAt(gridX, gridZ)];
   return m_heights[indexAt(gridX, gridZ)];
 }
 }
 
 
 bool TerrainHeightMap::isWalkable(int gridX, int gridZ) const {
 bool TerrainHeightMap::isWalkable(int gridX, int gridZ) const {
-  if (!inBounds(gridX, gridZ))
+  if (!inBounds(gridX, gridZ)) {
     return false;
     return false;
+  }
 
 
   TerrainType type = m_terrainTypes[indexAt(gridX, gridZ)];
   TerrainType type = m_terrainTypes[indexAt(gridX, gridZ)];
 
 
-  if (type == TerrainType::Mountain)
+  if (type == TerrainType::Mountain) {
     return false;
     return false;
+  }
 
 
-  if (type == TerrainType::River)
+  if (type == TerrainType::River) {
     return false;
     return false;
+  }
 
 
   if (type == TerrainType::Hill) {
   if (type == TerrainType::Hill) {
     return m_hillWalkable[indexAt(gridX, gridZ)];
     return m_hillWalkable[indexAt(gridX, gridZ)];
@@ -381,28 +390,33 @@ bool TerrainHeightMap::isWalkable(int gridX, int gridZ) const {
 }
 }
 
 
 bool TerrainHeightMap::isHillEntrance(int gridX, int gridZ) const {
 bool TerrainHeightMap::isHillEntrance(int gridX, int gridZ) const {
-  if (!inBounds(gridX, gridZ))
+  if (!inBounds(gridX, gridZ)) {
     return false;
     return false;
+  }
   return m_hillEntrances[indexAt(gridX, gridZ)];
   return m_hillEntrances[indexAt(gridX, gridZ)];
 }
 }
 
 
 TerrainType TerrainHeightMap::getTerrainType(int gridX, int gridZ) const {
 TerrainType TerrainHeightMap::getTerrainType(int gridX, int gridZ) const {
-  if (!inBounds(gridX, gridZ))
+  if (!inBounds(gridX, gridZ)) {
     return TerrainType::Flat;
     return TerrainType::Flat;
+  }
   return m_terrainTypes[indexAt(gridX, gridZ)];
   return m_terrainTypes[indexAt(gridX, gridZ)];
 }
 }
 
 
 bool TerrainHeightMap::isRiverOrNearby(int gridX, int gridZ, int margin) const {
 bool TerrainHeightMap::isRiverOrNearby(int gridX, int gridZ, int margin) const {
-  if (!inBounds(gridX, gridZ))
+  if (!inBounds(gridX, gridZ)) {
     return false;
     return false;
+  }
 
 
-  if (m_terrainTypes[indexAt(gridX, gridZ)] == TerrainType::River)
+  if (m_terrainTypes[indexAt(gridX, gridZ)] == TerrainType::River) {
     return true;
     return true;
+  }
 
 
   for (int dz = -margin; dz <= margin; ++dz) {
   for (int dz = -margin; dz <= margin; ++dz) {
     for (int dx = -margin; dx <= margin; ++dx) {
     for (int dx = -margin; dx <= margin; ++dx) {
-      if (dx == 0 && dz == 0)
+      if (dx == 0 && dz == 0) {
         continue;
         continue;
+      }
       int nx = gridX + dx;
       int nx = gridX + dx;
       int nz = gridZ + dz;
       int nz = gridZ + dz;
       if (inBounds(nx, nz) &&
       if (inBounds(nx, nz) &&
@@ -428,8 +442,9 @@ float TerrainHeightMap::calculateFeatureHeight(const TerrainFeature &feature,
   float dz = worldZ - feature.centerZ;
   float dz = worldZ - feature.centerZ;
   float dist = std::sqrt(dx * dx + dz * dz);
   float dist = std::sqrt(dx * dx + dz * dz);
 
 
-  if (dist > feature.radius)
+  if (dist > feature.radius) {
     return 0.0f;
     return 0.0f;
+  }
 
 
   float t = dist / feature.radius;
   float t = dist / feature.radius;
   float heightFactor = (std::cos(t * M_PI) + 1.0f) * 0.5f;
   float heightFactor = (std::cos(t * M_PI) + 1.0f) * 0.5f;
@@ -438,12 +453,14 @@ float TerrainHeightMap::calculateFeatureHeight(const TerrainFeature &feature,
 }
 }
 
 
 void TerrainHeightMap::applyBiomeVariation(const BiomeSettings &settings) {
 void TerrainHeightMap::applyBiomeVariation(const BiomeSettings &settings) {
-  if (m_heights.empty())
+  if (m_heights.empty()) {
     return;
     return;
+  }
 
 
   const float amplitude = std::max(0.0f, settings.heightNoiseAmplitude);
   const float amplitude = std::max(0.0f, settings.heightNoiseAmplitude);
-  if (amplitude <= 0.0001f)
+  if (amplitude <= 0.0001f) {
     return;
     return;
+  }
 
 
   const float frequency = std::max(0.0001f, settings.heightNoiseFrequency);
   const float frequency = std::max(0.0001f, settings.heightNoiseFrequency);
   const float halfWidth = m_width * 0.5f - 0.5f;
   const float halfWidth = m_width * 0.5f - 0.5f;
@@ -453,8 +470,9 @@ void TerrainHeightMap::applyBiomeVariation(const BiomeSettings &settings) {
     for (int x = 0; x < m_width; ++x) {
     for (int x = 0; x < m_width; ++x) {
       int idx = indexAt(x, z);
       int idx = indexAt(x, z);
       TerrainType type = m_terrainTypes[idx];
       TerrainType type = m_terrainTypes[idx];
-      if (type == TerrainType::Mountain)
+      if (type == TerrainType::Mountain) {
         continue;
         continue;
+      }
 
 
       float worldX = (static_cast<float>(x) - halfWidth) * m_tileSize;
       float worldX = (static_cast<float>(x) - halfWidth) * m_tileSize;
       float worldZ = (static_cast<float>(z) - halfHeight) * m_tileSize;
       float worldZ = (static_cast<float>(z) - halfHeight) * m_tileSize;
@@ -468,8 +486,9 @@ void TerrainHeightMap::applyBiomeVariation(const BiomeSettings &settings) {
       float blended = 0.65f * baseNoise + 0.35f * detailNoise;
       float blended = 0.65f * baseNoise + 0.35f * detailNoise;
       float perturb = (blended - 0.5f) * 2.0f * amplitude;
       float perturb = (blended - 0.5f) * 2.0f * amplitude;
 
 
-      if (type == TerrainType::Hill)
+      if (type == TerrainType::Hill) {
         perturb *= 0.6f;
         perturb *= 0.6f;
+      }
 
 
       m_heights[idx] = std::max(0.0f, m_heights[idx] + perturb);
       m_heights[idx] = std::max(0.0f, m_heights[idx] + perturb);
     }
     }
@@ -486,8 +505,9 @@ void TerrainHeightMap::addRiverSegments(
   for (const auto &river : riverSegments) {
   for (const auto &river : riverSegments) {
     QVector3D dir = river.end - river.start;
     QVector3D dir = river.end - river.start;
     float length = dir.length();
     float length = dir.length();
-    if (length < 0.01f)
+    if (length < 0.01f) {
       continue;
       continue;
+    }
 
 
     dir.normalize();
     dir.normalize();
     QVector3D perpendicular(-dir.z(), 0.0f, dir.x());
     QVector3D perpendicular(-dir.z(), 0.0f, dir.x());
@@ -545,8 +565,9 @@ void TerrainHeightMap::addBridges(const std::vector<Bridge> &bridges) {
   for (const auto &bridge : bridges) {
   for (const auto &bridge : bridges) {
     QVector3D dir = bridge.end - bridge.start;
     QVector3D dir = bridge.end - bridge.start;
     float length = dir.length();
     float length = dir.length();
-    if (length < 0.01f)
+    if (length < 0.01f) {
       continue;
       continue;
+    }
 
 
     dir.normalize();
     dir.normalize();
     QVector3D perpendicular(-dir.z(), 0.0f, dir.x());
     QVector3D perpendicular(-dir.z(), 0.0f, dir.x());

+ 18 - 9
game/map/terrain_service.cpp

@@ -29,29 +29,34 @@ void TerrainService::clear() {
 }
 }
 
 
 float TerrainService::getTerrainHeight(float worldX, float worldZ) const {
 float TerrainService::getTerrainHeight(float worldX, float worldZ) const {
-  if (!m_heightMap)
+  if (!m_heightMap) {
     return 0.0f;
     return 0.0f;
+  }
   return m_heightMap->getHeightAt(worldX, worldZ);
   return m_heightMap->getHeightAt(worldX, worldZ);
 }
 }
 
 
 float TerrainService::getTerrainHeightGrid(int gridX, int gridZ) const {
 float TerrainService::getTerrainHeightGrid(int gridX, int gridZ) const {
-  if (!m_heightMap)
+  if (!m_heightMap) {
     return 0.0f;
     return 0.0f;
+  }
   return m_heightMap->getHeightAtGrid(gridX, gridZ);
   return m_heightMap->getHeightAtGrid(gridX, gridZ);
 }
 }
 
 
 bool TerrainService::isWalkable(int gridX, int gridZ) const {
 bool TerrainService::isWalkable(int gridX, int gridZ) const {
-  if (!m_heightMap)
+  if (!m_heightMap) {
     return true;
     return true;
+  }
   return m_heightMap->isWalkable(gridX, gridZ);
   return m_heightMap->isWalkable(gridX, gridZ);
 }
 }
 
 
 bool TerrainService::isForbidden(int gridX, int gridZ) const {
 bool TerrainService::isForbidden(int gridX, int gridZ) const {
-  if (!m_heightMap)
+  if (!m_heightMap) {
     return false;
     return false;
+  }
 
 
-  if (!m_heightMap->isWalkable(gridX, gridZ))
+  if (!m_heightMap->isWalkable(gridX, gridZ)) {
     return true;
     return true;
+  }
 
 
   float halfW = m_heightMap->getWidth() * 0.5f - 0.5f;
   float halfW = m_heightMap->getWidth() * 0.5f - 0.5f;
   float halfH = m_heightMap->getHeight() * 0.5f - 0.5f;
   float halfH = m_heightMap->getHeight() * 0.5f - 0.5f;
@@ -60,15 +65,17 @@ bool TerrainService::isForbidden(int gridX, int gridZ) const {
   float worldZ = (static_cast<float>(gridZ) - halfH) * tile;
   float worldZ = (static_cast<float>(gridZ) - halfH) * tile;
 
 
   auto &registry = Game::Systems::BuildingCollisionRegistry::instance();
   auto &registry = Game::Systems::BuildingCollisionRegistry::instance();
-  if (registry.isPointInBuilding(worldX, worldZ))
+  if (registry.isPointInBuilding(worldX, worldZ)) {
     return true;
     return true;
+  }
 
 
   return false;
   return false;
 }
 }
 
 
 bool TerrainService::isForbiddenWorld(float worldX, float worldZ) const {
 bool TerrainService::isForbiddenWorld(float worldX, float worldZ) const {
-  if (!m_heightMap)
+  if (!m_heightMap) {
     return false;
     return false;
+  }
 
 
   const float gridHalfWidth = m_heightMap->getWidth() * 0.5f - 0.5f;
   const float gridHalfWidth = m_heightMap->getWidth() * 0.5f - 0.5f;
   const float gridHalfHeight = m_heightMap->getHeight() * 0.5f - 0.5f;
   const float gridHalfHeight = m_heightMap->getHeight() * 0.5f - 0.5f;
@@ -82,14 +89,16 @@ bool TerrainService::isForbiddenWorld(float worldX, float worldZ) const {
 }
 }
 
 
 bool TerrainService::isHillEntrance(int gridX, int gridZ) const {
 bool TerrainService::isHillEntrance(int gridX, int gridZ) const {
-  if (!m_heightMap)
+  if (!m_heightMap) {
     return false;
     return false;
+  }
   return m_heightMap->isHillEntrance(gridX, gridZ);
   return m_heightMap->isHillEntrance(gridX, gridZ);
 }
 }
 
 
 TerrainType TerrainService::getTerrainType(int gridX, int gridZ) const {
 TerrainType TerrainService::getTerrainType(int gridX, int gridZ) const {
-  if (!m_heightMap)
+  if (!m_heightMap) {
     return TerrainType::Flat;
     return TerrainType::Flat;
+  }
   return m_heightMap->getTerrainType(gridX, gridZ);
   return m_heightMap->getTerrainType(gridX, gridZ);
 }
 }
 
 

+ 34 - 18
game/map/visibility_service.cpp

@@ -44,8 +44,9 @@ void VisibilityService::initialize(int width, int height, float tileSize) {
 }
 }
 
 
 void VisibilityService::reset() {
 void VisibilityService::reset() {
-  if (!m_initialized)
+  if (!m_initialized) {
     return;
     return;
+  }
   std::unique_lock lock(m_cellsMutex);
   std::unique_lock lock(m_cellsMutex);
   std::fill(m_cells.begin(), m_cells.end(),
   std::fill(m_cells.begin(), m_cells.end(),
             static_cast<std::uint8_t>(VisibilityState::Unseen));
             static_cast<std::uint8_t>(VisibilityState::Unseen));
@@ -53,8 +54,9 @@ void VisibilityService::reset() {
 }
 }
 
 
 bool VisibilityService::update(Engine::Core::World &world, int playerId) {
 bool VisibilityService::update(Engine::Core::World &world, int playerId) {
-  if (!m_initialized)
+  if (!m_initialized) {
     return false;
     return false;
+  }
 
 
   bool integrated = integrateCompletedJob();
   bool integrated = integrateCompletedJob();
 
 
@@ -69,8 +71,9 @@ bool VisibilityService::update(Engine::Core::World &world, int playerId) {
 
 
 void VisibilityService::computeImmediate(Engine::Core::World &world,
 void VisibilityService::computeImmediate(Engine::Core::World &world,
                                          int playerId) {
                                          int playerId) {
-  if (!m_initialized)
+  if (!m_initialized) {
     return;
     return;
+  }
 
 
   auto sources = gatherVisionSources(world, playerId);
   auto sources = gatherVisionSources(world, playerId);
   auto payload = composeJobPayload(sources);
   auto payload = composeJobPayload(sources);
@@ -95,25 +98,29 @@ VisibilityService::gatherVisionSources(Engine::Core::World &world,
   for (auto *entity : entities) {
   for (auto *entity : entities) {
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
-    if (!transform || !unit)
+    if (!transform || !unit) {
       continue;
       continue;
+    }
 
 
-    // Skip neutral entities - they should not contribute to fog of war
-    if (Game::Core::isNeutralOwner(unit->ownerId))
+    if (Game::Core::isNeutralOwner(unit->ownerId)) {
       continue;
       continue;
+    }
 
 
     if (unit->ownerId != playerId &&
     if (unit->ownerId != playerId &&
-        !ownerRegistry.areAllies(playerId, unit->ownerId))
+        !ownerRegistry.areAllies(playerId, unit->ownerId)) {
       continue;
       continue;
+    }
 
 
-    if (unit->health <= 0)
+    if (unit->health <= 0) {
       continue;
       continue;
+    }
 
 
     const float visionRange = std::max(unit->visionRange, kDefaultVisionRange);
     const float visionRange = std::max(unit->visionRange, kDefaultVisionRange);
     const int centerX = worldToGrid(transform->position.x, m_halfWidth);
     const int centerX = worldToGrid(transform->position.x, m_halfWidth);
     const int centerZ = worldToGrid(transform->position.z, m_halfHeight);
     const int centerZ = worldToGrid(transform->position.z, m_halfHeight);
-    if (!inBounds(centerX, centerZ))
+    if (!inBounds(centerX, centerZ)) {
       continue;
       continue;
+    }
 
 
     const int cellRadius =
     const int cellRadius =
         std::max(1, static_cast<int>(std::ceil(visionRange / m_tileSize)));
         std::max(1, static_cast<int>(std::ceil(visionRange / m_tileSize)));
@@ -140,12 +147,14 @@ void VisibilityService::startAsyncJob(JobPayload &&payload) {
 }
 }
 
 
 bool VisibilityService::integrateCompletedJob() {
 bool VisibilityService::integrateCompletedJob() {
-  if (!m_jobActive.load(std::memory_order_acquire))
+  if (!m_jobActive.load(std::memory_order_acquire)) {
     return false;
     return false;
+  }
 
 
   if (m_pendingJob.wait_for(std::chrono::seconds(0)) !=
   if (m_pendingJob.wait_for(std::chrono::seconds(0)) !=
-      std::future_status::ready)
+      std::future_status::ready) {
     return false;
     return false;
+  }
 
 
   auto result = m_pendingJob.get();
   auto result = m_pendingJob.get();
   m_jobActive.store(false, std::memory_order_release);
   m_jobActive.store(false, std::memory_order_release);
@@ -170,13 +179,15 @@ VisibilityService::JobResult VisibilityService::executeJob(JobPayload payload) {
   for (const auto &src : payload.sources) {
   for (const auto &src : payload.sources) {
     for (int dz = -src.cellRadius; dz <= src.cellRadius; ++dz) {
     for (int dz = -src.cellRadius; dz <= src.cellRadius; ++dz) {
       const int gz = src.centerZ + dz;
       const int gz = src.centerZ + dz;
-      if (!inBoundsStatic(src.centerX, gz, payload.width, payload.height))
+      if (!inBoundsStatic(src.centerX, gz, payload.width, payload.height)) {
         continue;
         continue;
+      }
       const float worldDz = dz * payload.tileSize;
       const float worldDz = dz * payload.tileSize;
       for (int dx = -src.cellRadius; dx <= src.cellRadius; ++dx) {
       for (int dx = -src.cellRadius; dx <= src.cellRadius; ++dx) {
         const int gx = src.centerX + dx;
         const int gx = src.centerX + dx;
-        if (!inBoundsStatic(gx, gz, payload.width, payload.height))
+        if (!inBoundsStatic(gx, gz, payload.width, payload.height)) {
           continue;
           continue;
+        }
         const float worldDx = dx * payload.tileSize;
         const float worldDx = dx * payload.tileSize;
         const float distSq = worldDx * worldDx + worldDz * worldDz;
         const float distSq = worldDx * worldDx + worldDz * worldDz;
         if (distSq <= src.expandedRangeSq) {
         if (distSq <= src.expandedRangeSq) {
@@ -212,31 +223,36 @@ VisibilityService::JobResult VisibilityService::executeJob(JobPayload payload) {
 }
 }
 
 
 VisibilityState VisibilityService::stateAt(int gridX, int gridZ) const {
 VisibilityState VisibilityService::stateAt(int gridX, int gridZ) const {
-  if (!m_initialized || !inBounds(gridX, gridZ))
+  if (!m_initialized || !inBounds(gridX, gridZ)) {
     return VisibilityState::Visible;
     return VisibilityState::Visible;
+  }
   std::shared_lock lock(m_cellsMutex);
   std::shared_lock lock(m_cellsMutex);
   return static_cast<VisibilityState>(m_cells[index(gridX, gridZ)]);
   return static_cast<VisibilityState>(m_cells[index(gridX, gridZ)]);
 }
 }
 
 
 bool VisibilityService::isVisibleWorld(float worldX, float worldZ) const {
 bool VisibilityService::isVisibleWorld(float worldX, float worldZ) const {
-  if (!m_initialized)
+  if (!m_initialized) {
     return true;
     return true;
+  }
   const int gx = worldToGrid(worldX, m_halfWidth);
   const int gx = worldToGrid(worldX, m_halfWidth);
   const int gz = worldToGrid(worldZ, m_halfHeight);
   const int gz = worldToGrid(worldZ, m_halfHeight);
-  if (!inBounds(gx, gz))
+  if (!inBounds(gx, gz)) {
     return false;
     return false;
+  }
   std::shared_lock lock(m_cellsMutex);
   std::shared_lock lock(m_cellsMutex);
   return m_cells[index(gx, gz)] ==
   return m_cells[index(gx, gz)] ==
          static_cast<std::uint8_t>(VisibilityState::Visible);
          static_cast<std::uint8_t>(VisibilityState::Visible);
 }
 }
 
 
 bool VisibilityService::isExploredWorld(float worldX, float worldZ) const {
 bool VisibilityService::isExploredWorld(float worldX, float worldZ) const {
-  if (!m_initialized)
+  if (!m_initialized) {
     return true;
     return true;
+  }
   const int gx = worldToGrid(worldX, m_halfWidth);
   const int gx = worldToGrid(worldX, m_halfWidth);
   const int gz = worldToGrid(worldZ, m_halfHeight);
   const int gz = worldToGrid(worldZ, m_halfHeight);
-  if (!inBounds(gx, gz))
+  if (!inBounds(gx, gz)) {
     return false;
     return false;
+  }
   std::shared_lock lock(m_cellsMutex);
   std::shared_lock lock(m_cellsMutex);
   const auto state = m_cells[index(gx, gz)];
   const auto state = m_cells[index(gx, gz)];
   return state == static_cast<std::uint8_t>(VisibilityState::Visible) ||
   return state == static_cast<std::uint8_t>(VisibilityState::Visible) ||

+ 6 - 3
game/systems/ai_system.cpp

@@ -60,8 +60,9 @@ void AISystem::initializeAIPlayers() {
 AISystem::~AISystem() {}
 AISystem::~AISystem() {}
 
 
 void AISystem::update(Engine::Core::World *world, float deltaTime) {
 void AISystem::update(Engine::Core::World *world, float deltaTime) {
-  if (!world)
+  if (!world) {
     return;
     return;
+  }
 
 
   m_totalGameTime += deltaTime;
   m_totalGameTime += deltaTime;
 
 
@@ -73,11 +74,13 @@ void AISystem::update(Engine::Core::World *world, float deltaTime) {
 
 
     ai.updateTimer += deltaTime;
     ai.updateTimer += deltaTime;
 
 
-    if (ai.updateTimer < 0.3f)
+    if (ai.updateTimer < 0.3f) {
       continue;
       continue;
+    }
 
 
-    if (ai.worker->busy())
+    if (ai.worker->busy()) {
       continue;
       continue;
+    }
 
 
     AI::AISnapshot snapshot =
     AI::AISnapshot snapshot =
         m_snapshotBuilder.build(*world, ai.context.playerId);
         m_snapshotBuilder.build(*world, ai.context.playerId);

+ 18 - 9
game/systems/ai_system/ai_command_applier.cpp

@@ -17,8 +17,9 @@ void AICommandApplier::apply(Engine::Core::World &world, int aiOwnerId,
     switch (command.type) {
     switch (command.type) {
 
 
     case AICommandType::MoveUnits: {
     case AICommandType::MoveUnits: {
-      if (command.units.empty())
+      if (command.units.empty()) {
         break;
         break;
+      }
 
 
       std::vector<float> expandedX, expandedY, expandedZ;
       std::vector<float> expandedX, expandedY, expandedZ;
 
 
@@ -32,8 +33,9 @@ void AICommandApplier::apply(Engine::Core::World &world, int aiOwnerId,
         expandedZ = command.moveTargetZ;
         expandedZ = command.moveTargetZ;
       }
       }
 
 
-      if (expandedX.empty())
+      if (expandedX.empty()) {
         break;
         break;
+      }
 
 
       std::vector<Engine::Core::EntityID> ownedUnits;
       std::vector<Engine::Core::EntityID> ownedUnits;
       std::vector<QVector3D> ownedTargets;
       std::vector<QVector3D> ownedTargets;
@@ -43,20 +45,23 @@ void AICommandApplier::apply(Engine::Core::World &world, int aiOwnerId,
       for (std::size_t idx = 0; idx < command.units.size(); ++idx) {
       for (std::size_t idx = 0; idx < command.units.size(); ++idx) {
         auto entityId = command.units[idx];
         auto entityId = command.units[idx];
         auto *entity = world.getEntity(entityId);
         auto *entity = world.getEntity(entityId);
-        if (!entity)
+        if (!entity) {
           continue;
           continue;
+        }
 
 
         auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
         auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
-        if (!unit || unit->ownerId != aiOwnerId)
+        if (!unit || unit->ownerId != aiOwnerId) {
           continue;
           continue;
+        }
 
 
         ownedUnits.push_back(entityId);
         ownedUnits.push_back(entityId);
         ownedTargets.emplace_back(expandedX[idx], expandedY[idx],
         ownedTargets.emplace_back(expandedX[idx], expandedY[idx],
                                   expandedZ[idx]);
                                   expandedZ[idx]);
       }
       }
 
 
-      if (ownedUnits.empty())
+      if (ownedUnits.empty()) {
         break;
         break;
+      }
 
 
       CommandService::MoveOptions opts;
       CommandService::MoveOptions opts;
       opts.allowDirectFallback = true;
       opts.allowDirectFallback = true;
@@ -67,26 +72,30 @@ void AICommandApplier::apply(Engine::Core::World &world, int aiOwnerId,
     }
     }
 
 
     case AICommandType::AttackTarget: {
     case AICommandType::AttackTarget: {
-      if (command.units.empty() || command.targetId == 0)
+      if (command.units.empty() || command.targetId == 0) {
         break;
         break;
+      }
 
 
       std::vector<Engine::Core::EntityID> ownedUnits;
       std::vector<Engine::Core::EntityID> ownedUnits;
       ownedUnits.reserve(command.units.size());
       ownedUnits.reserve(command.units.size());
 
 
       for (auto entityId : command.units) {
       for (auto entityId : command.units) {
         auto *entity = world.getEntity(entityId);
         auto *entity = world.getEntity(entityId);
-        if (!entity)
+        if (!entity) {
           continue;
           continue;
+        }
 
 
         auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
         auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
-        if (!unit || unit->ownerId != aiOwnerId)
+        if (!unit || unit->ownerId != aiOwnerId) {
           continue;
           continue;
+        }
 
 
         ownedUnits.push_back(entityId);
         ownedUnits.push_back(entityId);
       }
       }
 
 
-      if (ownedUnits.empty())
+      if (ownedUnits.empty()) {
         break;
         break;
+      }
 
 
       CommandService::attackTarget(world, ownedUnits, command.targetId,
       CommandService::attackTarget(world, ownedUnits, command.targetId,
                                    command.shouldChase);
                                    command.shouldChase);

+ 6 - 3
game/systems/ai_system/ai_command_filter.cpp

@@ -152,14 +152,17 @@ bool AICommandFilter::CommandHistory::isSimilarTo(const AICommandType &cmdType,
                                                   float currentTime,
                                                   float currentTime,
                                                   float cooldown) const {
                                                   float cooldown) const {
 
 
-  if (unitId != unit)
+  if (unitId != unit) {
     return false;
     return false;
+  }
 
 
-  if (type != cmdType)
+  if (type != cmdType) {
     return false;
     return false;
+  }
 
 
-  if ((currentTime - issuedTime) > cooldown)
+  if ((currentTime - issuedTime) > cooldown) {
     return false;
     return false;
+  }
 
 
   switch (cmdType) {
   switch (cmdType) {
   case AICommandType::AttackTarget:
   case AICommandType::AttackTarget:

+ 2 - 1
game/systems/ai_system/ai_reasoner.cpp

@@ -180,8 +180,9 @@ void AIReasoner::updateStateMachine(AIContext &ctx, float deltaTime) {
   }
   }
 
 
   if (ctx.decisionTimer < 2.0f) {
   if (ctx.decisionTimer < 2.0f) {
-    if (ctx.state != previousState)
+    if (ctx.state != previousState) {
       ctx.stateTimer = 0.0f;
       ctx.stateTimer = 0.0f;
+    }
     return;
     return;
   }
   }
 
 

+ 4 - 2
game/systems/ai_system/ai_snapshot_builder.cpp

@@ -80,12 +80,14 @@ AISnapshot AISnapshotBuilder::build(const Engine::Core::World &world,
 
 
   for (auto *entity : enemies) {
   for (auto *entity : enemies) {
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
-    if (!unit || unit->health <= 0)
+    if (!unit || unit->health <= 0) {
       continue;
       continue;
+    }
 
 
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
-    if (!transform)
+    if (!transform) {
       continue;
       continue;
+    }
 
 
     ContactSnapshot contact;
     ContactSnapshot contact;
     contact.id = entity->getId();
     contact.id = entity->getId();

+ 2 - 1
game/systems/ai_system/ai_tactical.cpp

@@ -185,8 +185,9 @@ bool TacticalUtils::isTargetIsolated(
 
 
   for (const auto *enemy : allEnemies) {
   for (const auto *enemy : allEnemies) {
 
 
-    if (enemy->id == target.id)
+    if (enemy->id == target.id) {
       continue;
       continue;
+    }
 
 
     float distSq = distanceSquared(target.posX, target.posY, target.posZ,
     float distSq = distanceSquared(target.posX, target.posY, target.posZ,
                                    enemy->posX, enemy->posY, enemy->posZ);
                                    enemy->posX, enemy->posY, enemy->posZ);

+ 22 - 11
game/systems/ai_system/behaviors/attack_behavior.cpp

@@ -14,12 +14,14 @@ void AttackBehavior::execute(const AISnapshot &snapshot, AIContext &context,
   m_attackTimer += deltaTime;
   m_attackTimer += deltaTime;
   m_targetLockDuration += deltaTime;
   m_targetLockDuration += deltaTime;
 
 
-  if (m_attackTimer < 1.5f)
+  if (m_attackTimer < 1.5f) {
     return;
     return;
+  }
   m_attackTimer = 0.0f;
   m_attackTimer = 0.0f;
 
 
-  if (snapshot.visibleEnemies.empty())
+  if (snapshot.visibleEnemies.empty()) {
     return;
     return;
+  }
 
 
   std::vector<const EntitySnapshot *> engagedUnits;
   std::vector<const EntitySnapshot *> engagedUnits;
   std::vector<const EntitySnapshot *> readyUnits;
   std::vector<const EntitySnapshot *> readyUnits;
@@ -31,8 +33,9 @@ void AttackBehavior::execute(const AISnapshot &snapshot, AIContext &context,
   float groupCenterZ = 0.0f;
   float groupCenterZ = 0.0f;
 
 
   for (const auto &entity : snapshot.friendlies) {
   for (const auto &entity : snapshot.friendlies) {
-    if (entity.isBuilding)
+    if (entity.isBuilding) {
       continue;
       continue;
+    }
 
 
     if (isEntityEngaged(entity, snapshot.visibleEnemies)) {
     if (isEntityEngaged(entity, snapshot.visibleEnemies)) {
       engagedUnits.push_back(&entity);
       engagedUnits.push_back(&entity);
@@ -209,8 +212,9 @@ void AttackBehavior::execute(const AISnapshot &snapshot, AIContext &context,
       readyUnits, nearbyEnemies, groupCenterX, groupCenterY, groupCenterZ,
       readyUnits, nearbyEnemies, groupCenterX, groupCenterY, groupCenterZ,
       context, m_lastTarget);
       context, m_lastTarget);
 
 
-  if (targetInfo.targetId == 0)
+  if (targetInfo.targetId == 0) {
     return;
     return;
+  }
 
 
   if (targetInfo.targetId != m_lastTarget) {
   if (targetInfo.targetId != m_lastTarget) {
     m_lastTarget = targetInfo.targetId;
     m_lastTarget = targetInfo.targetId;
@@ -226,8 +230,9 @@ void AttackBehavior::execute(const AISnapshot &snapshot, AIContext &context,
   auto claimedUnits = claimUnits(unitIds, getPriority(), "attacking", context,
   auto claimedUnits = claimUnits(unitIds, getPriority(), "attacking", context,
                                  m_attackTimer + deltaTime, 2.5f);
                                  m_attackTimer + deltaTime, 2.5f);
 
 
-  if (claimedUnits.empty())
+  if (claimedUnits.empty()) {
     return;
     return;
+  }
 
 
   AICommand command;
   AICommand command;
   command.type = AICommandType::AttackTarget;
   command.type = AICommandType::AttackTarget;
@@ -245,28 +250,34 @@ void AttackBehavior::execute(const AISnapshot &snapshot, AIContext &context,
 bool AttackBehavior::shouldExecute(const AISnapshot &snapshot,
 bool AttackBehavior::shouldExecute(const AISnapshot &snapshot,
                                    const AIContext &context) const {
                                    const AIContext &context) const {
 
 
-  if (context.state == AIState::Retreating)
+  if (context.state == AIState::Retreating) {
     return false;
     return false;
+  }
 
 
   int readyUnits = 0;
   int readyUnits = 0;
   for (const auto &entity : snapshot.friendlies) {
   for (const auto &entity : snapshot.friendlies) {
-    if (entity.isBuilding)
+    if (entity.isBuilding) {
       continue;
       continue;
+    }
 
 
-    if (isEntityEngaged(entity, snapshot.visibleEnemies))
+    if (isEntityEngaged(entity, snapshot.visibleEnemies)) {
       continue;
       continue;
+    }
 
 
     ++readyUnits;
     ++readyUnits;
   }
   }
 
 
-  if (readyUnits == 0)
+  if (readyUnits == 0) {
     return false;
     return false;
+  }
 
 
-  if (snapshot.visibleEnemies.empty())
+  if (snapshot.visibleEnemies.empty()) {
     return false;
     return false;
+  }
 
 
-  if (context.state == AIState::Attacking)
+  if (context.state == AIState::Attacking) {
     return true;
     return true;
+  }
 
 
   if (context.state == AIState::Defending) {
   if (context.state == AIState::Defending) {
     return context.barracksUnderThreat && readyUnits >= 2;
     return context.barracksUnderThreat && readyUnits >= 2;

+ 28 - 14
game/systems/ai_system/behaviors/defend_behavior.cpp

@@ -19,12 +19,14 @@ void DefendBehavior::execute(const AISnapshot &snapshot, AIContext &context,
 
 
   float updateInterval = context.barracksUnderThreat ? 0.5f : 1.5f;
   float updateInterval = context.barracksUnderThreat ? 0.5f : 1.5f;
 
 
-  if (m_defendTimer < updateInterval)
+  if (m_defendTimer < updateInterval) {
     return;
     return;
+  }
   m_defendTimer = 0.0f;
   m_defendTimer = 0.0f;
 
 
-  if (context.primaryBarracks == 0)
+  if (context.primaryBarracks == 0) {
     return;
     return;
+  }
 
 
   float defendPosX = 0.0f;
   float defendPosX = 0.0f;
   float defendPosY = 0.0f;
   float defendPosY = 0.0f;
@@ -41,8 +43,9 @@ void DefendBehavior::execute(const AISnapshot &snapshot, AIContext &context,
     }
     }
   }
   }
 
 
-  if (!foundBarracks)
+  if (!foundBarracks) {
     return;
     return;
+  }
 
 
   std::vector<const EntitySnapshot *> readyDefenders;
   std::vector<const EntitySnapshot *> readyDefenders;
   std::vector<const EntitySnapshot *> engagedDefenders;
   std::vector<const EntitySnapshot *> engagedDefenders;
@@ -50,8 +53,9 @@ void DefendBehavior::execute(const AISnapshot &snapshot, AIContext &context,
   engagedDefenders.reserve(snapshot.friendlies.size());
   engagedDefenders.reserve(snapshot.friendlies.size());
 
 
   for (const auto &entity : snapshot.friendlies) {
   for (const auto &entity : snapshot.friendlies) {
-    if (entity.isBuilding)
+    if (entity.isBuilding) {
       continue;
       continue;
+    }
 
 
     if (isEntityEngaged(entity, snapshot.visibleEnemies)) {
     if (isEntityEngaged(entity, snapshot.visibleEnemies)) {
       engagedDefenders.push_back(&entity);
       engagedDefenders.push_back(&entity);
@@ -60,8 +64,9 @@ void DefendBehavior::execute(const AISnapshot &snapshot, AIContext &context,
     }
     }
   }
   }
 
 
-  if (readyDefenders.empty() && engagedDefenders.empty())
+  if (readyDefenders.empty() && engagedDefenders.empty()) {
     return;
     return;
+  }
 
 
   auto sortByDistance = [&](std::vector<const EntitySnapshot *> &list) {
   auto sortByDistance = [&](std::vector<const EntitySnapshot *> &list) {
     std::sort(list.begin(), list.end(),
     std::sort(list.begin(), list.end(),
@@ -93,8 +98,9 @@ void DefendBehavior::execute(const AISnapshot &snapshot, AIContext &context,
   std::size_t readyCount = std::min(desiredCount, readyDefenders.size());
   std::size_t readyCount = std::min(desiredCount, readyDefenders.size());
   readyDefenders.resize(readyCount);
   readyDefenders.resize(readyCount);
 
 
-  if (readyDefenders.empty())
+  if (readyDefenders.empty()) {
     return;
     return;
+  }
 
 
   if (context.barracksUnderThreat || !context.buildingsUnderAttack.empty()) {
   if (context.barracksUnderThreat || !context.buildingsUnderAttack.empty()) {
 
 
@@ -204,8 +210,9 @@ void DefendBehavior::execute(const AISnapshot &snapshot, AIContext &context,
     }
     }
   }
   }
 
 
-  if (unclaimedDefenders.empty())
+  if (unclaimedDefenders.empty()) {
     return;
     return;
+  }
 
 
   const Nation *nation =
   const Nation *nation =
       NationRegistry::instance().getNationForPlayer(context.playerId);
       NationRegistry::instance().getNationForPlayer(context.playerId);
@@ -234,8 +241,9 @@ void DefendBehavior::execute(const AISnapshot &snapshot, AIContext &context,
     float dz = entity->posZ - target.z();
     float dz = entity->posZ - target.z();
     float distanceSq = dx * dx + dz * dz;
     float distanceSq = dx * dx + dz * dz;
 
 
-    if (distanceSq < 1.0f * 1.0f)
+    if (distanceSq < 1.0f * 1.0f) {
       continue;
       continue;
+    }
 
 
     unitsToMove.push_back(entity->id);
     unitsToMove.push_back(entity->id);
     targetX.push_back(target.x());
     targetX.push_back(target.x());
@@ -243,15 +251,17 @@ void DefendBehavior::execute(const AISnapshot &snapshot, AIContext &context,
     targetZ.push_back(target.z());
     targetZ.push_back(target.z());
   }
   }
 
 
-  if (unitsToMove.empty())
+  if (unitsToMove.empty()) {
     return;
     return;
+  }
 
 
   auto claimedForMove =
   auto claimedForMove =
       claimUnits(unitsToMove, BehaviorPriority::Low, "positioning", context,
       claimUnits(unitsToMove, BehaviorPriority::Low, "positioning", context,
                  m_defendTimer + deltaTime, 1.5f);
                  m_defendTimer + deltaTime, 1.5f);
 
 
-  if (claimedForMove.empty())
+  if (claimedForMove.empty()) {
     return;
     return;
+  }
 
 
   std::vector<float> filteredX, filteredY, filteredZ;
   std::vector<float> filteredX, filteredY, filteredZ;
   for (size_t i = 0; i < unitsToMove.size(); ++i) {
   for (size_t i = 0; i < unitsToMove.size(); ++i) {
@@ -276,17 +286,21 @@ bool DefendBehavior::shouldExecute(const AISnapshot &snapshot,
                                    const AIContext &context) const {
                                    const AIContext &context) const {
   (void)snapshot;
   (void)snapshot;
 
 
-  if (context.primaryBarracks == 0)
+  if (context.primaryBarracks == 0) {
     return false;
     return false;
+  }
 
 
-  if (context.barracksUnderThreat || !context.buildingsUnderAttack.empty())
+  if (context.barracksUnderThreat || !context.buildingsUnderAttack.empty()) {
     return true;
     return true;
+  }
 
 
-  if (context.state == AIState::Defending && context.idleUnits > 0)
+  if (context.state == AIState::Defending && context.idleUnits > 0) {
     return true;
     return true;
+  }
 
 
-  if (context.averageHealth < 0.6f && context.totalUnits > 0)
+  if (context.averageHealth < 0.6f && context.totalUnits > 0) {
     return true;
     return true;
+  }
 
 
   return false;
   return false;
 }
 }

+ 24 - 12
game/systems/ai_system/behaviors/gather_behavior.cpp

@@ -13,12 +13,14 @@ void GatherBehavior::execute(const AISnapshot &snapshot, AIContext &context,
                              std::vector<AICommand> &outCommands) {
                              std::vector<AICommand> &outCommands) {
   m_gatherTimer += deltaTime;
   m_gatherTimer += deltaTime;
 
 
-  if (m_gatherTimer < 1.0f)
+  if (m_gatherTimer < 1.0f) {
     return;
     return;
+  }
   m_gatherTimer = 0.0f;
   m_gatherTimer = 0.0f;
 
 
-  if (context.primaryBarracks == 0)
+  if (context.primaryBarracks == 0) {
     return;
     return;
+  }
 
 
   QVector3D rallyPoint(context.rallyX, 0.0f, context.rallyZ);
   QVector3D rallyPoint(context.rallyX, 0.0f, context.rallyZ);
 
 
@@ -26,11 +28,13 @@ void GatherBehavior::execute(const AISnapshot &snapshot, AIContext &context,
   unitsToGather.reserve(snapshot.friendlies.size());
   unitsToGather.reserve(snapshot.friendlies.size());
 
 
   for (const auto &entity : snapshot.friendlies) {
   for (const auto &entity : snapshot.friendlies) {
-    if (entity.isBuilding)
+    if (entity.isBuilding) {
       continue;
       continue;
+    }
 
 
-    if (isEntityEngaged(entity, snapshot.visibleEnemies))
+    if (isEntityEngaged(entity, snapshot.visibleEnemies)) {
       continue;
       continue;
+    }
 
 
     const float dx = entity.posX - rallyPoint.x();
     const float dx = entity.posX - rallyPoint.x();
     const float dz = entity.posZ - rallyPoint.z();
     const float dz = entity.posZ - rallyPoint.z();
@@ -41,8 +45,9 @@ void GatherBehavior::execute(const AISnapshot &snapshot, AIContext &context,
     }
     }
   }
   }
 
 
-  if (unitsToGather.empty())
+  if (unitsToGather.empty()) {
     return;
     return;
+  }
 
 
   const Nation *nation =
   const Nation *nation =
       NationRegistry::instance().getNationForPlayer(context.playerId);
       NationRegistry::instance().getNationForPlayer(context.playerId);
@@ -71,14 +76,16 @@ void GatherBehavior::execute(const AISnapshot &snapshot, AIContext &context,
     targetZ.push_back(target.z());
     targetZ.push_back(target.z());
   }
   }
 
 
-  if (unitsToMove.empty())
+  if (unitsToMove.empty()) {
     return;
     return;
+  }
 
 
   auto claimedUnits = claimUnits(unitsToMove, getPriority(), "gathering",
   auto claimedUnits = claimUnits(unitsToMove, getPriority(), "gathering",
                                  context, m_gatherTimer + deltaTime, 2.0f);
                                  context, m_gatherTimer + deltaTime, 2.0f);
 
 
-  if (claimedUnits.empty())
+  if (claimedUnits.empty()) {
     return;
     return;
+  }
 
 
   std::vector<float> filteredX, filteredY, filteredZ;
   std::vector<float> filteredX, filteredY, filteredZ;
   for (size_t i = 0; i < unitsToMove.size(); ++i) {
   for (size_t i = 0; i < unitsToMove.size(); ++i) {
@@ -102,21 +109,25 @@ void GatherBehavior::execute(const AISnapshot &snapshot, AIContext &context,
 
 
 bool GatherBehavior::shouldExecute(const AISnapshot &snapshot,
 bool GatherBehavior::shouldExecute(const AISnapshot &snapshot,
                                    const AIContext &context) const {
                                    const AIContext &context) const {
-  if (context.primaryBarracks == 0)
+  if (context.primaryBarracks == 0) {
     return false;
     return false;
+  }
 
 
-  if (context.state == AIState::Retreating)
+  if (context.state == AIState::Retreating) {
     return false;
     return false;
+  }
 
 
-  if (context.state == AIState::Attacking)
+  if (context.state == AIState::Attacking) {
     return false;
     return false;
+  }
 
 
   if (context.state == AIState::Defending) {
   if (context.state == AIState::Defending) {
 
 
     QVector3D rallyPoint(context.rallyX, 0.0f, context.rallyZ);
     QVector3D rallyPoint(context.rallyX, 0.0f, context.rallyZ);
     for (const auto &entity : snapshot.friendlies) {
     for (const auto &entity : snapshot.friendlies) {
-      if (entity.isBuilding)
+      if (entity.isBuilding) {
         continue;
         continue;
+      }
 
 
       const float dx = entity.posX - rallyPoint.x();
       const float dx = entity.posX - rallyPoint.x();
       const float dz = entity.posZ - rallyPoint.z();
       const float dz = entity.posZ - rallyPoint.z();
@@ -129,8 +140,9 @@ bool GatherBehavior::shouldExecute(const AISnapshot &snapshot,
     return false;
     return false;
   }
   }
 
 
-  if (context.state == AIState::Gathering || context.state == AIState::Idle)
+  if (context.state == AIState::Gathering || context.state == AIState::Idle) {
     return true;
     return true;
+  }
 
 
   return false;
   return false;
 }
 }

+ 14 - 7
game/systems/ai_system/behaviors/production_behavior.cpp

@@ -9,8 +9,9 @@ void ProductionBehavior::execute(const AISnapshot &snapshot, AIContext &context,
                                  float deltaTime,
                                  float deltaTime,
                                  std::vector<AICommand> &outCommands) {
                                  std::vector<AICommand> &outCommands) {
   m_productionTimer += deltaTime;
   m_productionTimer += deltaTime;
-  if (m_productionTimer < 1.5f)
+  if (m_productionTimer < 1.5f) {
     return;
     return;
+  }
   m_productionTimer = 0.0f;
   m_productionTimer = 0.0f;
 
 
   static int execCounter = 0;
   static int execCounter = 0;
@@ -53,26 +54,31 @@ void ProductionBehavior::execute(const AISnapshot &snapshot, AIContext &context,
 
 
   for (const auto &entity : snapshot.friendlies) {
   for (const auto &entity : snapshot.friendlies) {
     if (!entity.isBuilding ||
     if (!entity.isBuilding ||
-        entity.spawnType != Game::Units::SpawnType::Barracks)
+        entity.spawnType != Game::Units::SpawnType::Barracks) {
       continue;
       continue;
+    }
 
 
-    if (Game::Core::isNeutralOwner(entity.ownerId))
+    if (Game::Core::isNeutralOwner(entity.ownerId)) {
       continue;
       continue;
+    }
 
 
     static int logCounter = 0;
     static int logCounter = 0;
 
 
-    if (!entity.production.hasComponent)
+    if (!entity.production.hasComponent) {
       continue;
       continue;
+    }
 
 
     const auto &prod = entity.production;
     const auto &prod = entity.production;
 
 
-    if (prod.producedCount >= prod.maxUnits)
+    if (prod.producedCount >= prod.maxUnits) {
       continue;
       continue;
+    }
 
 
     const int maxQueueSize = 5;
     const int maxQueueSize = 5;
     int totalInQueue = (prod.inProgress ? 1 : 0) + prod.queueSize;
     int totalInQueue = (prod.inProgress ? 1 : 0) + prod.queueSize;
-    if (totalInQueue >= maxQueueSize)
+    if (totalInQueue >= maxQueueSize) {
       continue;
       continue;
+    }
 
 
     AICommand command;
     AICommand command;
     command.type = AICommandType::StartProduction;
     command.type = AICommandType::StartProduction;
@@ -88,8 +94,9 @@ bool ProductionBehavior::shouldExecute(const AISnapshot &snapshot,
                                        const AIContext &context) const {
                                        const AIContext &context) const {
   (void)snapshot;
   (void)snapshot;
 
 
-  if (context.totalUnits >= context.maxTroopsPerPlayer)
+  if (context.totalUnits >= context.maxTroopsPerPlayer) {
     return false;
     return false;
+  }
 
 
   return true;
   return true;
 }
 }

+ 18 - 9
game/systems/ai_system/behaviors/retreat_behavior.cpp

@@ -12,12 +12,14 @@ void RetreatBehavior::execute(const AISnapshot &snapshot, AIContext &context,
                               float deltaTime,
                               float deltaTime,
                               std::vector<AICommand> &outCommands) {
                               std::vector<AICommand> &outCommands) {
   m_retreatTimer += deltaTime;
   m_retreatTimer += deltaTime;
-  if (m_retreatTimer < 1.0f)
+  if (m_retreatTimer < 1.0f) {
     return;
     return;
+  }
   m_retreatTimer = 0.0f;
   m_retreatTimer = 0.0f;
 
 
-  if (context.primaryBarracks == 0)
+  if (context.primaryBarracks == 0) {
     return;
     return;
+  }
 
 
   std::vector<const EntitySnapshot *> retreatingUnits;
   std::vector<const EntitySnapshot *> retreatingUnits;
   retreatingUnits.reserve(snapshot.friendlies.size());
   retreatingUnits.reserve(snapshot.friendlies.size());
@@ -26,11 +28,13 @@ void RetreatBehavior::execute(const AISnapshot &snapshot, AIContext &context,
   constexpr float LOW_HEALTH = 0.50f;
   constexpr float LOW_HEALTH = 0.50f;
 
 
   for (const auto &entity : snapshot.friendlies) {
   for (const auto &entity : snapshot.friendlies) {
-    if (entity.isBuilding)
+    if (entity.isBuilding) {
       continue;
       continue;
+    }
 
 
-    if (entity.maxHealth <= 0)
+    if (entity.maxHealth <= 0) {
       continue;
       continue;
+    }
 
 
     float healthRatio = static_cast<float>(entity.health) /
     float healthRatio = static_cast<float>(entity.health) /
                         static_cast<float>(entity.maxHealth);
                         static_cast<float>(entity.maxHealth);
@@ -45,8 +49,9 @@ void RetreatBehavior::execute(const AISnapshot &snapshot, AIContext &context,
     }
     }
   }
   }
 
 
-  if (retreatingUnits.empty())
+  if (retreatingUnits.empty()) {
     return;
     return;
+  }
 
 
   QVector3D retreatPos(context.basePosX, context.basePosY, context.basePosZ);
   QVector3D retreatPos(context.basePosX, context.basePosY, context.basePosZ);
 
 
@@ -72,8 +77,9 @@ void RetreatBehavior::execute(const AISnapshot &snapshot, AIContext &context,
   auto claimedUnits = claimUnits(unitIds, getPriority(), "retreating", context,
   auto claimedUnits = claimUnits(unitIds, getPriority(), "retreating", context,
                                  m_retreatTimer + deltaTime, 1.0f);
                                  m_retreatTimer + deltaTime, 1.0f);
 
 
-  if (claimedUnits.empty())
+  if (claimedUnits.empty()) {
     return;
     return;
+  }
 
 
   std::vector<float> filteredX, filteredY, filteredZ;
   std::vector<float> filteredX, filteredY, filteredZ;
   for (size_t i = 0; i < unitIds.size(); ++i) {
   for (size_t i = 0; i < unitIds.size(); ++i) {
@@ -96,17 +102,20 @@ void RetreatBehavior::execute(const AISnapshot &snapshot, AIContext &context,
 
 
 bool RetreatBehavior::shouldExecute(const AISnapshot &snapshot,
 bool RetreatBehavior::shouldExecute(const AISnapshot &snapshot,
                                     const AIContext &context) const {
                                     const AIContext &context) const {
-  if (context.primaryBarracks == 0)
+  if (context.primaryBarracks == 0) {
     return false;
     return false;
+  }
 
 
-  if (context.state == AIState::Retreating)
+  if (context.state == AIState::Retreating) {
     return true;
     return true;
+  }
 
 
   constexpr float CRITICAL_HEALTH = 0.35f;
   constexpr float CRITICAL_HEALTH = 0.35f;
 
 
   for (const auto &entity : snapshot.friendlies) {
   for (const auto &entity : snapshot.friendlies) {
-    if (entity.isBuilding)
+    if (entity.isBuilding) {
       continue;
       continue;
+    }
 
 
     if (entity.maxHealth > 0) {
     if (entity.maxHealth > 0) {
       float healthRatio = static_cast<float>(entity.health) /
       float healthRatio = static_cast<float>(entity.health) /

+ 2 - 1
game/systems/arrow_system.cpp

@@ -28,8 +28,9 @@ void ArrowSystem::spawnArrow(const QVector3D &start, const QVector3D &end,
 
 
 void ArrowSystem::update(Engine::Core::World *world, float deltaTime) {
 void ArrowSystem::update(Engine::Core::World *world, float deltaTime) {
   for (auto &arrow : m_arrows) {
   for (auto &arrow : m_arrows) {
-    if (!arrow.active)
+    if (!arrow.active) {
       continue;
       continue;
+    }
 
 
     arrow.t += deltaTime * arrow.speed * arrow.invDist;
     arrow.t += deltaTime * arrow.speed * arrow.invDist;
     if (arrow.t >= 1.0f) {
     if (arrow.t >= 1.0f) {

+ 12 - 6
game/systems/camera_controller.cpp

@@ -7,40 +7,46 @@ namespace Systems {
 void CameraController::move(Render::GL::Camera &camera, float dx,
 void CameraController::move(Render::GL::Camera &camera, float dx,
                             float dz) const {
                             float dz) const {
   camera.pan(dx, dz);
   camera.pan(dx, dz);
-  if (camera.isFollowEnabled())
+  if (camera.isFollowEnabled()) {
     camera.captureFollowOffset();
     camera.captureFollowOffset();
+  }
 }
 }
 
 
 void CameraController::elevate(Render::GL::Camera &camera, float dy) const {
 void CameraController::elevate(Render::GL::Camera &camera, float dy) const {
   camera.elevate(dy);
   camera.elevate(dy);
-  if (camera.isFollowEnabled())
+  if (camera.isFollowEnabled()) {
     camera.captureFollowOffset();
     camera.captureFollowOffset();
+  }
 }
 }
 
 
 void CameraController::moveUp(Render::GL::Camera &camera, float dy) const {
 void CameraController::moveUp(Render::GL::Camera &camera, float dy) const {
   camera.moveUp(dy);
   camera.moveUp(dy);
-  if (camera.isFollowEnabled())
+  if (camera.isFollowEnabled()) {
     camera.captureFollowOffset();
     camera.captureFollowOffset();
+  }
 }
 }
 
 
 void CameraController::yaw(Render::GL::Camera &camera, float degrees) const {
 void CameraController::yaw(Render::GL::Camera &camera, float degrees) const {
   camera.yaw(degrees);
   camera.yaw(degrees);
-  if (camera.isFollowEnabled())
+  if (camera.isFollowEnabled()) {
     camera.captureFollowOffset();
     camera.captureFollowOffset();
+  }
 }
 }
 
 
 void CameraController::orbit(Render::GL::Camera &camera, float yawDeg,
 void CameraController::orbit(Render::GL::Camera &camera, float yawDeg,
                              float pitchDeg) const {
                              float pitchDeg) const {
   camera.orbit(yawDeg, pitchDeg);
   camera.orbit(yawDeg, pitchDeg);
-  if (camera.isFollowEnabled())
+  if (camera.isFollowEnabled()) {
     camera.captureFollowOffset();
     camera.captureFollowOffset();
+  }
 }
 }
 
 
 void CameraController::zoomDistance(Render::GL::Camera &camera,
 void CameraController::zoomDistance(Render::GL::Camera &camera,
                                     float delta) const {
                                     float delta) const {
   camera.zoomDistance(delta);
   camera.zoomDistance(delta);
-  if (camera.isFollowEnabled())
+  if (camera.isFollowEnabled()) {
     camera.captureFollowOffset();
     camera.captureFollowOffset();
+  }
 }
 }
 
 
 void CameraController::setFollowEnabled(Render::GL::Camera &camera,
 void CameraController::setFollowEnabled(Render::GL::Camera &camera,

+ 4 - 2
game/systems/camera_follow_system.cpp

@@ -11,8 +11,9 @@ void CameraFollowSystem::update(Engine::Core::World &world,
                                 SelectionSystem &selection,
                                 SelectionSystem &selection,
                                 Render::GL::Camera &camera) {
                                 Render::GL::Camera &camera) {
   const auto &sel = selection.getSelectedUnits();
   const auto &sel = selection.getSelectedUnits();
-  if (sel.empty())
+  if (sel.empty()) {
     return;
     return;
+  }
   QVector3D sum(0, 0, 0);
   QVector3D sum(0, 0, 0);
   int count = 0;
   int count = 0;
   for (auto id : sel) {
   for (auto id : sel) {
@@ -34,8 +35,9 @@ void CameraFollowSystem::snapToSelection(Engine::Core::World &world,
                                          SelectionSystem &selection,
                                          SelectionSystem &selection,
                                          Render::GL::Camera &camera) {
                                          Render::GL::Camera &camera) {
   const auto &sel = selection.getSelectedUnits();
   const auto &sel = selection.getSelectedUnits();
-  if (sel.empty())
+  if (sel.empty()) {
     return;
     return;
+  }
   QVector3D sum(0, 0, 0);
   QVector3D sum(0, 0, 0);
   int count = 0;
   int count = 0;
   for (auto id : sel) {
   for (auto id : sel) {

+ 6 - 3
game/systems/camera_service.cpp

@@ -85,19 +85,22 @@ void CameraService::resetCamera(Render::GL::Camera &camera,
                                 unsigned int playerUnitId) {
                                 unsigned int playerUnitId) {
   Engine::Core::Entity *focusEntity = nullptr;
   Engine::Core::Entity *focusEntity = nullptr;
   for (auto *e : world.getEntitiesWith<Engine::Core::UnitComponent>()) {
   for (auto *e : world.getEntitiesWith<Engine::Core::UnitComponent>()) {
-    if (!e)
+    if (!e) {
       continue;
       continue;
+    }
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
-    if (!u)
+    if (!u) {
       continue;
       continue;
+    }
     if (u->spawnType == Game::Units::SpawnType::Barracks &&
     if (u->spawnType == Game::Units::SpawnType::Barracks &&
         u->ownerId == localOwnerId && u->health > 0) {
         u->ownerId == localOwnerId && u->health > 0) {
       focusEntity = e;
       focusEntity = e;
       break;
       break;
     }
     }
   }
   }
-  if (!focusEntity && playerUnitId != 0)
+  if (!focusEntity && playerUnitId != 0) {
     focusEntity = world.getEntity(playerUnitId);
     focusEntity = world.getEntity(playerUnitId);
+  }
 
 
   if (focusEntity) {
   if (focusEntity) {
     snapToEntity(camera, *focusEntity);
     snapToEntity(camera, *focusEntity);

+ 12 - 6
game/systems/capture_system.cpp

@@ -25,14 +25,17 @@ int CaptureSystem::countNearbyTroops(Engine::Core::World *world, float barrackX,
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
     auto *transform = e->getComponent<Engine::Core::TransformComponent>();
     auto *transform = e->getComponent<Engine::Core::TransformComponent>();
 
 
-    if (!unit || !transform || unit->health <= 0)
+    if (!unit || !transform || unit->health <= 0) {
       continue;
       continue;
+    }
 
 
-    if (unit->ownerId != ownerId)
+    if (unit->ownerId != ownerId) {
       continue;
       continue;
+    }
 
 
-    if (unit->spawnType == Game::Units::SpawnType::Barracks)
+    if (unit->spawnType == Game::Units::SpawnType::Barracks) {
       continue;
       continue;
+    }
 
 
     float dx = transform->position.x - barrackX;
     float dx = transform->position.x - barrackX;
     float dz = transform->position.z - barrackZ;
     float dz = transform->position.z - barrackZ;
@@ -57,8 +60,9 @@ void CaptureSystem::transferBarrackOwnership(Engine::Core::World *world,
   auto *transform = barrack->getComponent<Engine::Core::TransformComponent>();
   auto *transform = barrack->getComponent<Engine::Core::TransformComponent>();
   auto *prod = barrack->getComponent<Engine::Core::ProductionComponent>();
   auto *prod = barrack->getComponent<Engine::Core::ProductionComponent>();
 
 
-  if (!unit || !renderable || !transform)
+  if (!unit || !renderable || !transform) {
     return;
     return;
+  }
 
 
   int previousOwnerId = unit->ownerId;
   int previousOwnerId = unit->ownerId;
   unit->ownerId = newOwnerId;
   unit->ownerId = newOwnerId;
@@ -107,11 +111,13 @@ void CaptureSystem::processBarrackCapture(Engine::Core::World *world,
     auto *unit = barrack->getComponent<Engine::Core::UnitComponent>();
     auto *unit = barrack->getComponent<Engine::Core::UnitComponent>();
     auto *transform = barrack->getComponent<Engine::Core::TransformComponent>();
     auto *transform = barrack->getComponent<Engine::Core::TransformComponent>();
 
 
-    if (!unit || !transform)
+    if (!unit || !transform) {
       continue;
       continue;
+    }
 
 
-    if (unit->spawnType != Game::Units::SpawnType::Barracks)
+    if (unit->spawnType != Game::Units::SpawnType::Barracks) {
       continue;
       continue;
+    }
 
 
     auto *capture = barrack->getComponent<Engine::Core::CaptureComponent>();
     auto *capture = barrack->getComponent<Engine::Core::CaptureComponent>();
     if (!capture) {
     if (!capture) {

+ 4 - 2
game/systems/combat_system.cpp

@@ -27,8 +27,9 @@ void CombatSystem::processAttacks(Engine::Core::World *world, float deltaTime) {
 
 
   for (auto attacker : units) {
   for (auto attacker : units) {
 
 
-    if (attacker->hasComponent<Engine::Core::PendingRemovalComponent>())
+    if (attacker->hasComponent<Engine::Core::PendingRemovalComponent>()) {
       continue;
       continue;
+    }
 
 
     auto attackerUnit = attacker->getComponent<Engine::Core::UnitComponent>();
     auto attackerUnit = attacker->getComponent<Engine::Core::UnitComponent>();
     auto attackerTransform =
     auto attackerTransform =
@@ -39,8 +40,9 @@ void CombatSystem::processAttacks(Engine::Core::World *world, float deltaTime) {
       continue;
       continue;
     }
     }
 
 
-    if (attackerUnit->health <= 0)
+    if (attackerUnit->health <= 0) {
       continue;
       continue;
+    }
 
 
     if (attackerAtk && attackerAtk->inMeleeLock) {
     if (attackerAtk && attackerAtk->inMeleeLock) {
       auto *lockTarget = world->getEntity(attackerAtk->meleeLockTargetId);
       auto *lockTarget = world->getEntity(attackerAtk->meleeLockTargetId);

+ 70 - 54
game/systems/command_service.cpp

@@ -68,15 +68,17 @@ QVector3D CommandService::gridToWorld(const Point &gridPos) {
 void CommandService::clearPendingRequest(Engine::Core::EntityID entityId) {
 void CommandService::clearPendingRequest(Engine::Core::EntityID entityId) {
   std::lock_guard<std::mutex> lock(s_pendingMutex);
   std::lock_guard<std::mutex> lock(s_pendingMutex);
   auto it = s_entityToRequest.find(entityId);
   auto it = s_entityToRequest.find(entityId);
-  if (it == s_entityToRequest.end())
+  if (it == s_entityToRequest.end()) {
     return;
     return;
+  }
 
 
   std::uint64_t requestId = it->second;
   std::uint64_t requestId = it->second;
   s_entityToRequest.erase(it);
   s_entityToRequest.erase(it);
 
 
   auto pendingIt = s_pendingRequests.find(requestId);
   auto pendingIt = s_pendingRequests.find(requestId);
-  if (pendingIt == s_pendingRequests.end())
+  if (pendingIt == s_pendingRequests.end()) {
     return;
     return;
+  }
 
 
   auto members = pendingIt->second.groupMembers;
   auto members = pendingIt->second.groupMembers;
   s_pendingRequests.erase(pendingIt);
   s_pendingRequests.erase(pendingIt);
@@ -100,8 +102,9 @@ void CommandService::moveUnits(Engine::Core::World &world,
                                const std::vector<Engine::Core::EntityID> &units,
                                const std::vector<Engine::Core::EntityID> &units,
                                const std::vector<QVector3D> &targets,
                                const std::vector<QVector3D> &targets,
                                const MoveOptions &options) {
                                const MoveOptions &options) {
-  if (units.size() != targets.size())
+  if (units.size() != targets.size()) {
     return;
     return;
+  }
 
 
   if (options.groupMove && units.size() > 1) {
   if (options.groupMove && units.size() > 1) {
     moveGroup(world, units, targets, options);
     moveGroup(world, units, targets, options);
@@ -110,8 +113,9 @@ void CommandService::moveUnits(Engine::Core::World &world,
 
 
   for (size_t i = 0; i < units.size(); ++i) {
   for (size_t i = 0; i < units.size(); ++i) {
     auto *e = world.getEntity(units[i]);
     auto *e = world.getEntity(units[i]);
-    if (!e)
+    if (!e) {
       continue;
       continue;
+    }
 
 
     auto *holdMode = e->getComponent<Engine::Core::HoldModeComponent>();
     auto *holdMode = e->getComponent<Engine::Core::HoldModeComponent>();
     if (holdMode && holdMode->active) {
     if (holdMode && holdMode->active) {
@@ -127,14 +131,17 @@ void CommandService::moveUnits(Engine::Core::World &world,
     }
     }
 
 
     auto *transform = e->getComponent<Engine::Core::TransformComponent>();
     auto *transform = e->getComponent<Engine::Core::TransformComponent>();
-    if (!transform)
+    if (!transform) {
       continue;
       continue;
+    }
 
 
     auto *mv = e->getComponent<Engine::Core::MovementComponent>();
     auto *mv = e->getComponent<Engine::Core::MovementComponent>();
-    if (!mv)
+    if (!mv) {
       mv = e->addComponent<Engine::Core::MovementComponent>();
       mv = e->addComponent<Engine::Core::MovementComponent>();
-    if (!mv)
+    }
+    if (!mv) {
       continue;
       continue;
+    }
 
 
     if (options.clearAttackIntent) {
     if (options.clearAttackIntent) {
       e->removeComponent<Engine::Core::AttackTargetComponent>();
       e->removeComponent<Engine::Core::AttackTargetComponent>();
@@ -331,8 +338,9 @@ void CommandService::moveGroup(Engine::Core::World &world,
 
 
   for (size_t i = 0; i < units.size(); ++i) {
   for (size_t i = 0; i < units.size(); ++i) {
     auto *entity = world.getEntity(units[i]);
     auto *entity = world.getEntity(units[i]);
-    if (!entity)
+    if (!entity) {
       continue;
       continue;
+    }
 
 
     auto *holdMode = entity->getComponent<Engine::Core::HoldModeComponent>();
     auto *holdMode = entity->getComponent<Engine::Core::HoldModeComponent>();
     if (holdMode && holdMode->active) {
     if (holdMode && holdMode->active) {
@@ -341,14 +349,17 @@ void CommandService::moveGroup(Engine::Core::World &world,
     }
     }
 
 
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
-    if (!transform)
+    if (!transform) {
       continue;
       continue;
+    }
 
 
     auto *movement = entity->getComponent<Engine::Core::MovementComponent>();
     auto *movement = entity->getComponent<Engine::Core::MovementComponent>();
-    if (!movement)
+    if (!movement) {
       movement = entity->addComponent<Engine::Core::MovementComponent>();
       movement = entity->addComponent<Engine::Core::MovementComponent>();
-    if (!movement)
+    }
+    if (!movement) {
       continue;
       continue;
+    }
 
 
     bool engaged =
     bool engaged =
         entity->getComponent<Engine::Core::AttackTargetComponent>() != nullptr;
         entity->getComponent<Engine::Core::AttackTargetComponent>() != nullptr;
@@ -361,23 +372,17 @@ void CommandService::moveGroup(Engine::Core::World &world,
     auto *unitComponent = entity->getComponent<Engine::Core::UnitComponent>();
     auto *unitComponent = entity->getComponent<Engine::Core::UnitComponent>();
     float memberSpeed =
     float memberSpeed =
         unitComponent ? std::max(0.1f, unitComponent->speed) : 1.0f;
         unitComponent ? std::max(0.1f, unitComponent->speed) : 1.0f;
-    Game::Units::SpawnType spawnType =
-        unitComponent ? unitComponent->spawnType
-                      : Game::Units::SpawnType::Archer;
-
-    members.push_back({units[i],
-                       entity,
-                       transform,
-                       movement,
-                       targets[i],
-                       engaged,
-                       memberSpeed,
-                       spawnType,
-                       0.0f});
-  }
-
-  if (members.empty())
+    Game::Units::SpawnType spawnType = unitComponent
+                                           ? unitComponent->spawnType
+                                           : Game::Units::SpawnType::Archer;
+
+    members.push_back({units[i], entity, transform, movement, targets[i],
+                       engaged, memberSpeed, spawnType, 0.0f});
+  }
+
+  if (members.empty()) {
     return;
     return;
+  }
 
 
   if (members.size() == 1) {
   if (members.size() == 1) {
     std::vector<Engine::Core::EntityID> singleUnit = {members[0].id};
     std::vector<Engine::Core::EntityID> singleUnit = {members[0].id};
@@ -426,16 +431,17 @@ void CommandService::moveGroup(Engine::Core::World &world,
 
 
   members = movingMembers;
   members = movingMembers;
 
 
-  if (members.empty())
+  if (members.empty()) {
     return;
     return;
+  }
 
 
   QVector3D targetCentroid(0.0f, 0.0f, 0.0f);
   QVector3D targetCentroid(0.0f, 0.0f, 0.0f);
   QVector3D positionCentroid(0.0f, 0.0f, 0.0f);
   QVector3D positionCentroid(0.0f, 0.0f, 0.0f);
   float speedSum = 0.0f;
   float speedSum = 0.0f;
   for (auto &member : members) {
   for (auto &member : members) {
     targetCentroid += member.target;
     targetCentroid += member.target;
-    positionCentroid +=
-        QVector3D(member.transform->position.x, 0.0f, member.transform->position.z);
+    positionCentroid += QVector3D(member.transform->position.x, 0.0f,
+                                  member.transform->position.z);
     speedSum += member.speed;
     speedSum += member.speed;
   }
   }
 
 
@@ -458,18 +464,15 @@ void CommandService::moveGroup(Engine::Core::World &world,
   }
   }
 
 
   float avgTargetDistance =
   float avgTargetDistance =
-      members.empty()
-          ? 0.0f
-          : targetDistanceSum / static_cast<float>(members.size());
-  float avgScatter =
-      members.empty()
-          ? 0.0f
-          : centroidDistanceSum / static_cast<float>(members.size());
+      members.empty() ? 0.0f
+                      : targetDistanceSum / static_cast<float>(members.size());
+  float avgScatter = members.empty() ? 0.0f
+                                     : centroidDistanceSum /
+                                           static_cast<float>(members.size());
   float avgSpeed =
   float avgSpeed =
       members.empty() ? 0.0f : speedSum / static_cast<float>(members.size());
       members.empty() ? 0.0f : speedSum / static_cast<float>(members.size());
 
 
-  float nearThreshold =
-      std::clamp(avgTargetDistance * 0.5f, 4.0f, 12.0f);
+  float nearThreshold = std::clamp(avgTargetDistance * 0.5f, 4.0f, 12.0f);
   if (maxTargetDistance <= nearThreshold) {
   if (maxTargetDistance <= nearThreshold) {
     MoveOptions directOptions = options;
     MoveOptions directOptions = options;
     directOptions.groupMove = false;
     directOptions.groupMove = false;
@@ -543,8 +546,7 @@ void CommandService::moveGroup(Engine::Core::World &world,
       directOptions.groupMove = false;
       directOptions.groupMove = false;
       std::vector<Engine::Core::EntityID> singleIds = {
       std::vector<Engine::Core::EntityID> singleIds = {
           regroupMembers.front().id};
           regroupMembers.front().id};
-      std::vector<QVector3D> singleTargets = {
-          regroupMembers.front().target};
+      std::vector<QVector3D> singleTargets = {regroupMembers.front().target};
       moveUnits(world, singleIds, singleTargets, directOptions);
       moveUnits(world, singleIds, singleTargets, directOptions);
     }
     }
     return;
     return;
@@ -553,8 +555,9 @@ void CommandService::moveGroup(Engine::Core::World &world,
   members = std::move(regroupMembers);
   members = std::move(regroupMembers);
 
 
   QVector3D average(0.0f, 0.0f, 0.0f);
   QVector3D average(0.0f, 0.0f, 0.0f);
-  for (const auto &member : members)
+  for (const auto &member : members) {
     average += member.target;
     average += member.target;
+  }
   average /= static_cast<float>(members.size());
   average /= static_cast<float>(members.size());
 
 
   std::size_t leaderIndex = 0;
   std::size_t leaderIndex = 0;
@@ -672,12 +675,14 @@ void CommandService::moveGroup(Engine::Core::World &world,
 }
 }
 
 
 void CommandService::processPathResults(Engine::Core::World &world) {
 void CommandService::processPathResults(Engine::Core::World &world) {
-  if (!s_pathfinder)
+  if (!s_pathfinder) {
     return;
     return;
+  }
 
 
   auto results = s_pathfinder->fetchCompletedPaths();
   auto results = s_pathfinder->fetchCompletedPaths();
-  if (results.empty())
+  if (results.empty()) {
     return;
     return;
+  }
 
 
   for (auto &result : results) {
   for (auto &result : results) {
     PendingPathRequest requestInfo;
     PendingPathRequest requestInfo;
@@ -706,18 +711,21 @@ void CommandService::processPathResults(Engine::Core::World &world) {
     auto applyToMember = [&](Engine::Core::EntityID memberId,
     auto applyToMember = [&](Engine::Core::EntityID memberId,
                              const QVector3D &target, const QVector3D &offset) {
                              const QVector3D &target, const QVector3D &offset) {
       auto *memberEntity = world.getEntity(memberId);
       auto *memberEntity = world.getEntity(memberId);
-      if (!memberEntity)
+      if (!memberEntity) {
         return;
         return;
+      }
 
 
       auto *movementComponent =
       auto *movementComponent =
           memberEntity->getComponent<Engine::Core::MovementComponent>();
           memberEntity->getComponent<Engine::Core::MovementComponent>();
-      if (!movementComponent)
+      if (!movementComponent) {
         return;
         return;
+      }
 
 
       auto *memberTransform =
       auto *memberTransform =
           memberEntity->getComponent<Engine::Core::TransformComponent>();
           memberEntity->getComponent<Engine::Core::TransformComponent>();
-      if (!memberTransform)
+      if (!memberTransform) {
         return;
         return;
+      }
 
 
       if (!movementComponent->pathPending ||
       if (!movementComponent->pathPending ||
           movementComponent->pendingRequestId != result.requestId) {
           movementComponent->pendingRequestId != result.requestId) {
@@ -792,8 +800,10 @@ void CommandService::processPathResults(Engine::Core::World &world) {
     processed.reserve(requestInfo.groupMembers.size() + 1);
     processed.reserve(requestInfo.groupMembers.size() + 1);
 
 
     auto addMember = [&](Engine::Core::EntityID id, const QVector3D &target) {
     auto addMember = [&](Engine::Core::EntityID id, const QVector3D &target) {
-      if (std::find(processed.begin(), processed.end(), id) != processed.end())
+      if (std::find(processed.begin(), processed.end(), id) !=
+          processed.end()) {
         return;
         return;
+      }
       QVector3D offset = target - leaderTarget;
       QVector3D offset = target - leaderTarget;
       applyToMember(id, target, offset);
       applyToMember(id, target, offset);
       processed.push_back(id);
       processed.push_back(id);
@@ -818,12 +828,14 @@ void CommandService::attackTarget(
     Engine::Core::World &world,
     Engine::Core::World &world,
     const std::vector<Engine::Core::EntityID> &units,
     const std::vector<Engine::Core::EntityID> &units,
     Engine::Core::EntityID targetId, bool shouldChase) {
     Engine::Core::EntityID targetId, bool shouldChase) {
-  if (targetId == 0)
+  if (targetId == 0) {
     return;
     return;
+  }
   for (auto unitId : units) {
   for (auto unitId : units) {
     auto *e = world.getEntity(unitId);
     auto *e = world.getEntity(unitId);
-    if (!e)
+    if (!e) {
       continue;
       continue;
+    }
 
 
     auto *holdMode = e->getComponent<Engine::Core::HoldModeComponent>();
     auto *holdMode = e->getComponent<Engine::Core::HoldModeComponent>();
     if (holdMode && holdMode->active) {
     if (holdMode && holdMode->active) {
@@ -836,23 +848,27 @@ void CommandService::attackTarget(
     if (!attackTarget) {
     if (!attackTarget) {
       attackTarget = e->addComponent<Engine::Core::AttackTargetComponent>();
       attackTarget = e->addComponent<Engine::Core::AttackTargetComponent>();
     }
     }
-    if (!attackTarget)
+    if (!attackTarget) {
       continue;
       continue;
+    }
 
 
     attackTarget->targetId = targetId;
     attackTarget->targetId = targetId;
     attackTarget->shouldChase = shouldChase;
     attackTarget->shouldChase = shouldChase;
 
 
-    if (!shouldChase)
+    if (!shouldChase) {
       continue;
       continue;
+    }
 
 
     auto *targetEnt = world.getEntity(targetId);
     auto *targetEnt = world.getEntity(targetId);
-    if (!targetEnt)
+    if (!targetEnt) {
       continue;
       continue;
+    }
 
 
     auto *tTrans = targetEnt->getComponent<Engine::Core::TransformComponent>();
     auto *tTrans = targetEnt->getComponent<Engine::Core::TransformComponent>();
     auto *attTrans = e->getComponent<Engine::Core::TransformComponent>();
     auto *attTrans = e->getComponent<Engine::Core::TransformComponent>();
-    if (!tTrans || !attTrans)
+    if (!tTrans || !attTrans) {
       continue;
       continue;
+    }
 
 
     QVector3D targetPos(tTrans->position.x, 0.0f, tTrans->position.z);
     QVector3D targetPos(tTrans->position.x, 0.0f, tTrans->position.z);
     QVector3D attackerPos(attTrans->position.x, 0.0f, attTrans->position.z);
     QVector3D attackerPos(attTrans->position.x, 0.0f, attTrans->position.z);

+ 4 - 2
game/systems/formation_system.cpp

@@ -12,8 +12,9 @@ RomanFormation::calculatePositions(int unitCount, const QVector3D &center,
   std::vector<QVector3D> positions;
   std::vector<QVector3D> positions;
   positions.reserve(unitCount);
   positions.reserve(unitCount);
 
 
-  if (unitCount <= 0)
+  if (unitCount <= 0) {
     return positions;
     return positions;
+  }
 
 
   float spacing = baseSpacing * 1.2f;
   float spacing = baseSpacing * 1.2f;
 
 
@@ -46,8 +47,9 @@ BarbarianFormation::calculatePositions(int unitCount, const QVector3D &center,
   std::vector<QVector3D> positions;
   std::vector<QVector3D> positions;
   positions.reserve(unitCount);
   positions.reserve(unitCount);
 
 
-  if (unitCount <= 0)
+  if (unitCount <= 0) {
     return positions;
     return positions;
+  }
 
 
   float spacing = baseSpacing * 1.8f;
   float spacing = baseSpacing * 1.8f;
 
 

+ 2 - 1
game/systems/global_stats_registry.cpp

@@ -142,8 +142,9 @@ void GlobalStatsRegistry::rebuildFromWorld(Engine::Core::World &world) {
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   for (auto *e : entities) {
   for (auto *e : entities) {
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
-    if (!unit || unit->health <= 0)
+    if (!unit || unit->health <= 0) {
       continue;
       continue;
+    }
 
 
     auto &stats = m_playerStats[unit->ownerId];
     auto &stats = m_playerStats[unit->ownerId];
 
 

+ 4 - 2
game/systems/nation_registry.cpp

@@ -35,8 +35,9 @@ const TroopType *Nation::getTroop(Game::Units::TroopType unitType) const {
 
 
 const TroopType *Nation::getBestMeleeTroop() const {
 const TroopType *Nation::getBestMeleeTroop() const {
   auto melee = getMeleeTroops();
   auto melee = getMeleeTroops();
-  if (melee.empty())
+  if (melee.empty()) {
     return nullptr;
     return nullptr;
+  }
 
 
   auto it = std::max_element(melee.begin(), melee.end(),
   auto it = std::max_element(melee.begin(), melee.end(),
                              [](const TroopType *a, const TroopType *b) {
                              [](const TroopType *a, const TroopType *b) {
@@ -48,8 +49,9 @@ const TroopType *Nation::getBestMeleeTroop() const {
 
 
 const TroopType *Nation::getBestRangedTroop() const {
 const TroopType *Nation::getBestRangedTroop() const {
   auto ranged = getRangedTroops();
   auto ranged = getRangedTroops();
-  if (ranged.empty())
+  if (ranged.empty()) {
     return nullptr;
     return nullptr;
+  }
 
 
   auto it = std::max_element(ranged.begin(), ranged.end(),
   auto it = std::max_element(ranged.begin(), ranged.end(),
                              [](const TroopType *a, const TroopType *b) {
                              [](const TroopType *a, const TroopType *b) {

+ 18 - 9
game/systems/owner_registry.cpp

@@ -140,29 +140,33 @@ int OwnerRegistry::getLocalPlayerId() const { return m_localPlayerId; }
 
 
 bool OwnerRegistry::isPlayer(int ownerId) const {
 bool OwnerRegistry::isPlayer(int ownerId) const {
   auto it = m_ownerIdToIndex.find(ownerId);
   auto it = m_ownerIdToIndex.find(ownerId);
-  if (it == m_ownerIdToIndex.end())
+  if (it == m_ownerIdToIndex.end()) {
     return false;
     return false;
+  }
   return m_owners[it->second].type == OwnerType::Player;
   return m_owners[it->second].type == OwnerType::Player;
 }
 }
 
 
 bool OwnerRegistry::isAI(int ownerId) const {
 bool OwnerRegistry::isAI(int ownerId) const {
   auto it = m_ownerIdToIndex.find(ownerId);
   auto it = m_ownerIdToIndex.find(ownerId);
-  if (it == m_ownerIdToIndex.end())
+  if (it == m_ownerIdToIndex.end()) {
     return false;
     return false;
+  }
   return m_owners[it->second].type == OwnerType::AI;
   return m_owners[it->second].type == OwnerType::AI;
 }
 }
 
 
 OwnerType OwnerRegistry::getOwnerType(int ownerId) const {
 OwnerType OwnerRegistry::getOwnerType(int ownerId) const {
   auto it = m_ownerIdToIndex.find(ownerId);
   auto it = m_ownerIdToIndex.find(ownerId);
-  if (it == m_ownerIdToIndex.end())
+  if (it == m_ownerIdToIndex.end()) {
     return OwnerType::Neutral;
     return OwnerType::Neutral;
+  }
   return m_owners[it->second].type;
   return m_owners[it->second].type;
 }
 }
 
 
 std::string OwnerRegistry::getOwnerName(int ownerId) const {
 std::string OwnerRegistry::getOwnerName(int ownerId) const {
   auto it = m_ownerIdToIndex.find(ownerId);
   auto it = m_ownerIdToIndex.find(ownerId);
-  if (it == m_ownerIdToIndex.end())
+  if (it == m_ownerIdToIndex.end()) {
     return "Unknown";
     return "Unknown";
+  }
   return m_owners[it->second].name;
   return m_owners[it->second].name;
 }
 }
 
 
@@ -199,15 +203,17 @@ void OwnerRegistry::setOwnerTeam(int ownerId, int teamId) {
 
 
 int OwnerRegistry::getOwnerTeam(int ownerId) const {
 int OwnerRegistry::getOwnerTeam(int ownerId) const {
   auto it = m_ownerIdToIndex.find(ownerId);
   auto it = m_ownerIdToIndex.find(ownerId);
-  if (it == m_ownerIdToIndex.end())
+  if (it == m_ownerIdToIndex.end()) {
     return 0;
     return 0;
+  }
   return m_owners[it->second].teamId;
   return m_owners[it->second].teamId;
 }
 }
 
 
 bool OwnerRegistry::areAllies(int ownerId1, int ownerId2) const {
 bool OwnerRegistry::areAllies(int ownerId1, int ownerId2) const {
 
 
-  if (ownerId1 == ownerId2)
+  if (ownerId1 == ownerId2) {
     return true;
     return true;
+  }
 
 
   int team1 = getOwnerTeam(ownerId1);
   int team1 = getOwnerTeam(ownerId1);
   int team2 = getOwnerTeam(ownerId2);
   int team2 = getOwnerTeam(ownerId2);
@@ -219,11 +225,13 @@ bool OwnerRegistry::areAllies(int ownerId1, int ownerId2) const {
 
 
 bool OwnerRegistry::areEnemies(int ownerId1, int ownerId2) const {
 bool OwnerRegistry::areEnemies(int ownerId1, int ownerId2) const {
 
 
-  if (ownerId1 == ownerId2)
+  if (ownerId1 == ownerId2) {
     return false;
     return false;
+  }
 
 
-  if (areAllies(ownerId1, ownerId2))
+  if (areAllies(ownerId1, ownerId2)) {
     return false;
     return false;
+  }
 
 
   return true;
   return true;
 }
 }
@@ -232,8 +240,9 @@ std::vector<int> OwnerRegistry::getAlliesOf(int ownerId) const {
   std::vector<int> result;
   std::vector<int> result;
   int myTeam = getOwnerTeam(ownerId);
   int myTeam = getOwnerTeam(ownerId);
 
 
-  if (myTeam == 0)
+  if (myTeam == 0) {
     return result;
     return result;
+  }
 
 
   for (const auto &owner : m_owners) {
   for (const auto &owner : m_owners) {
     if (owner.ownerId != ownerId && owner.teamId == myTeam) {
     if (owner.ownerId != ownerId && owner.teamId == myTeam) {

+ 10 - 5
game/systems/patrol_system.cpp

@@ -7,8 +7,9 @@
 namespace Game::Systems {
 namespace Game::Systems {
 
 
 void PatrolSystem::update(Engine::Core::World *world, float deltaTime) {
 void PatrolSystem::update(Engine::Core::World *world, float deltaTime) {
-  if (!world)
+  if (!world) {
     return;
     return;
+  }
 
 
   auto entities = world->getEntitiesWith<Engine::Core::PatrolComponent>();
   auto entities = world->getEntitiesWith<Engine::Core::PatrolComponent>();
 
 
@@ -18,10 +19,12 @@ void PatrolSystem::update(Engine::Core::World *world, float deltaTime) {
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
     auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
 
 
-    if (!patrol || !movement || !transform || !unit)
+    if (!patrol || !movement || !transform || !unit) {
       continue;
       continue;
-    if (!patrol->patrolling || patrol->waypoints.size() < 2)
+    }
+    if (!patrol->patrolling || patrol->waypoints.size() < 2) {
       continue;
       continue;
+    }
 
 
     if (unit->health <= 0) {
     if (unit->health <= 0) {
       patrol->patrolling = false;
       patrol->patrolling = false;
@@ -42,10 +45,12 @@ void PatrolSystem::update(Engine::Core::World *world, float deltaTime) {
       auto *otherTransform =
       auto *otherTransform =
           other->getComponent<Engine::Core::TransformComponent>();
           other->getComponent<Engine::Core::TransformComponent>();
 
 
-      if (!otherUnit || !otherTransform || otherUnit->health <= 0)
+      if (!otherUnit || !otherTransform || otherUnit->health <= 0) {
         continue;
         continue;
-      if (otherUnit->ownerId == unit->ownerId)
+      }
+      if (otherUnit->ownerId == unit->ownerId) {
         continue;
         continue;
+      }
 
 
       float dx = otherTransform->position.x - transform->position.x;
       float dx = otherTransform->position.x - transform->position.x;
       float dz = otherTransform->position.z - transform->position.z;
       float dz = otherTransform->position.z - transform->position.z;

+ 32 - 16
game/systems/picking_service.cpp

@@ -16,8 +16,9 @@ bool PickingService::worldToScreen(const Render::GL::Camera &cam, int viewW,
 bool PickingService::screenToGround(const Render::GL::Camera &cam, int viewW,
 bool PickingService::screenToGround(const Render::GL::Camera &cam, int viewW,
                                     int viewH, const QPointF &screenPt,
                                     int viewH, const QPointF &screenPt,
                                     QVector3D &outWorld) const {
                                     QVector3D &outWorld) const {
-  if (viewW <= 0 || viewH <= 0)
+  if (viewW <= 0 || viewH <= 0) {
     return false;
     return false;
+  }
   return cam.screenToGround(screenPt.x(), screenPt.y(), qreal(viewW),
   return cam.screenToGround(screenPt.x(), screenPt.y(), qreal(viewW),
                             qreal(viewH), outWorld);
                             qreal(viewH), outWorld);
 }
 }
@@ -32,8 +33,9 @@ bool PickingService::projectBounds(const Render::GL::Camera &cam,
       QVector3D(center.x() - hx, center.y(), center.z() + hz)};
       QVector3D(center.x() - hx, center.y(), center.z() + hz)};
   QPointF screenPts[4];
   QPointF screenPts[4];
   for (int i = 0; i < 4; ++i) {
   for (int i = 0; i < 4; ++i) {
-    if (!worldToScreen(cam, viewW, viewH, corners[i], screenPts[i]))
+    if (!worldToScreen(cam, viewW, viewH, corners[i], screenPts[i])) {
       return false;
       return false;
+    }
   }
   }
   qreal minX = screenPts[0].x(), maxX = screenPts[0].x();
   qreal minX = screenPts[0].x(), maxX = screenPts[0].x();
   qreal minY = screenPts[0].y(), maxY = screenPts[0].y();
   qreal minY = screenPts[0].y(), maxY = screenPts[0].y();
@@ -70,8 +72,9 @@ PickingService::updateHover(float sx, float sy, Engine::Core::World &world,
     currentHover = prevHover;
     currentHover = prevHover;
   }
   }
 
 
-  if (m_hoverGraceTicks > 0)
+  if (m_hoverGraceTicks > 0) {
     --m_hoverGraceTicks;
     --m_hoverGraceTicks;
+  }
   m_prevHoverId = currentHover;
   m_prevHoverId = currentHover;
   return currentHover;
   return currentHover;
 }
 }
@@ -90,19 +93,22 @@ PickingService::pickSingle(float sx, float sy, Engine::Core::World &world,
   Engine::Core::EntityID bestBuildingId = 0;
   Engine::Core::EntityID bestBuildingId = 0;
   auto ents = world.getEntitiesWith<Engine::Core::TransformComponent>();
   auto ents = world.getEntitiesWith<Engine::Core::TransformComponent>();
   for (auto *e : ents) {
   for (auto *e : ents) {
-    if (!e->hasComponent<Engine::Core::UnitComponent>())
+    if (!e->hasComponent<Engine::Core::UnitComponent>()) {
       continue;
       continue;
+    }
     auto *t = e->getComponent<Engine::Core::TransformComponent>();
     auto *t = e->getComponent<Engine::Core::TransformComponent>();
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
 
 
-    if (ownerFilter != 0 && u->ownerId != ownerFilter)
+    if (ownerFilter != 0 && u->ownerId != ownerFilter) {
       continue;
       continue;
+    }
 
 
     QPointF sp;
     QPointF sp;
     if (!camera.worldToScreen(
     if (!camera.worldToScreen(
             QVector3D(t->position.x, t->position.y, t->position.z), viewW,
             QVector3D(t->position.x, t->position.y, t->position.z), viewW,
-            viewH, sp))
+            viewH, sp)) {
       continue;
       continue;
+    }
     float dx = float(sx - sp.x());
     float dx = float(sx - sp.x());
     float dy = float(sy - sp.y());
     float dy = float(sy - sp.y());
     float d2 = dx * dx + dy * dy;
     float d2 = dx * dx + dy * dy;
@@ -161,8 +167,9 @@ PickingService::pickSingle(float sx, float sy, Engine::Core::World &world,
         float scaleXZ = std::max(std::max(t->scale.x, t->scale.z), 1.0f);
         float scaleXZ = std::max(std::max(t->scale.x, t->scale.z), 1.0f);
         float rp = baseBuildingPickRadius * scaleXZ;
         float rp = baseBuildingPickRadius * scaleXZ;
         float r2 = rp * rp;
         float r2 = rp * rp;
-        if (d2 <= r2)
+        if (d2 <= r2) {
           hit = true;
           hit = true;
+        }
       }
       }
       if (hit && pickDist2 < bestBuildingDist2) {
       if (hit && pickDist2 < bestBuildingDist2) {
         bestBuildingDist2 = pickDist2;
         bestBuildingDist2 = pickDist2;
@@ -177,15 +184,19 @@ PickingService::pickSingle(float sx, float sy, Engine::Core::World &world,
     }
     }
   }
   }
   if (preferBuildingsFirst) {
   if (preferBuildingsFirst) {
-    if (bestBuildingId && (!bestUnitId || bestBuildingDist2 <= bestUnitDist2))
+    if (bestBuildingId && (!bestUnitId || bestBuildingDist2 <= bestUnitDist2)) {
       return bestBuildingId;
       return bestBuildingId;
-    if (bestUnitId)
+    }
+    if (bestUnitId) {
       return bestUnitId;
       return bestUnitId;
+    }
   } else {
   } else {
-    if (bestUnitId)
+    if (bestUnitId) {
       return bestUnitId;
       return bestUnitId;
-    if (bestBuildingId)
+    }
+    if (bestBuildingId) {
       return bestBuildingId;
       return bestBuildingId;
+    }
   }
   }
   return 0;
   return 0;
 }
 }
@@ -196,8 +207,9 @@ PickingService::pickUnitFirst(float sx, float sy, Engine::Core::World &world,
                               int viewH, int ownerFilter) const {
                               int viewH, int ownerFilter) const {
 
 
   auto id = pickSingle(sx, sy, world, camera, viewW, viewH, ownerFilter, false);
   auto id = pickSingle(sx, sy, world, camera, viewW, viewH, ownerFilter, false);
-  if (id != 0)
+  if (id != 0) {
     return id;
     return id;
+  }
 
 
   return pickSingle(sx, sy, world, camera, viewW, viewH, ownerFilter, true);
   return pickSingle(sx, sy, world, camera, viewW, viewH, ownerFilter, true);
 }
 }
@@ -214,19 +226,23 @@ PickingService::pickInRect(float x1, float y1, float x2, float y2,
   std::vector<Engine::Core::EntityID> picked;
   std::vector<Engine::Core::EntityID> picked;
   auto ents = world.getEntitiesWith<Engine::Core::TransformComponent>();
   auto ents = world.getEntitiesWith<Engine::Core::TransformComponent>();
   for (auto *e : ents) {
   for (auto *e : ents) {
-    if (!e->hasComponent<Engine::Core::UnitComponent>())
+    if (!e->hasComponent<Engine::Core::UnitComponent>()) {
       continue;
       continue;
-    if (e->hasComponent<Engine::Core::BuildingComponent>())
+    }
+    if (e->hasComponent<Engine::Core::BuildingComponent>()) {
       continue;
       continue;
+    }
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
     auto *u = e->getComponent<Engine::Core::UnitComponent>();
-    if (!u || u->ownerId != ownerFilter)
+    if (!u || u->ownerId != ownerFilter) {
       continue;
       continue;
+    }
     auto *t = e->getComponent<Engine::Core::TransformComponent>();
     auto *t = e->getComponent<Engine::Core::TransformComponent>();
     QPointF sp;
     QPointF sp;
     if (!camera.worldToScreen(
     if (!camera.worldToScreen(
             QVector3D(t->position.x, t->position.y, t->position.z), viewW,
             QVector3D(t->position.x, t->position.y, t->position.z), viewW,
-            viewH, sp))
+            viewH, sp)) {
       continue;
       continue;
+    }
     if (sp.x() >= minX && sp.x() <= maxX && sp.y() >= minY && sp.y() <= maxY) {
     if (sp.x() >= minX && sp.x() <= maxX && sp.y() >= minY && sp.y() <= maxY) {
       picked.push_back(e->getId());
       picked.push_back(e->getId());
     }
     }

+ 22 - 11
game/systems/production_service.cpp

@@ -14,10 +14,12 @@ findFirstSelectedBarracks(Engine::Core::World &world,
   for (auto id : selected) {
   for (auto id : selected) {
     if (auto *e = world.getEntity(id)) {
     if (auto *e = world.getEntity(id)) {
       auto *u = e->getComponent<Engine::Core::UnitComponent>();
       auto *u = e->getComponent<Engine::Core::UnitComponent>();
-      if (!u || u->ownerId != ownerId)
+      if (!u || u->ownerId != ownerId) {
         continue;
         continue;
-      if (u->spawnType == Game::Units::SpawnType::Barracks)
+      }
+      if (u->spawnType == Game::Units::SpawnType::Barracks) {
         return e;
         return e;
+      }
     }
     }
   }
   }
   return nullptr;
   return nullptr;
@@ -28,31 +30,37 @@ ProductionResult ProductionService::startProductionForFirstSelectedBarracks(
     const std::vector<Engine::Core::EntityID> &selected, int ownerId,
     const std::vector<Engine::Core::EntityID> &selected, int ownerId,
     Game::Units::TroopType unitType) {
     Game::Units::TroopType unitType) {
   auto *e = findFirstSelectedBarracks(world, selected, ownerId);
   auto *e = findFirstSelectedBarracks(world, selected, ownerId);
-  if (!e)
+  if (!e) {
     return ProductionResult::NoBarracks;
     return ProductionResult::NoBarracks;
+  }
   auto *p = e->getComponent<Engine::Core::ProductionComponent>();
   auto *p = e->getComponent<Engine::Core::ProductionComponent>();
-  if (!p)
+  if (!p) {
     p = e->addComponent<Engine::Core::ProductionComponent>();
     p = e->addComponent<Engine::Core::ProductionComponent>();
-  if (!p)
+  }
+  if (!p) {
     return ProductionResult::NoBarracks;
     return ProductionResult::NoBarracks;
+  }
 
 
   int individualsPerUnit =
   int individualsPerUnit =
       Game::Units::TroopConfig::instance().getIndividualsPerUnit(unitType);
       Game::Units::TroopConfig::instance().getIndividualsPerUnit(unitType);
 
 
-  if (p->producedCount + individualsPerUnit > p->maxUnits)
+  if (p->producedCount + individualsPerUnit > p->maxUnits) {
     return ProductionResult::PerBarracksLimitReached;
     return ProductionResult::PerBarracksLimitReached;
+  }
 
 
   int currentTroops = world.countTroopsForPlayer(ownerId);
   int currentTroops = world.countTroopsForPlayer(ownerId);
   int maxTroops = Game::GameConfig::instance().getMaxTroopsPerPlayer();
   int maxTroops = Game::GameConfig::instance().getMaxTroopsPerPlayer();
-  if (currentTroops + individualsPerUnit > maxTroops)
+  if (currentTroops + individualsPerUnit > maxTroops) {
     return ProductionResult::GlobalTroopLimitReached;
     return ProductionResult::GlobalTroopLimitReached;
+  }
 
 
   const int maxQueueSize = 5;
   const int maxQueueSize = 5;
   int totalInQueue = p->inProgress ? 1 : 0;
   int totalInQueue = p->inProgress ? 1 : 0;
   totalInQueue += static_cast<int>(p->productionQueue.size());
   totalInQueue += static_cast<int>(p->productionQueue.size());
 
 
-  if (totalInQueue >= maxQueueSize)
+  if (totalInQueue >= maxQueueSize) {
     return ProductionResult::QueueFull;
     return ProductionResult::QueueFull;
+  }
 
 
   if (p->inProgress) {
   if (p->inProgress) {
     p->productionQueue.push_back(unitType);
     p->productionQueue.push_back(unitType);
@@ -70,13 +78,16 @@ bool ProductionService::setRallyForFirstSelectedBarracks(
     const std::vector<Engine::Core::EntityID> &selected, int ownerId, float x,
     const std::vector<Engine::Core::EntityID> &selected, int ownerId, float x,
     float z) {
     float z) {
   auto *e = findFirstSelectedBarracks(world, selected, ownerId);
   auto *e = findFirstSelectedBarracks(world, selected, ownerId);
-  if (!e)
+  if (!e) {
     return false;
     return false;
+  }
   auto *p = e->getComponent<Engine::Core::ProductionComponent>();
   auto *p = e->getComponent<Engine::Core::ProductionComponent>();
-  if (!p)
+  if (!p) {
     p = e->addComponent<Engine::Core::ProductionComponent>();
     p = e->addComponent<Engine::Core::ProductionComponent>();
-  if (!p)
+  }
+  if (!p) {
     return false;
     return false;
+  }
   p->rallyX = x;
   p->rallyX = x;
   p->rallyZ = z;
   p->rallyZ = z;
   p->rallySet = true;
   p->rallySet = true;

+ 6 - 3
game/systems/production_system.cpp

@@ -12,21 +12,24 @@ namespace Game {
 namespace Systems {
 namespace Systems {
 
 
 void ProductionSystem::update(Engine::Core::World *world, float deltaTime) {
 void ProductionSystem::update(Engine::Core::World *world, float deltaTime) {
-  if (!world)
+  if (!world) {
     return;
     return;
+  }
   auto entities = world->getEntitiesWith<Engine::Core::ProductionComponent>();
   auto entities = world->getEntitiesWith<Engine::Core::ProductionComponent>();
   for (auto *e : entities) {
   for (auto *e : entities) {
     auto *prod = e->getComponent<Engine::Core::ProductionComponent>();
     auto *prod = e->getComponent<Engine::Core::ProductionComponent>();
-    if (!prod)
+    if (!prod) {
       continue;
       continue;
+    }
 
 
     auto *unitComp = e->getComponent<Engine::Core::UnitComponent>();
     auto *unitComp = e->getComponent<Engine::Core::UnitComponent>();
     if (unitComp && Game::Core::isNeutralOwner(unitComp->ownerId)) {
     if (unitComp && Game::Core::isNeutralOwner(unitComp->ownerId)) {
       continue;
       continue;
     }
     }
 
 
-    if (!prod->inProgress)
+    if (!prod->inProgress) {
       continue;
       continue;
+    }
 
 
     int individualsPerUnit =
     int individualsPerUnit =
         Game::Units::TroopConfig::instance().getIndividualsPerUnit(
         Game::Units::TroopConfig::instance().getIndividualsPerUnit(

+ 30 - 15
game/systems/selection_system.cpp

@@ -61,8 +61,9 @@ SelectionController::SelectionController(Engine::Core::World *world,
 void SelectionController::onClickSelect(qreal sx, qreal sy, bool additive,
 void SelectionController::onClickSelect(qreal sx, qreal sy, bool additive,
                                         int viewportWidth, int viewportHeight,
                                         int viewportWidth, int viewportHeight,
                                         void *camera, int localOwnerId) {
                                         void *camera, int localOwnerId) {
-  if (!m_selectionSystem || !m_pickingService || !camera || !m_world)
+  if (!m_selectionSystem || !m_pickingService || !camera || !m_world) {
     return;
     return;
+  }
 
 
   auto *cam = static_cast<Render::GL::Camera *>(camera);
   auto *cam = static_cast<Render::GL::Camera *>(camera);
   Engine::Core::EntityID picked = m_pickingService->pickSingle(
   Engine::Core::EntityID picked = m_pickingService->pickSingle(
@@ -70,8 +71,9 @@ void SelectionController::onClickSelect(qreal sx, qreal sy, bool additive,
       localOwnerId, true);
       localOwnerId, true);
 
 
   if (picked) {
   if (picked) {
-    if (!additive)
+    if (!additive) {
       m_selectionSystem->clearSelection();
       m_selectionSystem->clearSelection();
+    }
     m_selectionSystem->selectUnit(picked);
     m_selectionSystem->selectUnit(picked);
     syncSelectionFlags();
     syncSelectionFlags();
     emit selectionChanged();
     emit selectionChanged();
@@ -101,47 +103,55 @@ void SelectionController::onAreaSelected(qreal x1, qreal y1, qreal x2, qreal y2,
                                          bool additive, int viewportWidth,
                                          bool additive, int viewportWidth,
                                          int viewportHeight, void *camera,
                                          int viewportHeight, void *camera,
                                          int localOwnerId) {
                                          int localOwnerId) {
-  if (!m_selectionSystem || !m_pickingService || !camera || !m_world)
+  if (!m_selectionSystem || !m_pickingService || !camera || !m_world) {
     return;
     return;
+  }
 
 
-  if (!additive)
+  if (!additive) {
     m_selectionSystem->clearSelection();
     m_selectionSystem->clearSelection();
+  }
 
 
   auto *cam = static_cast<Render::GL::Camera *>(camera);
   auto *cam = static_cast<Render::GL::Camera *>(camera);
   auto picked = m_pickingService->pickInRect(
   auto picked = m_pickingService->pickInRect(
       float(x1), float(y1), float(x2), float(y2), *m_world, *cam, viewportWidth,
       float(x1), float(y1), float(x2), float(y2), *m_world, *cam, viewportWidth,
       viewportHeight, localOwnerId);
       viewportHeight, localOwnerId);
-  for (auto id : picked)
+  for (auto id : picked) {
     m_selectionSystem->selectUnit(id);
     m_selectionSystem->selectUnit(id);
+  }
   syncSelectionFlags();
   syncSelectionFlags();
   emit selectionChanged();
   emit selectionChanged();
 }
 }
 
 
 void SelectionController::onRightClickClearSelection() {
 void SelectionController::onRightClickClearSelection() {
-  if (!m_selectionSystem)
+  if (!m_selectionSystem) {
     return;
     return;
+  }
   m_selectionSystem->clearSelection();
   m_selectionSystem->clearSelection();
   syncSelectionFlags();
   syncSelectionFlags();
   emit selectionChanged();
   emit selectionChanged();
 }
 }
 
 
 void SelectionController::selectAllPlayerTroops(int localOwnerId) {
 void SelectionController::selectAllPlayerTroops(int localOwnerId) {
-  if (!m_selectionSystem || !m_world)
+  if (!m_selectionSystem || !m_world) {
     return;
     return;
+  }
 
 
   m_selectionSystem->clearSelection();
   m_selectionSystem->clearSelection();
 
 
   auto entities = m_world->getEntitiesWith<Engine::Core::UnitComponent>();
   auto entities = m_world->getEntitiesWith<Engine::Core::UnitComponent>();
   for (auto *e : entities) {
   for (auto *e : entities) {
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
-    if (!unit || unit->ownerId != localOwnerId)
+    if (!unit || unit->ownerId != localOwnerId) {
       continue;
       continue;
+    }
 
 
-    if (e->hasComponent<Engine::Core::BuildingComponent>())
+    if (e->hasComponent<Engine::Core::BuildingComponent>()) {
       continue;
       continue;
+    }
 
 
-    if (unit->health <= 0)
+    if (unit->health <= 0) {
       continue;
       continue;
+    }
 
 
     m_selectionSystem->selectUnit(e->getId());
     m_selectionSystem->selectUnit(e->getId());
   }
   }
@@ -151,8 +161,9 @@ void SelectionController::selectAllPlayerTroops(int localOwnerId) {
 }
 }
 
 
 bool SelectionController::hasUnitsSelected() const {
 bool SelectionController::hasUnitsSelected() const {
-  if (!m_selectionSystem)
+  if (!m_selectionSystem) {
     return false;
     return false;
+  }
   const auto &sel = m_selectionSystem->getSelectedUnits();
   const auto &sel = m_selectionSystem->getSelectedUnits();
   return !sel.empty();
   return !sel.empty();
 }
 }
@@ -160,22 +171,25 @@ bool SelectionController::hasUnitsSelected() const {
 void SelectionController::getSelectedUnitIds(
 void SelectionController::getSelectedUnitIds(
     std::vector<Engine::Core::EntityID> &out) const {
     std::vector<Engine::Core::EntityID> &out) const {
   out.clear();
   out.clear();
-  if (!m_selectionSystem)
+  if (!m_selectionSystem) {
     return;
     return;
+  }
   const auto &ids = m_selectionSystem->getSelectedUnits();
   const auto &ids = m_selectionSystem->getSelectedUnits();
   out.assign(ids.begin(), ids.end());
   out.assign(ids.begin(), ids.end());
 }
 }
 
 
 bool SelectionController::hasSelectedType(const QString &type) const {
 bool SelectionController::hasSelectedType(const QString &type) const {
-  if (!m_world || !m_selectionSystem)
+  if (!m_world || !m_selectionSystem) {
     return false;
     return false;
+  }
   const auto &sel = m_selectionSystem->getSelectedUnits();
   const auto &sel = m_selectionSystem->getSelectedUnits();
   for (auto id : sel) {
   for (auto id : sel) {
     if (auto *e = m_world->getEntity(id)) {
     if (auto *e = m_world->getEntity(id)) {
       if (auto *u = e->getComponent<Engine::Core::UnitComponent>()) {
       if (auto *u = e->getComponent<Engine::Core::UnitComponent>()) {
         if (QString::fromStdString(
         if (QString::fromStdString(
-                Game::Units::spawnTypeToString(u->spawnType)) == type)
+                Game::Units::spawnTypeToString(u->spawnType)) == type) {
           return true;
           return true;
+        }
       }
       }
     }
     }
   }
   }
@@ -183,8 +197,9 @@ bool SelectionController::hasSelectedType(const QString &type) const {
 }
 }
 
 
 void SelectionController::syncSelectionFlags() {
 void SelectionController::syncSelectionFlags() {
-  if (!m_world || !m_selectionSystem)
+  if (!m_world || !m_selectionSystem) {
     return;
     return;
+  }
   App::Utils::sanitizeSelection(m_world, m_selectionSystem);
   App::Utils::sanitizeSelection(m_world, m_selectionSystem);
 }
 }
 
 

+ 2 - 1
game/systems/terrain_alignment_system.cpp

@@ -24,8 +24,9 @@ void TerrainAlignmentSystem::update(Engine::Core::World *world,
 void TerrainAlignmentSystem::alignEntityToTerrain(
 void TerrainAlignmentSystem::alignEntityToTerrain(
     Engine::Core::Entity *entity) {
     Engine::Core::Entity *entity) {
   auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
   auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
-  if (!transform)
+  if (!transform) {
     return;
     return;
+  }
 
 
   auto &terrainService = Game::Map::TerrainService::instance();
   auto &terrainService = Game::Map::TerrainService::instance();
 
 

+ 8 - 4
game/systems/troop_count_registry.cpp

@@ -34,8 +34,9 @@ int TroopCountRegistry::getTroopCount(int ownerId) const {
 
 
 void TroopCountRegistry::onUnitSpawned(
 void TroopCountRegistry::onUnitSpawned(
     const Engine::Core::UnitSpawnedEvent &event) {
     const Engine::Core::UnitSpawnedEvent &event) {
-  if (event.spawnType == Game::Units::SpawnType::Barracks)
+  if (event.spawnType == Game::Units::SpawnType::Barracks) {
     return;
     return;
+  }
 
 
   int individualsPerUnit =
   int individualsPerUnit =
       Game::Units::TroopConfig::instance().getIndividualsPerUnit(
       Game::Units::TroopConfig::instance().getIndividualsPerUnit(
@@ -44,8 +45,9 @@ void TroopCountRegistry::onUnitSpawned(
 }
 }
 
 
 void TroopCountRegistry::onUnitDied(const Engine::Core::UnitDiedEvent &event) {
 void TroopCountRegistry::onUnitDied(const Engine::Core::UnitDiedEvent &event) {
-  if (event.spawnType == Game::Units::SpawnType::Barracks)
+  if (event.spawnType == Game::Units::SpawnType::Barracks) {
     return;
     return;
+  }
 
 
   int individualsPerUnit =
   int individualsPerUnit =
       Game::Units::TroopConfig::instance().getIndividualsPerUnit(
       Game::Units::TroopConfig::instance().getIndividualsPerUnit(
@@ -62,11 +64,13 @@ void TroopCountRegistry::rebuildFromWorld(Engine::Core::World &world) {
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   for (auto *e : entities) {
   for (auto *e : entities) {
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
-    if (!unit || unit->health <= 0)
+    if (!unit || unit->health <= 0) {
       continue;
       continue;
+    }
 
 
-    if (unit->spawnType == Game::Units::SpawnType::Barracks)
+    if (unit->spawnType == Game::Units::SpawnType::Barracks) {
       continue;
       continue;
+    }
 
 
     int individualsPerUnit =
     int individualsPerUnit =
         Game::Units::TroopConfig::instance().getIndividualsPerUnit(
         Game::Units::TroopConfig::instance().getIndividualsPerUnit(

+ 10 - 5
game/systems/victory_service.cpp

@@ -191,14 +191,17 @@ bool VictoryService::checkElimination(Engine::Core::World &world) {
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   for (auto *e : entities) {
   for (auto *e : entities) {
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
-    if (!unit || unit->health <= 0)
+    if (!unit || unit->health <= 0) {
       continue;
       continue;
+    }
 
 
-    if (unit->ownerId == m_localOwnerId)
+    if (unit->ownerId == m_localOwnerId) {
       continue;
       continue;
+    }
 
 
-    if (m_ownerRegistry.areAllies(m_localOwnerId, unit->ownerId))
+    if (m_ownerRegistry.areAllies(m_localOwnerId, unit->ownerId)) {
       continue;
       continue;
+    }
 
 
     QString unitTypeStr =
     QString unitTypeStr =
         QString::fromStdString(Game::Units::spawnTypeToString(unit->spawnType));
         QString::fromStdString(Game::Units::spawnTypeToString(unit->spawnType));
@@ -221,8 +224,9 @@ bool VictoryService::checkNoUnits(Engine::Core::World &world) {
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   for (auto *e : entities) {
   for (auto *e : entities) {
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
-    if (!unit || unit->health <= 0)
+    if (!unit || unit->health <= 0) {
       continue;
       continue;
+    }
 
 
     if (unit->ownerId == m_localOwnerId) {
     if (unit->ownerId == m_localOwnerId) {
       return false;
       return false;
@@ -237,8 +241,9 @@ bool VictoryService::checkNoKeyStructures(Engine::Core::World &world) {
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   auto entities = world.getEntitiesWith<Engine::Core::UnitComponent>();
   for (auto *e : entities) {
   for (auto *e : entities) {
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
     auto *unit = e->getComponent<Engine::Core::UnitComponent>();
-    if (!unit || unit->health <= 0)
+    if (!unit || unit->health <= 0) {
       continue;
       continue;
+    }
 
 
     if (unit->ownerId == m_localOwnerId) {
     if (unit->ownerId == m_localOwnerId) {
       QString unitTypeStr = QString::fromStdString(
       QString unitTypeStr = QString::fromStdString(

+ 1 - 1
game/units/spawn_type.h

@@ -3,9 +3,9 @@
 #include "troop_type.h"
 #include "troop_type.h"
 #include <QString>
 #include <QString>
 #include <cstdint>
 #include <cstdint>
+#include <functional>
 #include <optional>
 #include <optional>
 #include <string>
 #include <string>
-#include <functional>
 
 
 namespace Game::Units {
 namespace Game::Units {
 
 

+ 22 - 11
game/units/unit.cpp

@@ -16,27 +16,34 @@ Engine::Core::Entity *Unit::entity() const {
 }
 }
 
 
 void Unit::ensureCoreComponents() {
 void Unit::ensureCoreComponents() {
-  if (!m_world)
+  if (!m_world) {
     return;
     return;
+  }
   if (auto *e = entity()) {
   if (auto *e = entity()) {
-    if (!m_t)
+    if (!m_t) {
       m_t = e->getComponent<Engine::Core::TransformComponent>();
       m_t = e->getComponent<Engine::Core::TransformComponent>();
-    if (!m_r)
+    }
+    if (!m_r) {
       m_r = e->getComponent<Engine::Core::RenderableComponent>();
       m_r = e->getComponent<Engine::Core::RenderableComponent>();
-    if (!m_u)
+    }
+    if (!m_u) {
       m_u = e->getComponent<Engine::Core::UnitComponent>();
       m_u = e->getComponent<Engine::Core::UnitComponent>();
-    if (!m_mv)
+    }
+    if (!m_mv) {
       m_mv = e->getComponent<Engine::Core::MovementComponent>();
       m_mv = e->getComponent<Engine::Core::MovementComponent>();
-    if (!m_atk)
+    }
+    if (!m_atk) {
       m_atk = e->getComponent<Engine::Core::AttackComponent>();
       m_atk = e->getComponent<Engine::Core::AttackComponent>();
+    }
   }
   }
 }
 }
 
 
 void Unit::moveTo(float x, float z) {
 void Unit::moveTo(float x, float z) {
   ensureCoreComponents();
   ensureCoreComponents();
   if (!m_mv) {
   if (!m_mv) {
-    if (auto *e = entity())
+    if (auto *e = entity()) {
       m_mv = e->addComponent<Engine::Core::MovementComponent>();
       m_mv = e->addComponent<Engine::Core::MovementComponent>();
+    }
   }
   }
   if (m_mv) {
   if (m_mv) {
     m_mv->targetX = x;
     m_mv->targetX = x;
@@ -59,24 +66,27 @@ void Unit::moveTo(float x, float z) {
 
 
 bool Unit::isAlive() const {
 bool Unit::isAlive() const {
   if (auto *e = entity()) {
   if (auto *e = entity()) {
-    if (auto *u = e->getComponent<Engine::Core::UnitComponent>())
+    if (auto *u = e->getComponent<Engine::Core::UnitComponent>()) {
       return u->health > 0;
       return u->health > 0;
+    }
   }
   }
   return false;
   return false;
 }
 }
 
 
 QVector3D Unit::position() const {
 QVector3D Unit::position() const {
   if (auto *e = entity()) {
   if (auto *e = entity()) {
-    if (auto *t = e->getComponent<Engine::Core::TransformComponent>())
+    if (auto *t = e->getComponent<Engine::Core::TransformComponent>()) {
       return QVector3D(t->position.x, t->position.y, t->position.z);
       return QVector3D(t->position.x, t->position.y, t->position.z);
+    }
   }
   }
   return QVector3D();
   return QVector3D();
 }
 }
 
 
 void Unit::setHoldMode(bool enabled) {
 void Unit::setHoldMode(bool enabled) {
   auto *e = entity();
   auto *e = entity();
-  if (!e)
+  if (!e) {
     return;
     return;
+  }
 
 
   auto *holdComp = e->getComponent<Engine::Core::HoldModeComponent>();
   auto *holdComp = e->getComponent<Engine::Core::HoldModeComponent>();
 
 
@@ -103,8 +113,9 @@ void Unit::setHoldMode(bool enabled) {
 
 
 bool Unit::isInHoldMode() const {
 bool Unit::isInHoldMode() const {
   auto *e = entity();
   auto *e = entity();
-  if (!e)
+  if (!e) {
     return false;
     return false;
+  }
 
 
   auto *holdComp = e->getComponent<Engine::Core::HoldModeComponent>();
   auto *holdComp = e->getComponent<Engine::Core::HoldModeComponent>();
   return holdComp && holdComp->active;
   return holdComp && holdComp->active;

+ 18 - 9
game/visuals/visual_catalog.cpp

@@ -9,16 +9,21 @@ namespace Game::Visuals {
 
 
 VisualDef::MeshKind meshKindFromString(const QString &s) {
 VisualDef::MeshKind meshKindFromString(const QString &s) {
   const QString t = s.trimmed().toLower();
   const QString t = s.trimmed().toLower();
-  if (t == "quad")
+  if (t == "quad") {
     return VisualDef::MeshKind::Quad;
     return VisualDef::MeshKind::Quad;
-  if (t == "plane")
+  }
+  if (t == "plane") {
     return VisualDef::MeshKind::Plane;
     return VisualDef::MeshKind::Plane;
-  if (t == "cube")
+  }
+  if (t == "cube") {
     return VisualDef::MeshKind::Cube;
     return VisualDef::MeshKind::Cube;
-  if (t == "capsule")
+  }
+  if (t == "capsule") {
     return VisualDef::MeshKind::Capsule;
     return VisualDef::MeshKind::Capsule;
-  if (t == "ring")
+  }
+  if (t == "ring") {
     return VisualDef::MeshKind::Ring;
     return VisualDef::MeshKind::Ring;
+  }
   return VisualDef::MeshKind::None;
   return VisualDef::MeshKind::None;
 }
 }
 
 
@@ -44,8 +49,9 @@ toRenderableMesh(VisualDef::MeshKind k) {
 bool VisualCatalog::loadFromJsonFile(const QString &path, QString *outError) {
 bool VisualCatalog::loadFromJsonFile(const QString &path, QString *outError) {
   QFile f(path);
   QFile f(path);
   if (!f.open(QIODevice::ReadOnly)) {
   if (!f.open(QIODevice::ReadOnly)) {
-    if (outError)
+    if (outError) {
       *outError = QString("Failed to open visuals file: %1").arg(path);
       *outError = QString("Failed to open visuals file: %1").arg(path);
+    }
     return false;
     return false;
   }
   }
   const QByteArray data = f.readAll();
   const QByteArray data = f.readAll();
@@ -53,10 +59,11 @@ bool VisualCatalog::loadFromJsonFile(const QString &path, QString *outError) {
   QJsonParseError perr{};
   QJsonParseError perr{};
   const QJsonDocument doc = QJsonDocument::fromJson(data, &perr);
   const QJsonDocument doc = QJsonDocument::fromJson(data, &perr);
   if (doc.isNull()) {
   if (doc.isNull()) {
-    if (outError)
+    if (outError) {
       *outError = QString("JSON parse error at %1: %2")
       *outError = QString("JSON parse error at %1: %2")
                       .arg(perr.offset)
                       .arg(perr.offset)
                       .arg(perr.errorString());
                       .arg(perr.errorString());
+    }
     return false;
     return false;
   }
   }
   QJsonObject root = doc.object();
   QJsonObject root = doc.object();
@@ -66,10 +73,11 @@ bool VisualCatalog::loadFromJsonFile(const QString &path, QString *outError) {
     QJsonObject o = it.value().toObject();
     QJsonObject o = it.value().toObject();
     def.mesh = meshKindFromString(o.value("mesh").toString("cube"));
     def.mesh = meshKindFromString(o.value("mesh").toString("cube"));
     QJsonArray col = o.value("color").toArray();
     QJsonArray col = o.value("color").toArray();
-    if (col.size() == 3)
+    if (col.size() == 3) {
       def.color =
       def.color =
           QVector3D(float(col[0].toDouble(1.0)), float(col[1].toDouble(1.0)),
           QVector3D(float(col[0].toDouble(1.0)), float(col[1].toDouble(1.0)),
                     float(col[2].toDouble(1.0)));
                     float(col[2].toDouble(1.0)));
+    }
     def.texture = o.value("texture").toString("");
     def.texture = o.value("texture").toString("");
     m_units.emplace(it.key().toStdString(), def);
     m_units.emplace(it.key().toStdString(), def);
   }
   }
@@ -78,8 +86,9 @@ bool VisualCatalog::loadFromJsonFile(const QString &path, QString *outError) {
 
 
 bool VisualCatalog::lookup(const std::string &unitType, VisualDef &out) const {
 bool VisualCatalog::lookup(const std::string &unitType, VisualDef &out) const {
   auto it = m_units.find(unitType);
   auto it = m_units.find(unitType);
-  if (it == m_units.end())
+  if (it == m_units.end()) {
     return false;
     return false;
+  }
   out = it->second;
   out = it->second;
   return true;
   return true;
 }
 }

+ 6 - 3
render/entity/archer_renderer.cpp

@@ -211,8 +211,9 @@ public:
 
 
     QVector3D rightAxis = pose.shoulderR - pose.shoulderL;
     QVector3D rightAxis = pose.shoulderR - pose.shoulderL;
     rightAxis.setY(0.0f);
     rightAxis.setY(0.0f);
-    if (rightAxis.lengthSquared() < 1e-8f)
+    if (rightAxis.lengthSquared() < 1e-8f) {
       rightAxis = QVector3D(1, 0, 0);
       rightAxis = QVector3D(1, 0, 0);
+    }
     rightAxis.normalize();
     rightAxis.normalize();
     QVector3D outwardL = -rightAxis;
     QVector3D outwardL = -rightAxis;
     QVector3D outwardR = rightAxis;
     QVector3D outwardR = rightAxis;
@@ -232,8 +233,9 @@ public:
     uint32_t seed = 0u;
     uint32_t seed = 0u;
     if (ctx.entity) {
     if (ctx.entity) {
       auto *unit = ctx.entity->getComponent<Engine::Core::UnitComponent>();
       auto *unit = ctx.entity->getComponent<Engine::Core::UnitComponent>();
-      if (unit)
+      if (unit) {
         seed ^= uint32_t(unit->ownerId * 2654435761u);
         seed ^= uint32_t(unit->ownerId * 2654435761u);
+      }
       seed ^= uint32_t(reinterpret_cast<uintptr_t>(ctx.entity) & 0xFFFFFFFFu);
       seed ^= uint32_t(reinterpret_cast<uintptr_t>(ctx.entity) & 0xFFFFFFFFu);
     }
     }
 
 
@@ -409,8 +411,9 @@ public:
     auto drawManica = [&](const QVector3D &shoulder, const QVector3D &elbow) {
     auto drawManica = [&](const QVector3D &shoulder, const QVector3D &elbow) {
       QVector3D dir = (elbow - shoulder);
       QVector3D dir = (elbow - shoulder);
       float len = dir.length();
       float len = dir.length();
-      if (len < 1e-5f)
+      if (len < 1e-5f) {
         return;
         return;
+      }
       dir /= len;
       dir /= len;
 
 
       for (int i = 0; i < 4; ++i) {
       for (int i = 0; i < 4; ++i) {

+ 13 - 7
render/entity/barracks_renderer.cpp

@@ -604,16 +604,19 @@ static inline void drawRallyFlagIfAny(const DrawContext &p, ISubmitter &out,
 
 
 static inline void drawHealthBar(const DrawContext &p, ISubmitter &out,
 static inline void drawHealthBar(const DrawContext &p, ISubmitter &out,
                                  Mesh *unit, Texture *white) {
                                  Mesh *unit, Texture *white) {
-  if (!p.entity)
+  if (!p.entity) {
     return;
     return;
+  }
   auto *u = p.entity->getComponent<Engine::Core::UnitComponent>();
   auto *u = p.entity->getComponent<Engine::Core::UnitComponent>();
-  if (!u)
+  if (!u) {
     return;
     return;
+  }
 
 
   int mh = std::max(1, u->maxHealth);
   int mh = std::max(1, u->maxHealth);
   float ratio = std::clamp(u->health / float(mh), 0.0f, 1.0f);
   float ratio = std::clamp(u->health / float(mh), 0.0f, 1.0f);
-  if (ratio <= 0.0f)
+  if (ratio <= 0.0f) {
     return;
     return;
+  }
 
 
   constexpr float baseHeight = BuildingProportions::baseHeight;
   constexpr float baseHeight = BuildingProportions::baseHeight;
   constexpr float roofPitch = BuildingProportions::roofPitch;
   constexpr float roofPitch = BuildingProportions::roofPitch;
@@ -647,20 +650,23 @@ static inline void drawSelectionFX(const DrawContext &p, ISubmitter &out) {
   QVector3D pos = p.model.column(3).toVector3D();
   QVector3D pos = p.model.column(3).toVector3D();
   M.translate(pos.x(), 0.0f, pos.z());
   M.translate(pos.x(), 0.0f, pos.z());
   M.scale(2.2f, 1.0f, 2.0f);
   M.scale(2.2f, 1.0f, 2.0f);
-  if (p.selected)
+  if (p.selected) {
     out.selectionSmoke(M, QVector3D(0.2f, 0.85f, 0.2f), 0.35f);
     out.selectionSmoke(M, QVector3D(0.2f, 0.85f, 0.2f), 0.35f);
-  else if (p.hovered)
+  } else if (p.hovered) {
     out.selectionSmoke(M, QVector3D(0.95f, 0.92f, 0.25f), 0.22f);
     out.selectionSmoke(M, QVector3D(0.95f, 0.92f, 0.25f), 0.22f);
+  }
 }
 }
 
 
 static void drawBarracks(const DrawContext &p, ISubmitter &out) {
 static void drawBarracks(const DrawContext &p, ISubmitter &out) {
-  if (!p.resources || !p.entity)
+  if (!p.resources || !p.entity) {
     return;
     return;
+  }
 
 
   auto *t = p.entity->getComponent<Engine::Core::TransformComponent>();
   auto *t = p.entity->getComponent<Engine::Core::TransformComponent>();
   auto *r = p.entity->getComponent<Engine::Core::RenderableComponent>();
   auto *r = p.entity->getComponent<Engine::Core::RenderableComponent>();
-  if (!t || !r)
+  if (!t || !r) {
     return;
     return;
+  }
 
 
   Mesh *unit = p.resources->unit();
   Mesh *unit = p.resources->unit();
   Texture *white = p.resources->white();
   Texture *white = p.resources->white();

+ 7 - 4
render/entity/horse_renderer.cpp

@@ -703,16 +703,18 @@ void HorseRenderer::render(const DrawContext &ctx, const AnimationInputs &anim,
             : 0.0f;
             : 0.0f;
 
 
     shoulder.setZ(shoulder.z() + hipSwing * (isRear ? -0.12f : 0.10f));
     shoulder.setZ(shoulder.z() + hipSwing * (isRear ? -0.12f : 0.10f));
-    if (tightenLegs)
+    if (tightenLegs) {
       shoulder.setX(shoulder.x() - lateralSign * liftFactor * 0.05f);
       shoulder.setX(shoulder.x() - lateralSign * liftFactor * 0.05f);
+    }
 
 
     float thighLength = d.legLength * (isRear ? 0.62f : 0.56f);
     float thighLength = d.legLength * (isRear ? 0.62f : 0.56f);
     float hipPitch = hipSwing * (isRear ? 0.62f : 0.50f);
     float hipPitch = hipSwing * (isRear ? 0.62f : 0.50f);
     float inwardLean = tightenLegs ? (-0.06f - liftFactor * 0.045f) : -0.012f;
     float inwardLean = tightenLegs ? (-0.06f - liftFactor * 0.045f) : -0.012f;
     QVector3D thighDir(lateralSign * inwardLean, -std::cos(hipPitch) * 0.90f,
     QVector3D thighDir(lateralSign * inwardLean, -std::cos(hipPitch) * 0.90f,
                        (isRear ? -1.0f : 1.0f) * std::sin(hipPitch) * 0.65f);
                        (isRear ? -1.0f : 1.0f) * std::sin(hipPitch) * 0.65f);
-    if (thighDir.lengthSquared() > 1e-6f)
+    if (thighDir.lengthSquared() > 1e-6f) {
       thighDir.normalize();
       thighDir.normalize();
+    }
 
 
     QVector3D knee = shoulder + thighDir * thighLength;
     QVector3D knee = shoulder + thighDir * thighLength;
     knee.setY(knee.y() + liftFactor * thighLength * 0.28f);
     knee.setY(knee.y() + liftFactor * thighLength * 0.28f);
@@ -758,10 +760,11 @@ void HorseRenderer::render(const DrawContext &ctx, const AnimationInputs &anim,
     float bendSin = std::sin(kneeFlex * kPi * 0.5f);
     float bendSin = std::sin(kneeFlex * kPi * 0.5f);
     QVector3D forearmDir(0.0f, -bendCos,
     QVector3D forearmDir(0.0f, -bendCos,
                          (isRear ? -1.0f : 1.0f) * bendSin * 0.85f);
                          (isRear ? -1.0f : 1.0f) * bendSin * 0.85f);
-    if (forearmDir.lengthSquared() < 1e-6f)
+    if (forearmDir.lengthSquared() < 1e-6f) {
       forearmDir = QVector3D(0.0f, -1.0f, 0.0f);
       forearmDir = QVector3D(0.0f, -1.0f, 0.0f);
-    else
+    } else {
       forearmDir.normalize();
       forearmDir.normalize();
+    }
     QVector3D cannon = knee + forearmDir * forearmLength;
     QVector3D cannon = knee + forearmDir * forearmLength;
 
 
     float pasternLength = d.legLength * 0.12f;
     float pasternLength = d.legLength * 0.12f;

+ 10 - 5
render/entity/knight_renderer.cpp

@@ -319,8 +319,9 @@ public:
     auto drawArmPlate = [&](const QVector3D &shoulder, const QVector3D &elbow) {
     auto drawArmPlate = [&](const QVector3D &shoulder, const QVector3D &elbow) {
       QVector3D dir = (elbow - shoulder);
       QVector3D dir = (elbow - shoulder);
       float len = dir.length();
       float len = dir.length();
-      if (len < 1e-5f)
+      if (len < 1e-5f) {
         return;
         return;
+      }
       dir /= len;
       dir /= len;
 
 
       for (int i = 0; i < 3; ++i) {
       for (int i = 0; i < 3; ++i) {
@@ -514,12 +515,15 @@ private:
     QVector3D upish = yawM.map(QVector3D(0.05f, 1.0f, 0.15f));
     QVector3D upish = yawM.map(QVector3D(0.05f, 1.0f, 0.15f));
     QVector3D midish = yawM.map(QVector3D(0.08f, 0.20f, 1.0f));
     QVector3D midish = yawM.map(QVector3D(0.08f, 0.20f, 1.0f));
     QVector3D downish = yawM.map(QVector3D(0.10f, -1.0f, 0.25f));
     QVector3D downish = yawM.map(QVector3D(0.10f, -1.0f, 0.25f));
-    if (upish.lengthSquared() > 1e-6f)
+    if (upish.lengthSquared() > 1e-6f) {
       upish.normalize();
       upish.normalize();
-    if (midish.lengthSquared() > 1e-6f)
+    }
+    if (midish.lengthSquared() > 1e-6f) {
       midish.normalize();
       midish.normalize();
-    if (downish.lengthSquared() > 1e-6f)
+    }
+    if (downish.lengthSquared() > 1e-6f) {
       downish.normalize();
       downish.normalize();
+    }
 
 
     QVector3D swordDir = upish;
     QVector3D swordDir = upish;
 
 
@@ -563,8 +567,9 @@ private:
 
 
     QVector3D guardRight =
     QVector3D guardRight =
         QVector3D::crossProduct(QVector3D(0, 1, 0), swordDir);
         QVector3D::crossProduct(QVector3D(0, 1, 0), swordDir);
-    if (guardRight.lengthSquared() < 1e-6f)
+    if (guardRight.lengthSquared() < 1e-6f) {
       guardRight = QVector3D::crossProduct(QVector3D(1, 0, 0), swordDir);
       guardRight = QVector3D::crossProduct(QVector3D(1, 0, 0), swordDir);
+    }
     guardRight.normalize();
     guardRight.normalize();
 
 
     QVector3D guardL = guardCenter - guardRight * gw;
     QVector3D guardL = guardCenter - guardRight * gw;

+ 4 - 2
render/entity/mounted_knight_renderer.cpp

@@ -391,8 +391,9 @@ public:
     auto drawArmPlate = [&](const QVector3D &shoulder, const QVector3D &elbow) {
     auto drawArmPlate = [&](const QVector3D &shoulder, const QVector3D &elbow) {
       QVector3D dir = (elbow - shoulder);
       QVector3D dir = (elbow - shoulder);
       float len = dir.length();
       float len = dir.length();
-      if (len < 1e-5f)
+      if (len < 1e-5f) {
         return;
         return;
+      }
       dir /= len;
       dir /= len;
 
 
       for (int i = 0; i < 3; ++i) {
       for (int i = 0; i < 3; ++i) {
@@ -500,8 +501,9 @@ private:
 
 
     QVector3D worldUp(0.0f, 1.0f, 0.0f);
     QVector3D worldUp(0.0f, 1.0f, 0.0f);
     QVector3D rightAxis = QVector3D::crossProduct(worldUp, swordDir);
     QVector3D rightAxis = QVector3D::crossProduct(worldUp, swordDir);
-    if (rightAxis.lengthSquared() < 1e-6f)
+    if (rightAxis.lengthSquared() < 1e-6f) {
       rightAxis = QVector3D(1.0f, 0.0f, 0.0f);
       rightAxis = QVector3D(1.0f, 0.0f, 0.0f);
+    }
     rightAxis.normalize();
     rightAxis.normalize();
     QVector3D upAxis = QVector3D::crossProduct(swordDir, rightAxis);
     QVector3D upAxis = QVector3D::crossProduct(swordDir, rightAxis);
     upAxis.normalize();
     upAxis.normalize();

+ 2 - 1
render/entity/registry.cpp

@@ -17,8 +17,9 @@ void EntityRendererRegistry::registerRenderer(const std::string &type,
 
 
 RenderFunc EntityRendererRegistry::get(const std::string &type) const {
 RenderFunc EntityRendererRegistry::get(const std::string &type) const {
   auto it = m_map.find(type);
   auto it = m_map.find(type);
-  if (it != m_map.end())
+  if (it != m_map.end()) {
     return it->second;
     return it->second;
+  }
   return {};
   return {};
 }
 }
 
 

+ 12 - 6
render/entity/spearman_renderer.cpp

@@ -305,8 +305,9 @@ public:
     auto drawArmPlate = [&](const QVector3D &shoulder, const QVector3D &elbow) {
     auto drawArmPlate = [&](const QVector3D &shoulder, const QVector3D &elbow) {
       QVector3D dir = (elbow - shoulder);
       QVector3D dir = (elbow - shoulder);
       float len = dir.length();
       float len = dir.length();
-      if (len < 1e-5f)
+      if (len < 1e-5f) {
         return;
         return;
+      }
       dir /= len;
       dir /= len;
 
 
       for (int i = 0; i < 2; ++i) {
       for (int i = 0; i < 2; ++i) {
@@ -362,30 +363,35 @@ private:
     QVector3D gripPos = pose.handR;
     QVector3D gripPos = pose.handR;
 
 
     QVector3D spearDir = QVector3D(0.05f, 0.55f, 0.85f);
     QVector3D spearDir = QVector3D(0.05f, 0.55f, 0.85f);
-    if (spearDir.lengthSquared() > 1e-6f)
+    if (spearDir.lengthSquared() > 1e-6f) {
       spearDir.normalize();
       spearDir.normalize();
+    }
 
 
     if (anim.isInHoldMode || anim.isExitingHold) {
     if (anim.isInHoldMode || anim.isExitingHold) {
       float t = anim.isInHoldMode ? 1.0f : (1.0f - anim.holdExitProgress);
       float t = anim.isInHoldMode ? 1.0f : (1.0f - anim.holdExitProgress);
 
 
       QVector3D bracedDir = QVector3D(0.05f, 0.40f, 0.91f);
       QVector3D bracedDir = QVector3D(0.05f, 0.40f, 0.91f);
-      if (bracedDir.lengthSquared() > 1e-6f)
+      if (bracedDir.lengthSquared() > 1e-6f) {
         bracedDir.normalize();
         bracedDir.normalize();
+      }
 
 
       spearDir = spearDir * (1.0f - t) + bracedDir * t;
       spearDir = spearDir * (1.0f - t) + bracedDir * t;
-      if (spearDir.lengthSquared() > 1e-6f)
+      if (spearDir.lengthSquared() > 1e-6f) {
         spearDir.normalize();
         spearDir.normalize();
+      }
     } else if (isAttacking) {
     } else if (isAttacking) {
       if (attackPhase >= 0.30f && attackPhase < 0.50f) {
       if (attackPhase >= 0.30f && attackPhase < 0.50f) {
         float t = (attackPhase - 0.30f) / 0.20f;
         float t = (attackPhase - 0.30f) / 0.20f;
 
 
         QVector3D attackDir = QVector3D(0.03f, -0.15f, 1.0f);
         QVector3D attackDir = QVector3D(0.03f, -0.15f, 1.0f);
-        if (attackDir.lengthSquared() > 1e-6f)
+        if (attackDir.lengthSquared() > 1e-6f) {
           attackDir.normalize();
           attackDir.normalize();
+        }
 
 
         spearDir = spearDir * (1.0f - t) + attackDir * t;
         spearDir = spearDir * (1.0f - t) + attackDir * t;
-        if (spearDir.lengthSquared() > 1e-6f)
+        if (spearDir.lengthSquared() > 1e-6f) {
           spearDir.normalize();
           spearDir.normalize();
+        }
       }
       }
     }
     }
 
 

+ 6 - 3
render/geom/arrow.cpp

@@ -88,16 +88,19 @@ namespace GL {
 
 
 void renderArrows(Renderer *renderer, ResourceManager *resources,
 void renderArrows(Renderer *renderer, ResourceManager *resources,
                   const Game::Systems::ArrowSystem &arrowSystem) {
                   const Game::Systems::ArrowSystem &arrowSystem) {
-  if (!renderer || !resources)
+  if (!renderer || !resources) {
     return;
     return;
+  }
   auto *arrowMesh = resources->arrow();
   auto *arrowMesh = resources->arrow();
-  if (!arrowMesh)
+  if (!arrowMesh) {
     return;
     return;
+  }
 
 
   const auto &arrows = arrowSystem.arrows();
   const auto &arrows = arrowSystem.arrows();
   for (const auto &arrow : arrows) {
   for (const auto &arrow : arrows) {
-    if (!arrow.active)
+    if (!arrow.active) {
       continue;
       continue;
+    }
 
 
     const QVector3D delta = arrow.end - arrow.start;
     const QVector3D delta = arrow.end - arrow.start;
     const float dist = std::max(0.001f, delta.length());
     const float dist = std::max(0.001f, delta.length());

+ 6 - 3
render/geom/patrol_flags.cpp

@@ -11,8 +11,9 @@ namespace Render::GL {
 void renderPatrolFlags(Renderer *renderer, ResourceManager *resources,
 void renderPatrolFlags(Renderer *renderer, ResourceManager *resources,
                        Engine::Core::World &world,
                        Engine::Core::World &world,
                        const std::optional<QVector3D> &previewWaypoint) {
                        const std::optional<QVector3D> &previewWaypoint) {
-  if (!renderer || !resources)
+  if (!renderer || !resources) {
     return;
     return;
+  }
 
 
   std::unordered_set<uint64_t> renderedPositions;
   std::unordered_set<uint64_t> renderedPositions;
 
 
@@ -39,12 +40,14 @@ void renderPatrolFlags(Renderer *renderer, ResourceManager *resources,
 
 
   for (auto *entity : patrolEntities) {
   for (auto *entity : patrolEntities) {
     auto *patrol = entity->getComponent<Engine::Core::PatrolComponent>();
     auto *patrol = entity->getComponent<Engine::Core::PatrolComponent>();
-    if (!patrol || !patrol->patrolling || patrol->waypoints.empty())
+    if (!patrol || !patrol->patrolling || patrol->waypoints.empty()) {
       continue;
       continue;
+    }
 
 
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
     auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
-    if (!unit || unit->health <= 0)
+    if (!unit || unit->health <= 0) {
       continue;
       continue;
+    }
 
 
     for (const auto &waypoint : patrol->waypoints) {
     for (const auto &waypoint : patrol->waypoints) {
 
 

+ 2 - 1
render/geom/selection_disc.cpp

@@ -30,8 +30,9 @@ static Render::GL::Mesh *createDiscMesh() {
 }
 }
 
 
 Render::GL::Mesh *SelectionDisc::get() {
 Render::GL::Mesh *SelectionDisc::get() {
-  if (!s_mesh)
+  if (!s_mesh) {
     s_mesh.reset(createDiscMesh());
     s_mesh.reset(createDiscMesh());
+  }
   return s_mesh.get();
   return s_mesh.get();
 }
 }
 
 

+ 2 - 1
render/geom/selection_ring.cpp

@@ -37,8 +37,9 @@ static Render::GL::Mesh *createRingMesh() {
 }
 }
 
 
 Render::GL::Mesh *SelectionRing::get() {
 Render::GL::Mesh *SelectionRing::get() {
-  if (!s_mesh)
+  if (!s_mesh) {
     s_mesh.reset(createRingMesh());
     s_mesh.reset(createRingMesh());
+  }
   return s_mesh.get();
   return s_mesh.get();
 }
 }
 
 

+ 204 - 103
render/gl/backend.cpp

@@ -64,42 +64,59 @@ void Backend::initialize() {
   m_archerShader = m_shaderCache->get(QStringLiteral("archer"));
   m_archerShader = m_shaderCache->get(QStringLiteral("archer"));
   m_knightShader = m_shaderCache->get(QStringLiteral("knight"));
   m_knightShader = m_shaderCache->get(QStringLiteral("knight"));
   m_spearmanShader = m_shaderCache->get(QStringLiteral("spearman"));
   m_spearmanShader = m_shaderCache->get(QStringLiteral("spearman"));
-  if (!m_basicShader)
+  if (!m_basicShader) {
     qWarning() << "Backend: basic shader missing";
     qWarning() << "Backend: basic shader missing";
-  if (!m_gridShader)
+  }
+  if (!m_gridShader) {
     qWarning() << "Backend: grid shader missing";
     qWarning() << "Backend: grid shader missing";
-  if (!m_cylinderShader)
+  }
+  if (!m_cylinderShader) {
     qWarning() << "Backend: cylinder shader missing";
     qWarning() << "Backend: cylinder shader missing";
-  if (!m_fogShader)
+  }
+  if (!m_fogShader) {
     qWarning() << "Backend: fog shader missing";
     qWarning() << "Backend: fog shader missing";
-  if (!m_grassShader)
+  }
+  if (!m_grassShader) {
     qWarning() << "Backend: grass shader missing";
     qWarning() << "Backend: grass shader missing";
-  if (!m_stoneShader)
+  }
+  if (!m_stoneShader) {
     qWarning() << "Backend: stone shader missing";
     qWarning() << "Backend: stone shader missing";
-  if (!m_plantShader)
+  }
+  if (!m_plantShader) {
     qWarning()
     qWarning()
         << "Backend: plant shader missing - check plant_instanced.vert/frag";
         << "Backend: plant shader missing - check plant_instanced.vert/frag";
-  if (!m_pineShader)
+  }
+  if (!m_pineShader) {
     qWarning()
     qWarning()
         << "Backend: pine shader missing - check pine_instanced.vert/frag";
         << "Backend: pine shader missing - check pine_instanced.vert/frag";
-  if (!m_firecampShader)
+  }
+  if (!m_firecampShader) {
     qWarning() << "Backend: firecamp shader missing - check firecamp.vert/frag";
     qWarning() << "Backend: firecamp shader missing - check firecamp.vert/frag";
-  if (!m_groundShader)
+  }
+  if (!m_groundShader) {
     qWarning() << "Backend: ground_plane shader missing";
     qWarning() << "Backend: ground_plane shader missing";
-  if (!m_terrainShader)
+  }
+  if (!m_terrainShader) {
     qWarning() << "Backend: terrain shader missing";
     qWarning() << "Backend: terrain shader missing";
-  if (!m_riverShader)
+  }
+  if (!m_riverShader) {
     qWarning() << "Backend: river shader missing";
     qWarning() << "Backend: river shader missing";
-  if (!m_riverbankShader)
+  }
+  if (!m_riverbankShader) {
     qWarning() << "Backend: riverbank shader missing";
     qWarning() << "Backend: riverbank shader missing";
-  if (!m_bridgeShader)
+  }
+  if (!m_bridgeShader) {
     qWarning() << "Backend: bridge shader missing";
     qWarning() << "Backend: bridge shader missing";
-  if (!m_archerShader)
+  }
+  if (!m_archerShader) {
     qWarning() << "Backend: archer shader missing";
     qWarning() << "Backend: archer shader missing";
-  if (!m_knightShader)
+  }
+  if (!m_knightShader) {
     qWarning() << "Backend: knight shader missing";
     qWarning() << "Backend: knight shader missing";
-  if (!m_spearmanShader)
+  }
+  if (!m_spearmanShader) {
     qWarning() << "Backend: spearman shader missing";
     qWarning() << "Backend: spearman shader missing";
+  }
 
 
   cacheBasicUniforms();
   cacheBasicUniforms();
   cacheArcherUniforms();
   cacheArcherUniforms();
@@ -164,8 +181,9 @@ void Backend::setClearColor(float r, float g, float b, float a) {
 }
 }
 
 
 void Backend::execute(const DrawQueue &queue, const Camera &cam) {
 void Backend::execute(const DrawQueue &queue, const Camera &cam) {
-  if (!m_basicShader)
+  if (!m_basicShader) {
     return;
     return;
+  }
 
 
   const QMatrix4x4 viewProj = cam.getProjectionMatrix() * cam.getViewMatrix();
   const QMatrix4x4 viewProj = cam.getProjectionMatrix() * cam.getViewMatrix();
 
 
@@ -194,8 +212,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       const std::size_t instanceCount = m_cylinderScratch.size();
       const std::size_t instanceCount = m_cylinderScratch.size();
       if (instanceCount > 0 && m_cylinderShader && m_cylinderVao) {
       if (instanceCount > 0 && m_cylinderShader && m_cylinderVao) {
         glDepthMask(GL_TRUE);
         glDepthMask(GL_TRUE);
-        if (glIsEnabled(GL_POLYGON_OFFSET_FILL))
+        if (glIsEnabled(GL_POLYGON_OFFSET_FILL)) {
           glDisable(GL_POLYGON_OFFSET_FILL);
           glDisable(GL_POLYGON_OFFSET_FILL);
+        }
         if (m_lastBoundShader != m_cylinderShader) {
         if (m_lastBoundShader != m_cylinderShader) {
           m_cylinderShader->use();
           m_cylinderShader->use();
           m_lastBoundShader = m_cylinderShader;
           m_lastBoundShader = m_cylinderShader;
@@ -224,8 +243,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
           m_fogScratch[idx] = gpu;
           m_fogScratch[idx] = gpu;
         }
         }
         glDepthMask(GL_TRUE);
         glDepthMask(GL_TRUE);
-        if (glIsEnabled(GL_POLYGON_OFFSET_FILL))
+        if (glIsEnabled(GL_POLYGON_OFFSET_FILL)) {
           glDisable(GL_POLYGON_OFFSET_FILL);
           glDisable(GL_POLYGON_OFFSET_FILL);
+        }
         if (m_lastBoundShader != m_fogShader) {
         if (m_lastBoundShader != m_fogShader) {
           m_fogShader->use();
           m_fogShader->use();
           m_lastBoundShader = m_fogShader;
           m_lastBoundShader = m_fogShader;
@@ -243,15 +263,17 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
     case GrassBatchCmdIndex: {
     case GrassBatchCmdIndex: {
       const auto &grass = std::get<GrassBatchCmdIndex>(cmd);
       const auto &grass = std::get<GrassBatchCmdIndex>(cmd);
       if (!grass.instanceBuffer || grass.instanceCount == 0 || !m_grassShader ||
       if (!grass.instanceBuffer || grass.instanceCount == 0 || !m_grassShader ||
-          !m_grassVao || m_grassVertexCount == 0)
+          !m_grassVao || m_grassVertexCount == 0) {
         break;
         break;
+      }
 
 
       DepthMaskScope depthMask(false);
       DepthMaskScope depthMask(false);
       BlendScope blend(true);
       BlendScope blend(true);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       GLboolean prevCull = glIsEnabled(GL_CULL_FACE);
       GLboolean prevCull = glIsEnabled(GL_CULL_FACE);
-      if (prevCull)
+      if (prevCull) {
         glDisable(GL_CULL_FACE);
         glDisable(GL_CULL_FACE);
+      }
 
 
       if (m_lastBoundShader != m_grassShader) {
       if (m_lastBoundShader != m_grassShader) {
         m_grassShader->use();
         m_grassShader->use();
@@ -279,8 +301,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       }
       }
       if (m_grassUniforms.lightDir != Shader::InvalidUniform) {
       if (m_grassUniforms.lightDir != Shader::InvalidUniform) {
         QVector3D lightDir = grass.params.lightDirection;
         QVector3D lightDir = grass.params.lightDirection;
-        if (!lightDir.isNull())
+        if (!lightDir.isNull()) {
           lightDir.normalize();
           lightDir.normalize();
+        }
         m_grassShader->setUniform(m_grassUniforms.lightDir, lightDir);
         m_grassShader->setUniform(m_grassUniforms.lightDir, lightDir);
       }
       }
 
 
@@ -302,16 +325,18 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
                             static_cast<GLsizei>(grass.instanceCount));
                             static_cast<GLsizei>(grass.instanceCount));
       glBindVertexArray(0);
       glBindVertexArray(0);
 
 
-      if (prevCull)
+      if (prevCull) {
         glEnable(GL_CULL_FACE);
         glEnable(GL_CULL_FACE);
+      }
 
 
       break;
       break;
     }
     }
     case StoneBatchCmdIndex: {
     case StoneBatchCmdIndex: {
       const auto &stone = std::get<StoneBatchCmdIndex>(cmd);
       const auto &stone = std::get<StoneBatchCmdIndex>(cmd);
       if (!stone.instanceBuffer || stone.instanceCount == 0 || !m_stoneShader ||
       if (!stone.instanceBuffer || stone.instanceCount == 0 || !m_stoneShader ||
-          !m_stoneVao || m_stoneIndexCount == 0)
+          !m_stoneVao || m_stoneIndexCount == 0) {
         break;
         break;
+      }
 
 
       DepthMaskScope depthMask(true);
       DepthMaskScope depthMask(true);
       BlendScope blend(false);
       BlendScope blend(false);
@@ -327,8 +352,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       }
       }
       if (m_stoneUniforms.lightDirection != Shader::InvalidUniform) {
       if (m_stoneUniforms.lightDirection != Shader::InvalidUniform) {
         QVector3D lightDir = stone.params.lightDirection;
         QVector3D lightDir = stone.params.lightDirection;
-        if (!lightDir.isNull())
+        if (!lightDir.isNull()) {
           lightDir.normalize();
           lightDir.normalize();
+        }
         m_stoneShader->setUniform(m_stoneUniforms.lightDirection, lightDir);
         m_stoneShader->setUniform(m_stoneUniforms.lightDirection, lightDir);
       }
       }
 
 
@@ -364,8 +390,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       BlendScope blend(true);
       BlendScope blend(true);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       GLboolean prevCull = glIsEnabled(GL_CULL_FACE);
       GLboolean prevCull = glIsEnabled(GL_CULL_FACE);
-      if (prevCull)
+      if (prevCull) {
         glDisable(GL_CULL_FACE);
         glDisable(GL_CULL_FACE);
+      }
 
 
       if (m_lastBoundShader != m_plantShader) {
       if (m_lastBoundShader != m_plantShader) {
         m_plantShader->use();
         m_plantShader->use();
@@ -389,8 +416,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       }
       }
       if (m_plantUniforms.lightDirection != Shader::InvalidUniform) {
       if (m_plantUniforms.lightDirection != Shader::InvalidUniform) {
         QVector3D lightDir = plant.params.lightDirection;
         QVector3D lightDir = plant.params.lightDirection;
-        if (!lightDir.isNull())
+        if (!lightDir.isNull()) {
           lightDir.normalize();
           lightDir.normalize();
+        }
         m_plantShader->setUniform(m_plantUniforms.lightDirection, lightDir);
         m_plantShader->setUniform(m_plantUniforms.lightDirection, lightDir);
       }
       }
 
 
@@ -413,8 +441,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
                               static_cast<GLsizei>(plant.instanceCount));
                               static_cast<GLsizei>(plant.instanceCount));
       glBindVertexArray(0);
       glBindVertexArray(0);
 
 
-      if (prevCull)
+      if (prevCull) {
         glEnable(GL_CULL_FACE);
         glEnable(GL_CULL_FACE);
+      }
 
 
       break;
       break;
     }
     }
@@ -431,8 +460,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       BlendScope blend(true);
       BlendScope blend(true);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       GLboolean prevCull = glIsEnabled(GL_CULL_FACE);
       GLboolean prevCull = glIsEnabled(GL_CULL_FACE);
-      if (prevCull)
+      if (prevCull) {
         glDisable(GL_CULL_FACE);
         glDisable(GL_CULL_FACE);
+      }
 
 
       if (m_lastBoundShader != m_pineShader) {
       if (m_lastBoundShader != m_pineShader) {
         m_pineShader->use();
         m_pineShader->use();
@@ -456,8 +486,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       }
       }
       if (m_pineUniforms.lightDirection != Shader::InvalidUniform) {
       if (m_pineUniforms.lightDirection != Shader::InvalidUniform) {
         QVector3D lightDir = pine.params.lightDirection;
         QVector3D lightDir = pine.params.lightDirection;
-        if (!lightDir.isNull())
+        if (!lightDir.isNull()) {
           lightDir.normalize();
           lightDir.normalize();
+        }
         m_pineShader->setUniform(m_pineUniforms.lightDirection, lightDir);
         m_pineShader->setUniform(m_pineUniforms.lightDirection, lightDir);
       }
       }
 
 
@@ -480,8 +511,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
                               static_cast<GLsizei>(pine.instanceCount));
                               static_cast<GLsizei>(pine.instanceCount));
       glBindVertexArray(0);
       glBindVertexArray(0);
 
 
-      if (prevCull)
+      if (prevCull) {
         glEnable(GL_CULL_FACE);
         glEnable(GL_CULL_FACE);
+      }
 
 
       break;
       break;
     }
     }
@@ -498,8 +530,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       BlendScope blend(true);
       BlendScope blend(true);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       GLboolean prevCull = glIsEnabled(GL_CULL_FACE);
       GLboolean prevCull = glIsEnabled(GL_CULL_FACE);
-      if (prevCull)
+      if (prevCull) {
         glDisable(GL_CULL_FACE);
         glDisable(GL_CULL_FACE);
+      }
 
 
       if (m_lastBoundShader != m_firecampShader) {
       if (m_lastBoundShader != m_firecampShader) {
         m_firecampShader->use();
         m_firecampShader->use();
@@ -570,8 +603,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
                               static_cast<GLsizei>(firecamp.instanceCount));
                               static_cast<GLsizei>(firecamp.instanceCount));
       glBindVertexArray(0);
       glBindVertexArray(0);
 
 
-      if (prevCull)
+      if (prevCull) {
         glEnable(GL_CULL_FACE);
         glEnable(GL_CULL_FACE);
+      }
 
 
       break;
       break;
     }
     }
@@ -581,8 +615,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       Shader *activeShader =
       Shader *activeShader =
           terrain.params.isGroundPlane ? m_groundShader : m_terrainShader;
           terrain.params.isGroundPlane ? m_groundShader : m_terrainShader;
 
 
-      if (!terrain.mesh || !activeShader)
+      if (!terrain.mesh || !activeShader) {
         break;
         break;
+      }
 
 
       if (m_lastBoundShader != activeShader) {
       if (m_lastBoundShader != activeShader) {
         activeShader->use();
         activeShader->use();
@@ -594,142 +629,183 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
 
 
       if (terrain.params.isGroundPlane) {
       if (terrain.params.isGroundPlane) {
 
 
-        if (m_groundUniforms.mvp != Shader::InvalidUniform)
+        if (m_groundUniforms.mvp != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.mvp, mvp);
           activeShader->setUniform(m_groundUniforms.mvp, mvp);
-        if (m_groundUniforms.model != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.model != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.model, terrain.model);
           activeShader->setUniform(m_groundUniforms.model, terrain.model);
-        if (m_groundUniforms.grassPrimary != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.grassPrimary != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.grassPrimary,
           activeShader->setUniform(m_groundUniforms.grassPrimary,
                                    terrain.params.grassPrimary);
                                    terrain.params.grassPrimary);
-        if (m_groundUniforms.grassSecondary != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.grassSecondary != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.grassSecondary,
           activeShader->setUniform(m_groundUniforms.grassSecondary,
                                    terrain.params.grassSecondary);
                                    terrain.params.grassSecondary);
-        if (m_groundUniforms.grassDry != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.grassDry != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.grassDry,
           activeShader->setUniform(m_groundUniforms.grassDry,
                                    terrain.params.grassDry);
                                    terrain.params.grassDry);
-        if (m_groundUniforms.soilColor != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.soilColor != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.soilColor,
           activeShader->setUniform(m_groundUniforms.soilColor,
                                    terrain.params.soilColor);
                                    terrain.params.soilColor);
-        if (m_groundUniforms.tint != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.tint != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.tint, terrain.params.tint);
           activeShader->setUniform(m_groundUniforms.tint, terrain.params.tint);
-        if (m_groundUniforms.noiseOffset != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.noiseOffset != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.noiseOffset,
           activeShader->setUniform(m_groundUniforms.noiseOffset,
                                    terrain.params.noiseOffset);
                                    terrain.params.noiseOffset);
-        if (m_groundUniforms.tileSize != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.tileSize != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.tileSize,
           activeShader->setUniform(m_groundUniforms.tileSize,
                                    terrain.params.tileSize);
                                    terrain.params.tileSize);
-        if (m_groundUniforms.macroNoiseScale != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.macroNoiseScale != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.macroNoiseScale,
           activeShader->setUniform(m_groundUniforms.macroNoiseScale,
                                    terrain.params.macroNoiseScale);
                                    terrain.params.macroNoiseScale);
-        if (m_groundUniforms.detailNoiseScale != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.detailNoiseScale != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.detailNoiseScale,
           activeShader->setUniform(m_groundUniforms.detailNoiseScale,
                                    terrain.params.detailNoiseScale);
                                    terrain.params.detailNoiseScale);
-        if (m_groundUniforms.soilBlendHeight != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.soilBlendHeight != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.soilBlendHeight,
           activeShader->setUniform(m_groundUniforms.soilBlendHeight,
                                    terrain.params.soilBlendHeight);
                                    terrain.params.soilBlendHeight);
-        if (m_groundUniforms.soilBlendSharpness != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.soilBlendSharpness != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.soilBlendSharpness,
           activeShader->setUniform(m_groundUniforms.soilBlendSharpness,
                                    terrain.params.soilBlendSharpness);
                                    terrain.params.soilBlendSharpness);
-        if (m_groundUniforms.ambientBoost != Shader::InvalidUniform)
+        }
+        if (m_groundUniforms.ambientBoost != Shader::InvalidUniform) {
           activeShader->setUniform(m_groundUniforms.ambientBoost,
           activeShader->setUniform(m_groundUniforms.ambientBoost,
                                    terrain.params.ambientBoost);
                                    terrain.params.ambientBoost);
+        }
         if (m_groundUniforms.lightDir != Shader::InvalidUniform) {
         if (m_groundUniforms.lightDir != Shader::InvalidUniform) {
           QVector3D lightDir = terrain.params.lightDirection;
           QVector3D lightDir = terrain.params.lightDirection;
-          if (!lightDir.isNull())
+          if (!lightDir.isNull()) {
             lightDir.normalize();
             lightDir.normalize();
+          }
           activeShader->setUniform(m_groundUniforms.lightDir, lightDir);
           activeShader->setUniform(m_groundUniforms.lightDir, lightDir);
         }
         }
       } else {
       } else {
 
 
-        if (m_terrainUniforms.mvp != Shader::InvalidUniform)
+        if (m_terrainUniforms.mvp != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.mvp, mvp);
           activeShader->setUniform(m_terrainUniforms.mvp, mvp);
-        if (m_terrainUniforms.model != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.model != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.model, terrain.model);
           activeShader->setUniform(m_terrainUniforms.model, terrain.model);
-        if (m_terrainUniforms.grassPrimary != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.grassPrimary != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.grassPrimary,
           activeShader->setUniform(m_terrainUniforms.grassPrimary,
                                    terrain.params.grassPrimary);
                                    terrain.params.grassPrimary);
-        if (m_terrainUniforms.grassSecondary != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.grassSecondary != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.grassSecondary,
           activeShader->setUniform(m_terrainUniforms.grassSecondary,
                                    terrain.params.grassSecondary);
                                    terrain.params.grassSecondary);
-        if (m_terrainUniforms.grassDry != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.grassDry != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.grassDry,
           activeShader->setUniform(m_terrainUniforms.grassDry,
                                    terrain.params.grassDry);
                                    terrain.params.grassDry);
-        if (m_terrainUniforms.soilColor != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.soilColor != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.soilColor,
           activeShader->setUniform(m_terrainUniforms.soilColor,
                                    terrain.params.soilColor);
                                    terrain.params.soilColor);
-        if (m_terrainUniforms.rockLow != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.rockLow != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.rockLow,
           activeShader->setUniform(m_terrainUniforms.rockLow,
                                    terrain.params.rockLow);
                                    terrain.params.rockLow);
-        if (m_terrainUniforms.rockHigh != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.rockHigh != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.rockHigh,
           activeShader->setUniform(m_terrainUniforms.rockHigh,
                                    terrain.params.rockHigh);
                                    terrain.params.rockHigh);
-        if (m_terrainUniforms.tint != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.tint != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.tint, terrain.params.tint);
           activeShader->setUniform(m_terrainUniforms.tint, terrain.params.tint);
-        if (m_terrainUniforms.noiseOffset != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.noiseOffset != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.noiseOffset,
           activeShader->setUniform(m_terrainUniforms.noiseOffset,
                                    terrain.params.noiseOffset);
                                    terrain.params.noiseOffset);
-        if (m_terrainUniforms.tileSize != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.tileSize != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.tileSize,
           activeShader->setUniform(m_terrainUniforms.tileSize,
                                    terrain.params.tileSize);
                                    terrain.params.tileSize);
-        if (m_terrainUniforms.macroNoiseScale != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.macroNoiseScale != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.macroNoiseScale,
           activeShader->setUniform(m_terrainUniforms.macroNoiseScale,
                                    terrain.params.macroNoiseScale);
                                    terrain.params.macroNoiseScale);
-        if (m_terrainUniforms.detailNoiseScale != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.detailNoiseScale != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.detailNoiseScale,
           activeShader->setUniform(m_terrainUniforms.detailNoiseScale,
                                    terrain.params.detailNoiseScale);
                                    terrain.params.detailNoiseScale);
-        if (m_terrainUniforms.slopeRockThreshold != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.slopeRockThreshold != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.slopeRockThreshold,
           activeShader->setUniform(m_terrainUniforms.slopeRockThreshold,
                                    terrain.params.slopeRockThreshold);
                                    terrain.params.slopeRockThreshold);
-        if (m_terrainUniforms.slopeRockSharpness != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.slopeRockSharpness != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.slopeRockSharpness,
           activeShader->setUniform(m_terrainUniforms.slopeRockSharpness,
                                    terrain.params.slopeRockSharpness);
                                    terrain.params.slopeRockSharpness);
-        if (m_terrainUniforms.soilBlendHeight != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.soilBlendHeight != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.soilBlendHeight,
           activeShader->setUniform(m_terrainUniforms.soilBlendHeight,
                                    terrain.params.soilBlendHeight);
                                    terrain.params.soilBlendHeight);
-        if (m_terrainUniforms.soilBlendSharpness != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.soilBlendSharpness != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.soilBlendSharpness,
           activeShader->setUniform(m_terrainUniforms.soilBlendSharpness,
                                    terrain.params.soilBlendSharpness);
                                    terrain.params.soilBlendSharpness);
-        if (m_terrainUniforms.heightNoiseStrength != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.heightNoiseStrength != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.heightNoiseStrength,
           activeShader->setUniform(m_terrainUniforms.heightNoiseStrength,
                                    terrain.params.heightNoiseStrength);
                                    terrain.params.heightNoiseStrength);
-        if (m_terrainUniforms.heightNoiseFrequency != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.heightNoiseFrequency != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.heightNoiseFrequency,
           activeShader->setUniform(m_terrainUniforms.heightNoiseFrequency,
                                    terrain.params.heightNoiseFrequency);
                                    terrain.params.heightNoiseFrequency);
-        if (m_terrainUniforms.ambientBoost != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.ambientBoost != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.ambientBoost,
           activeShader->setUniform(m_terrainUniforms.ambientBoost,
                                    terrain.params.ambientBoost);
                                    terrain.params.ambientBoost);
-        if (m_terrainUniforms.rockDetailStrength != Shader::InvalidUniform)
+        }
+        if (m_terrainUniforms.rockDetailStrength != Shader::InvalidUniform) {
           activeShader->setUniform(m_terrainUniforms.rockDetailStrength,
           activeShader->setUniform(m_terrainUniforms.rockDetailStrength,
                                    terrain.params.rockDetailStrength);
                                    terrain.params.rockDetailStrength);
+        }
         if (m_terrainUniforms.lightDir != Shader::InvalidUniform) {
         if (m_terrainUniforms.lightDir != Shader::InvalidUniform) {
           QVector3D lightDir = terrain.params.lightDirection;
           QVector3D lightDir = terrain.params.lightDirection;
-          if (!lightDir.isNull())
+          if (!lightDir.isNull()) {
             lightDir.normalize();
             lightDir.normalize();
+          }
           activeShader->setUniform(m_terrainUniforms.lightDir, lightDir);
           activeShader->setUniform(m_terrainUniforms.lightDir, lightDir);
         }
         }
       }
       }
 
 
       DepthMaskScope depthMask(terrain.depthWrite);
       DepthMaskScope depthMask(terrain.depthWrite);
       std::unique_ptr<PolygonOffsetScope> polyScope;
       std::unique_ptr<PolygonOffsetScope> polyScope;
-      if (terrain.depthBias != 0.0f)
+      if (terrain.depthBias != 0.0f) {
         polyScope = std::make_unique<PolygonOffsetScope>(terrain.depthBias,
         polyScope = std::make_unique<PolygonOffsetScope>(terrain.depthBias,
                                                          terrain.depthBias);
                                                          terrain.depthBias);
+      }
 
 
       terrain.mesh->draw();
       terrain.mesh->draw();
       break;
       break;
     }
     }
     case MeshCmdIndex: {
     case MeshCmdIndex: {
       const auto &it = std::get<MeshCmdIndex>(cmd);
       const auto &it = std::get<MeshCmdIndex>(cmd);
-      if (!it.mesh)
+      if (!it.mesh) {
         break;
         break;
+      }
 
 
       glDepthMask(GL_TRUE);
       glDepthMask(GL_TRUE);
-      if (glIsEnabled(GL_POLYGON_OFFSET_FILL))
+      if (glIsEnabled(GL_POLYGON_OFFSET_FILL)) {
         glDisable(GL_POLYGON_OFFSET_FILL);
         glDisable(GL_POLYGON_OFFSET_FILL);
+      }
 
 
       Shader *activeShader = it.shader ? it.shader : m_basicShader;
       Shader *activeShader = it.shader ? it.shader : m_basicShader;
-      if (!activeShader)
+      if (!activeShader) {
         break;
         break;
+      }
 
 
       if (activeShader == m_riverShader) {
       if (activeShader == m_riverShader) {
         if (m_lastBoundShader != activeShader) {
         if (m_lastBoundShader != activeShader) {
@@ -781,12 +857,13 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       }
       }
 
 
       BasicUniforms *uniforms = &m_basicUniforms;
       BasicUniforms *uniforms = &m_basicUniforms;
-      if (activeShader == m_archerShader)
+      if (activeShader == m_archerShader) {
         uniforms = &m_archerUniforms;
         uniforms = &m_archerUniforms;
-      else if (activeShader == m_knightShader)
+      } else if (activeShader == m_knightShader) {
         uniforms = &m_knightUniforms;
         uniforms = &m_knightUniforms;
-      else if (activeShader == m_spearmanShader)
+      } else if (activeShader == m_spearmanShader) {
         uniforms = &m_spearmanUniforms;
         uniforms = &m_spearmanUniforms;
+      }
 
 
       if (m_lastBoundShader != activeShader) {
       if (m_lastBoundShader != activeShader) {
         activeShader->use();
         activeShader->use();
@@ -812,8 +889,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       break;
       break;
     }
     }
     case GridCmdIndex: {
     case GridCmdIndex: {
-      if (!m_gridShader)
+      if (!m_gridShader) {
         break;
         break;
+      }
       const auto &gc = std::get<GridCmdIndex>(cmd);
       const auto &gc = std::get<GridCmdIndex>(cmd);
 
 
       if (m_lastBoundShader != m_gridShader) {
       if (m_lastBoundShader != m_gridShader) {
@@ -829,16 +907,18 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
       m_gridShader->setUniform(m_gridUniforms.thickness, gc.thickness);
       m_gridShader->setUniform(m_gridUniforms.thickness, gc.thickness);
 
 
       if (m_resources) {
       if (m_resources) {
-        if (auto *plane = m_resources->ground())
+        if (auto *plane = m_resources->ground()) {
           plane->draw();
           plane->draw();
+        }
       }
       }
       break;
       break;
     }
     }
     case SelectionRingCmdIndex: {
     case SelectionRingCmdIndex: {
       const auto &sc = std::get<SelectionRingCmdIndex>(cmd);
       const auto &sc = std::get<SelectionRingCmdIndex>(cmd);
       Mesh *ring = Render::Geom::SelectionRing::get();
       Mesh *ring = Render::Geom::SelectionRing::get();
-      if (!ring)
+      if (!ring) {
         break;
         break;
+      }
 
 
       if (m_lastBoundShader != m_basicShader) {
       if (m_lastBoundShader != m_basicShader) {
         m_basicShader->use();
         m_basicShader->use();
@@ -875,8 +955,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
     case SelectionSmokeCmdIndex: {
     case SelectionSmokeCmdIndex: {
       const auto &sm = std::get<SelectionSmokeCmdIndex>(cmd);
       const auto &sm = std::get<SelectionSmokeCmdIndex>(cmd);
       Mesh *disc = Render::Geom::SelectionDisc::get();
       Mesh *disc = Render::Geom::SelectionDisc::get();
-      if (!disc)
+      if (!disc) {
         break;
         break;
+      }
 
 
       if (m_lastBoundShader != m_basicShader) {
       if (m_lastBoundShader != m_basicShader) {
         m_basicShader->use();
         m_basicShader->use();
@@ -915,8 +996,9 @@ void Backend::execute(const DrawQueue &queue, const Camera &cam) {
 }
 }
 
 
 void Backend::cacheBasicUniforms() {
 void Backend::cacheBasicUniforms() {
-  if (!m_basicShader)
+  if (!m_basicShader) {
     return;
     return;
+  }
 
 
   m_basicUniforms.mvp = m_basicShader->uniformHandle("u_mvp");
   m_basicUniforms.mvp = m_basicShader->uniformHandle("u_mvp");
   m_basicUniforms.model = m_basicShader->uniformHandle("u_model");
   m_basicUniforms.model = m_basicShader->uniformHandle("u_model");
@@ -927,8 +1009,9 @@ void Backend::cacheBasicUniforms() {
 }
 }
 
 
 void Backend::cacheArcherUniforms() {
 void Backend::cacheArcherUniforms() {
-  if (!m_archerShader)
+  if (!m_archerShader) {
     return;
     return;
+  }
 
 
   m_archerUniforms.mvp = m_archerShader->uniformHandle("u_mvp");
   m_archerUniforms.mvp = m_archerShader->uniformHandle("u_mvp");
   m_archerUniforms.model = m_archerShader->uniformHandle("u_model");
   m_archerUniforms.model = m_archerShader->uniformHandle("u_model");
@@ -939,8 +1022,9 @@ void Backend::cacheArcherUniforms() {
 }
 }
 
 
 void Backend::cacheKnightUniforms() {
 void Backend::cacheKnightUniforms() {
-  if (!m_knightShader)
+  if (!m_knightShader) {
     return;
     return;
+  }
 
 
   m_knightUniforms.mvp = m_knightShader->uniformHandle("u_mvp");
   m_knightUniforms.mvp = m_knightShader->uniformHandle("u_mvp");
   m_knightUniforms.model = m_knightShader->uniformHandle("u_model");
   m_knightUniforms.model = m_knightShader->uniformHandle("u_model");
@@ -951,8 +1035,9 @@ void Backend::cacheKnightUniforms() {
 }
 }
 
 
 void Backend::cacheSpearmanUniforms() {
 void Backend::cacheSpearmanUniforms() {
-  if (!m_spearmanShader)
+  if (!m_spearmanShader) {
     return;
     return;
+  }
 
 
   m_spearmanUniforms.mvp = m_spearmanShader->uniformHandle("u_mvp");
   m_spearmanUniforms.mvp = m_spearmanShader->uniformHandle("u_mvp");
   m_spearmanUniforms.model = m_spearmanShader->uniformHandle("u_model");
   m_spearmanUniforms.model = m_spearmanShader->uniformHandle("u_model");
@@ -964,8 +1049,9 @@ void Backend::cacheSpearmanUniforms() {
 }
 }
 
 
 void Backend::cacheGridUniforms() {
 void Backend::cacheGridUniforms() {
-  if (!m_gridShader)
+  if (!m_gridShader) {
     return;
     return;
+  }
 
 
   m_gridUniforms.mvp = m_gridShader->uniformHandle("u_mvp");
   m_gridUniforms.mvp = m_gridShader->uniformHandle("u_mvp");
   m_gridUniforms.model = m_gridShader->uniformHandle("u_model");
   m_gridUniforms.model = m_gridShader->uniformHandle("u_model");
@@ -976,15 +1062,17 @@ void Backend::cacheGridUniforms() {
 }
 }
 
 
 void Backend::cacheCylinderUniforms() {
 void Backend::cacheCylinderUniforms() {
-  if (!m_cylinderShader)
+  if (!m_cylinderShader) {
     return;
     return;
+  }
 
 
   m_cylinderUniforms.viewProj = m_cylinderShader->uniformHandle("u_viewProj");
   m_cylinderUniforms.viewProj = m_cylinderShader->uniformHandle("u_viewProj");
 }
 }
 
 
 void Backend::cacheFogUniforms() {
 void Backend::cacheFogUniforms() {
-  if (!m_fogShader)
+  if (!m_fogShader) {
     return;
     return;
+  }
 
 
   m_fogUniforms.viewProj = m_fogShader->uniformHandle("u_viewProj");
   m_fogUniforms.viewProj = m_fogShader->uniformHandle("u_viewProj");
 }
 }
@@ -994,13 +1082,15 @@ void Backend::initializeCylinderPipeline() {
   shutdownCylinderPipeline();
   shutdownCylinderPipeline();
 
 
   Mesh *unit = getUnitCylinder();
   Mesh *unit = getUnitCylinder();
-  if (!unit)
+  if (!unit) {
     return;
     return;
+  }
 
 
   const auto &vertices = unit->getVertices();
   const auto &vertices = unit->getVertices();
   const auto &indices = unit->getIndices();
   const auto &indices = unit->getIndices();
-  if (vertices.empty() || indices.empty())
+  if (vertices.empty() || indices.empty()) {
     return;
     return;
+  }
 
 
   glGenVertexArrays(1, &m_cylinderVao);
   glGenVertexArrays(1, &m_cylinderVao);
   glBindVertexArray(m_cylinderVao);
   glBindVertexArray(m_cylinderVao);
@@ -1108,8 +1198,9 @@ void Backend::shutdownCylinderPipeline() {
 }
 }
 
 
 void Backend::uploadCylinderInstances(std::size_t count) {
 void Backend::uploadCylinderInstances(std::size_t count) {
-  if (count == 0)
+  if (count == 0) {
     return;
     return;
+  }
 
 
   initializeOpenGLFunctions();
   initializeOpenGLFunctions();
 
 
@@ -1126,8 +1217,9 @@ void Backend::uploadCylinderInstances(std::size_t count) {
     return;
     return;
   }
   }
 
 
-  if (!m_cylinderInstanceBuffer)
+  if (!m_cylinderInstanceBuffer) {
     return;
     return;
+  }
 
 
   glBindBuffer(GL_ARRAY_BUFFER, m_cylinderInstanceBuffer);
   glBindBuffer(GL_ARRAY_BUFFER, m_cylinderInstanceBuffer);
   if (count > m_cylinderInstanceCapacity) {
   if (count > m_cylinderInstanceCapacity) {
@@ -1145,8 +1237,9 @@ void Backend::uploadCylinderInstances(std::size_t count) {
 }
 }
 
 
 void Backend::drawCylinders(std::size_t count) {
 void Backend::drawCylinders(std::size_t count) {
-  if (!m_cylinderVao || m_cylinderIndexCount == 0 || count == 0)
+  if (!m_cylinderVao || m_cylinderIndexCount == 0 || count == 0) {
     return;
     return;
+  }
 
 
   initializeOpenGLFunctions();
   initializeOpenGLFunctions();
   glBindVertexArray(m_cylinderVao);
   glBindVertexArray(m_cylinderVao);
@@ -1253,8 +1346,9 @@ void Backend::shutdownFogPipeline() {
 }
 }
 
 
 void Backend::uploadFogInstances(std::size_t count) {
 void Backend::uploadFogInstances(std::size_t count) {
-  if (!m_fogInstanceBuffer || count == 0)
+  if (!m_fogInstanceBuffer || count == 0) {
     return;
     return;
+  }
 
 
   initializeOpenGLFunctions();
   initializeOpenGLFunctions();
   glBindBuffer(GL_ARRAY_BUFFER, m_fogInstanceBuffer);
   glBindBuffer(GL_ARRAY_BUFFER, m_fogInstanceBuffer);
@@ -1272,8 +1366,9 @@ void Backend::uploadFogInstances(std::size_t count) {
 }
 }
 
 
 void Backend::drawFog(std::size_t count) {
 void Backend::drawFog(std::size_t count) {
-  if (!m_fogVao || m_fogIndexCount == 0 || count == 0)
+  if (!m_fogVao || m_fogIndexCount == 0 || count == 0) {
     return;
     return;
+  }
 
 
   initializeOpenGLFunctions();
   initializeOpenGLFunctions();
   glBindVertexArray(m_fogVao);
   glBindVertexArray(m_fogVao);
@@ -1283,8 +1378,9 @@ void Backend::drawFog(std::size_t count) {
 }
 }
 
 
 void Backend::cacheGrassUniforms() {
 void Backend::cacheGrassUniforms() {
-  if (!m_grassShader)
+  if (!m_grassShader) {
     return;
     return;
+  }
 
 
   m_grassUniforms.viewProj = m_grassShader->uniformHandle("u_viewProj");
   m_grassUniforms.viewProj = m_grassShader->uniformHandle("u_viewProj");
   m_grassUniforms.time = m_grassShader->uniformHandle("u_time");
   m_grassUniforms.time = m_grassShader->uniformHandle("u_time");
@@ -1295,8 +1391,9 @@ void Backend::cacheGrassUniforms() {
 }
 }
 
 
 void Backend::cacheGroundUniforms() {
 void Backend::cacheGroundUniforms() {
-  if (!m_groundShader)
+  if (!m_groundShader) {
     return;
     return;
+  }
 
 
   m_groundUniforms.mvp = m_groundShader->uniformHandle("u_mvp");
   m_groundUniforms.mvp = m_groundShader->uniformHandle("u_mvp");
   m_groundUniforms.model = m_groundShader->uniformHandle("u_model");
   m_groundUniforms.model = m_groundShader->uniformHandle("u_model");
@@ -1323,8 +1420,9 @@ void Backend::cacheGroundUniforms() {
 }
 }
 
 
 void Backend::cacheTerrainUniforms() {
 void Backend::cacheTerrainUniforms() {
-  if (!m_terrainShader)
+  if (!m_terrainShader) {
     return;
     return;
+  }
 
 
   m_terrainUniforms.mvp = m_terrainShader->uniformHandle("u_mvp");
   m_terrainUniforms.mvp = m_terrainShader->uniformHandle("u_mvp");
   m_terrainUniforms.model = m_terrainShader->uniformHandle("u_model");
   m_terrainUniforms.model = m_terrainShader->uniformHandle("u_model");
@@ -1364,8 +1462,9 @@ void Backend::cacheTerrainUniforms() {
 }
 }
 
 
 void Backend::cacheRiverUniforms() {
 void Backend::cacheRiverUniforms() {
-  if (!m_riverShader)
+  if (!m_riverShader) {
     return;
     return;
+  }
 
 
   m_riverUniforms.model = m_riverShader->uniformHandle("model");
   m_riverUniforms.model = m_riverShader->uniformHandle("model");
   m_riverUniforms.view = m_riverShader->uniformHandle("view");
   m_riverUniforms.view = m_riverShader->uniformHandle("view");
@@ -1374,8 +1473,9 @@ void Backend::cacheRiverUniforms() {
 }
 }
 
 
 void Backend::cacheRiverbankUniforms() {
 void Backend::cacheRiverbankUniforms() {
-  if (!m_riverbankShader)
+  if (!m_riverbankShader) {
     return;
     return;
+  }
 
 
   m_riverbankUniforms.model = m_riverbankShader->uniformHandle("model");
   m_riverbankUniforms.model = m_riverbankShader->uniformHandle("model");
   m_riverbankUniforms.view = m_riverbankShader->uniformHandle("view");
   m_riverbankUniforms.view = m_riverbankShader->uniformHandle("view");
@@ -1385,8 +1485,9 @@ void Backend::cacheRiverbankUniforms() {
 }
 }
 
 
 void Backend::cacheBridgeUniforms() {
 void Backend::cacheBridgeUniforms() {
-  if (!m_bridgeShader)
+  if (!m_bridgeShader) {
     return;
     return;
+  }
 
 
   m_bridgeUniforms.mvp = m_bridgeShader->uniformHandle("u_mvp");
   m_bridgeUniforms.mvp = m_bridgeShader->uniformHandle("u_mvp");
   m_bridgeUniforms.model = m_bridgeShader->uniformHandle("u_model");
   m_bridgeUniforms.model = m_bridgeShader->uniformHandle("u_model");

+ 111 - 57
render/gl/camera.cpp

@@ -26,11 +26,13 @@ inline bool finite(float v) { return qIsFinite(v); }
 
 
 inline QVector3D safeNormalize(const QVector3D &v, const QVector3D &fallback,
 inline QVector3D safeNormalize(const QVector3D &v, const QVector3D &fallback,
                                float eps = kEps) {
                                float eps = kEps) {
-  if (!finite(v))
+  if (!finite(v)) {
     return fallback;
     return fallback;
+  }
   float len2 = v.lengthSquared();
   float len2 = v.lengthSquared();
-  if (len2 < eps)
+  if (len2 < eps) {
     return fallback;
     return fallback;
+  }
   return v / std::sqrt(len2);
   return v / std::sqrt(len2);
 }
 }
 
 
@@ -43,8 +45,9 @@ inline void orthonormalize(const QVector3D &frontIn, QVector3D &frontOut,
                     ? QVector3D(0, 0, 1)
                     ? QVector3D(0, 0, 1)
                     : worldUp;
                     : worldUp;
   QVector3D r = QVector3D::crossProduct(f, u);
   QVector3D r = QVector3D::crossProduct(f, u);
-  if (r.lengthSquared() < kEps)
+  if (r.lengthSquared() < kEps) {
     r = QVector3D(1, 0, 0);
     r = QVector3D(1, 0, 0);
+  }
   r = r.normalized();
   r = r.normalized();
   u = QVector3D::crossProduct(r, f).normalized();
   u = QVector3D::crossProduct(r, f).normalized();
 
 
@@ -80,8 +83,9 @@ inline float calculateDynamicMargin(float baseMargin, float cameraHeight,
 }
 }
 
 
 inline float smoothApproach(float current, float target, float smoothness) {
 inline float smoothApproach(float current, float target, float smoothness) {
-  if (std::abs(current - target) < kTiny)
+  if (std::abs(current - target) < kTiny) {
     return target;
     return target;
+  }
 
 
   return current +
   return current +
          (target - current) * std::clamp(1.0f - smoothness, 0.01f, 0.99f);
          (target - current) * std::clamp(1.0f - smoothness, 0.01f, 0.99f);
@@ -92,8 +96,9 @@ inline float smoothApproach(float current, float target, float smoothness) {
 Camera::Camera() { updateVectors(); }
 Camera::Camera() { updateVectors(); }
 
 
 void Camera::setPosition(const QVector3D &position) {
 void Camera::setPosition(const QVector3D &position) {
-  if (!finite(position))
+  if (!finite(position)) {
     return;
     return;
+  }
   m_position = position;
   m_position = position;
   applySoftBoundaries();
   applySoftBoundaries();
 
 
@@ -102,8 +107,9 @@ void Camera::setPosition(const QVector3D &position) {
 }
 }
 
 
 void Camera::setTarget(const QVector3D &target) {
 void Camera::setTarget(const QVector3D &target) {
-  if (!finite(target))
+  if (!finite(target)) {
     return;
     return;
+  }
   m_target = target;
   m_target = target;
   applySoftBoundaries();
   applySoftBoundaries();
 
 
@@ -117,19 +123,22 @@ void Camera::setTarget(const QVector3D &target) {
 }
 }
 
 
 void Camera::setUp(const QVector3D &up) {
 void Camera::setUp(const QVector3D &up) {
-  if (!finite(up))
+  if (!finite(up)) {
     return;
     return;
+  }
   QVector3D upN = up;
   QVector3D upN = up;
-  if (upN.lengthSquared() < kEps)
+  if (upN.lengthSquared() < kEps) {
     upN = QVector3D(0, 1, 0);
     upN = QVector3D(0, 1, 0);
+  }
 
 
   orthonormalize(m_target - m_position, m_front, m_right, m_up);
   orthonormalize(m_target - m_position, m_front, m_right, m_up);
 }
 }
 
 
 void Camera::lookAt(const QVector3D &position, const QVector3D &target,
 void Camera::lookAt(const QVector3D &position, const QVector3D &target,
                     const QVector3D &up) {
                     const QVector3D &up) {
-  if (!finite(position) || !finite(target) || !finite(up))
+  if (!finite(position) || !finite(target) || !finite(up)) {
     return;
     return;
+  }
   m_position = position;
   m_position = position;
   m_target = (position == target) ? position + QVector3D(0, 0, -1) : target;
   m_target = (position == target) ? position + QVector3D(0, 0, -1) : target;
 
 
@@ -143,8 +152,9 @@ void Camera::lookAt(const QVector3D &position, const QVector3D &target,
 void Camera::setPerspective(float fov, float aspect, float nearPlane,
 void Camera::setPerspective(float fov, float aspect, float nearPlane,
                             float farPlane) {
                             float farPlane) {
   if (!finite(fov) || !finite(aspect) || !finite(nearPlane) ||
   if (!finite(fov) || !finite(aspect) || !finite(nearPlane) ||
-      !finite(farPlane))
+      !finite(farPlane)) {
     return;
     return;
+  }
 
 
   m_isPerspective = true;
   m_isPerspective = true;
 
 
@@ -157,8 +167,9 @@ void Camera::setPerspective(float fov, float aspect, float nearPlane,
 void Camera::setOrthographic(float left, float right, float bottom, float top,
 void Camera::setOrthographic(float left, float right, float bottom, float top,
                              float nearPlane, float farPlane) {
                              float nearPlane, float farPlane) {
   if (!finite(left) || !finite(right) || !finite(bottom) || !finite(top) ||
   if (!finite(left) || !finite(right) || !finite(bottom) || !finite(top) ||
-      !finite(nearPlane) || !finite(farPlane))
+      !finite(nearPlane) || !finite(farPlane)) {
     return;
     return;
+  }
 
 
   m_isPerspective = false;
   m_isPerspective = false;
   clampOrthoBox(left, right, bottom, top);
   clampOrthoBox(left, right, bottom, top);
@@ -171,40 +182,46 @@ void Camera::setOrthographic(float left, float right, float bottom, float top,
 }
 }
 
 
 void Camera::moveForward(float distance) {
 void Camera::moveForward(float distance) {
-  if (!finite(distance))
+  if (!finite(distance)) {
     return;
     return;
+  }
   m_position += m_front * distance;
   m_position += m_front * distance;
   m_target = m_position + m_front;
   m_target = m_position + m_front;
   applySoftBoundaries();
   applySoftBoundaries();
 }
 }
 
 
 void Camera::moveRight(float distance) {
 void Camera::moveRight(float distance) {
-  if (!finite(distance))
+  if (!finite(distance)) {
     return;
     return;
+  }
   m_position += m_right * distance;
   m_position += m_right * distance;
   m_target = m_position + m_front;
   m_target = m_position + m_front;
   applySoftBoundaries();
   applySoftBoundaries();
 }
 }
 
 
 void Camera::moveUp(float distance) {
 void Camera::moveUp(float distance) {
-  if (!finite(distance))
+  if (!finite(distance)) {
     return;
     return;
+  }
   m_position += QVector3D(0, 1, 0) * distance;
   m_position += QVector3D(0, 1, 0) * distance;
   m_target = m_position + m_front;
   m_target = m_position + m_front;
   applySoftBoundaries();
   applySoftBoundaries();
 }
 }
 
 
 void Camera::zoom(float delta) {
 void Camera::zoom(float delta) {
-  if (!finite(delta))
+  if (!finite(delta)) {
     return;
     return;
+  }
   if (m_isPerspective) {
   if (m_isPerspective) {
     m_fov = qBound(kMinFov, m_fov - delta, kMaxFov);
     m_fov = qBound(kMinFov, m_fov - delta, kMaxFov);
   } else {
   } else {
     float scale = 1.0f + delta * 0.1f;
     float scale = 1.0f + delta * 0.1f;
-    if (!finite(scale) || scale <= 0.05f)
+    if (!finite(scale) || scale <= 0.05f) {
       scale = 0.05f;
       scale = 0.05f;
-    if (scale > 20.0f)
+    }
+    if (scale > 20.0f) {
       scale = 20.0f;
       scale = 20.0f;
+    }
     m_orthoLeft *= scale;
     m_orthoLeft *= scale;
     m_orthoRight *= scale;
     m_orthoRight *= scale;
     m_orthoBottom *= scale;
     m_orthoBottom *= scale;
@@ -214,17 +231,20 @@ void Camera::zoom(float delta) {
 }
 }
 
 
 void Camera::zoomDistance(float delta) {
 void Camera::zoomDistance(float delta) {
-  if (!finite(delta))
+  if (!finite(delta)) {
     return;
     return;
+  }
 
 
   QVector3D offset = m_position - m_target;
   QVector3D offset = m_position - m_target;
   float r = offset.length();
   float r = offset.length();
-  if (r < kTiny)
+  if (r < kTiny) {
     r = kTiny;
     r = kTiny;
+  }
 
 
   float factor = 1.0f - delta * 0.15f;
   float factor = 1.0f - delta * 0.15f;
-  if (!finite(factor))
+  if (!finite(factor)) {
     factor = 1.0f;
     factor = 1.0f;
+  }
   factor = std::clamp(factor, 0.1f, 10.0f);
   factor = std::clamp(factor, 0.1f, 10.0f);
 
 
   float newR = std::clamp(r * factor, kMinDist, kMaxDist);
   float newR = std::clamp(r * factor, kMinDist, kMaxDist);
@@ -242,18 +262,21 @@ void Camera::zoomDistance(float delta) {
 void Camera::rotate(float yaw, float pitch) { orbit(yaw, pitch); }
 void Camera::rotate(float yaw, float pitch) { orbit(yaw, pitch); }
 
 
 void Camera::pan(float rightDist, float forwardDist) {
 void Camera::pan(float rightDist, float forwardDist) {
-  if (!finite(rightDist) || !finite(forwardDist))
+  if (!finite(rightDist) || !finite(forwardDist)) {
     return;
     return;
+  }
 
 
   QVector3D right = m_right;
   QVector3D right = m_right;
   QVector3D front = m_front;
   QVector3D front = m_front;
   front.setY(0.0f);
   front.setY(0.0f);
-  if (front.lengthSquared() > 0)
+  if (front.lengthSquared() > 0) {
     front.normalize();
     front.normalize();
+  }
 
 
   QVector3D delta = right * rightDist + front * forwardDist;
   QVector3D delta = right * rightDist + front * forwardDist;
-  if (!finite(delta))
+  if (!finite(delta)) {
     return;
     return;
+  }
 
 
   m_position += delta;
   m_position += delta;
   m_target += delta;
   m_target += delta;
@@ -262,22 +285,25 @@ void Camera::pan(float rightDist, float forwardDist) {
 }
 }
 
 
 void Camera::elevate(float dy) {
 void Camera::elevate(float dy) {
-  if (!finite(dy))
+  if (!finite(dy)) {
     return;
     return;
+  }
   m_position.setY(m_position.y() + dy);
   m_position.setY(m_position.y() + dy);
   applySoftBoundaries();
   applySoftBoundaries();
 }
 }
 
 
 void Camera::yaw(float degrees) {
 void Camera::yaw(float degrees) {
-  if (!finite(degrees))
+  if (!finite(degrees)) {
     return;
     return;
+  }
 
 
   orbit(degrees, 0.0f);
   orbit(degrees, 0.0f);
 }
 }
 
 
 void Camera::orbit(float yawDeg, float pitchDeg) {
 void Camera::orbit(float yawDeg, float pitchDeg) {
-  if (!finite(yawDeg) || !finite(pitchDeg))
+  if (!finite(yawDeg) || !finite(pitchDeg)) {
     return;
     return;
+  }
 
 
   QVector3D offset = m_position - m_target;
   QVector3D offset = m_position - m_target;
   float curYaw = 0.f, curPitch = 0.f;
   float curYaw = 0.f, curPitch = 0.f;
@@ -293,10 +319,12 @@ void Camera::orbit(float yawDeg, float pitchDeg) {
 }
 }
 
 
 void Camera::update(float dt) {
 void Camera::update(float dt) {
-  if (!m_orbitPending)
+  if (!m_orbitPending) {
     return;
     return;
-  if (!finite(dt))
+  }
+  if (!finite(dt)) {
     return;
     return;
+  }
 
 
   m_orbitTime += std::max(0.0f, dt);
   m_orbitTime += std::max(0.0f, dt);
   float t = (m_orbitDuration <= 0.0f)
   float t = (m_orbitDuration <= 0.0f)
@@ -311,8 +339,9 @@ void Camera::update(float dt) {
 
 
   QVector3D offset = m_position - m_target;
   QVector3D offset = m_position - m_target;
   float r = offset.length();
   float r = offset.length();
-  if (r < kTiny)
+  if (r < kTiny) {
     r = kTiny;
     r = kTiny;
+  }
 
 
   float yawRad = qDegreesToRadians(newYaw);
   float yawRad = qDegreesToRadians(newYaw);
   float pitchRad = qDegreesToRadians(newPitch);
   float pitchRad = qDegreesToRadians(newPitch);
@@ -333,39 +362,46 @@ void Camera::update(float dt) {
 
 
 bool Camera::screenToGround(qreal sx, qreal sy, qreal screenW, qreal screenH,
 bool Camera::screenToGround(qreal sx, qreal sy, qreal screenW, qreal screenH,
                             QVector3D &outWorld) const {
                             QVector3D &outWorld) const {
-  if (screenW <= 0 || screenH <= 0)
+  if (screenW <= 0 || screenH <= 0) {
     return false;
     return false;
-  if (!qIsFinite(sx) || !qIsFinite(sy))
+  }
+  if (!qIsFinite(sx) || !qIsFinite(sy)) {
     return false;
     return false;
+  }
 
 
   double x = (2.0 * sx / screenW) - 1.0;
   double x = (2.0 * sx / screenW) - 1.0;
   double y = 1.0 - (2.0 * sy / screenH);
   double y = 1.0 - (2.0 * sy / screenH);
 
 
   bool ok = false;
   bool ok = false;
   QMatrix4x4 invVP = (getProjectionMatrix() * getViewMatrix()).inverted(&ok);
   QMatrix4x4 invVP = (getProjectionMatrix() * getViewMatrix()).inverted(&ok);
-  if (!ok)
+  if (!ok) {
     return false;
     return false;
+  }
 
 
   QVector4D nearClip(float(x), float(y), 0.0f, 1.0f);
   QVector4D nearClip(float(x), float(y), 0.0f, 1.0f);
   QVector4D farClip(float(x), float(y), 1.0f, 1.0f);
   QVector4D farClip(float(x), float(y), 1.0f, 1.0f);
   QVector4D nearWorld4 = invVP * nearClip;
   QVector4D nearWorld4 = invVP * nearClip;
   QVector4D farWorld4 = invVP * farClip;
   QVector4D farWorld4 = invVP * farClip;
 
 
-  if (std::abs(nearWorld4.w()) < kEps || std::abs(farWorld4.w()) < kEps)
+  if (std::abs(nearWorld4.w()) < kEps || std::abs(farWorld4.w()) < kEps) {
     return false;
     return false;
+  }
 
 
   QVector3D rayOrigin = (nearWorld4 / nearWorld4.w()).toVector3D();
   QVector3D rayOrigin = (nearWorld4 / nearWorld4.w()).toVector3D();
   QVector3D rayEnd = (farWorld4 / farWorld4.w()).toVector3D();
   QVector3D rayEnd = (farWorld4 / farWorld4.w()).toVector3D();
-  if (!finite(rayOrigin) || !finite(rayEnd))
+  if (!finite(rayOrigin) || !finite(rayEnd)) {
     return false;
     return false;
+  }
 
 
   QVector3D rayDir = safeNormalize(rayEnd - rayOrigin, QVector3D(0, -1, 0));
   QVector3D rayDir = safeNormalize(rayEnd - rayOrigin, QVector3D(0, -1, 0));
-  if (std::abs(rayDir.y()) < kEps)
+  if (std::abs(rayDir.y()) < kEps) {
     return false;
     return false;
+  }
 
 
   float t = (m_groundY - rayOrigin.y()) / rayDir.y();
   float t = (m_groundY - rayOrigin.y()) / rayDir.y();
-  if (!finite(t) || t < 0.0f)
+  if (!finite(t) || t < 0.0f) {
     return false;
     return false;
+  }
 
 
   outWorld = rayOrigin + rayDir * t;
   outWorld = rayOrigin + rayDir * t;
   return finite(outWorld);
   return finite(outWorld);
@@ -373,21 +409,26 @@ bool Camera::screenToGround(qreal sx, qreal sy, qreal screenW, qreal screenH,
 
 
 bool Camera::worldToScreen(const QVector3D &world, qreal screenW, qreal screenH,
 bool Camera::worldToScreen(const QVector3D &world, qreal screenW, qreal screenH,
                            QPointF &outScreen) const {
                            QPointF &outScreen) const {
-  if (screenW <= 0 || screenH <= 0)
+  if (screenW <= 0 || screenH <= 0) {
     return false;
     return false;
-  if (!finite(world))
+  }
+  if (!finite(world)) {
     return false;
     return false;
+  }
 
 
   QVector4D clip =
   QVector4D clip =
       getProjectionMatrix() * getViewMatrix() * QVector4D(world, 1.0f);
       getProjectionMatrix() * getViewMatrix() * QVector4D(world, 1.0f);
-  if (std::abs(clip.w()) < kEps)
+  if (std::abs(clip.w()) < kEps) {
     return false;
     return false;
+  }
 
 
   QVector3D ndc = (clip / clip.w()).toVector3D();
   QVector3D ndc = (clip / clip.w()).toVector3D();
-  if (!qIsFinite(ndc.x()) || !qIsFinite(ndc.y()) || !qIsFinite(ndc.z()))
+  if (!qIsFinite(ndc.x()) || !qIsFinite(ndc.y()) || !qIsFinite(ndc.z())) {
     return false;
     return false;
-  if (ndc.z() < -1.0f || ndc.z() > 1.0f)
+  }
+  if (ndc.z() < -1.0f || ndc.z() > 1.0f) {
     return false;
     return false;
+  }
 
 
   qreal sx = (ndc.x() * 0.5 + 0.5) * screenW;
   qreal sx = (ndc.x() * 0.5 + 0.5) * screenW;
   qreal sy = (1.0 - (ndc.y() * 0.5 + 0.5)) * screenH;
   qreal sy = (1.0 - (ndc.y() * 0.5 + 0.5)) * screenH;
@@ -396,10 +437,12 @@ bool Camera::worldToScreen(const QVector3D &world, qreal screenW, qreal screenH,
 }
 }
 
 
 void Camera::updateFollow(const QVector3D &targetCenter) {
 void Camera::updateFollow(const QVector3D &targetCenter) {
-  if (!m_followEnabled)
+  if (!m_followEnabled) {
     return;
     return;
-  if (!finite(targetCenter))
+  }
+  if (!finite(targetCenter)) {
     return;
     return;
+  }
 
 
   if (m_followOffset.lengthSquared() < 1e-5f) {
   if (m_followOffset.lengthSquared() < 1e-5f) {
     m_followOffset = m_position - m_target;
     m_followOffset = m_position - m_target;
@@ -411,8 +454,9 @@ void Camera::updateFollow(const QVector3D &targetCenter) {
           : (m_position +
           : (m_position +
              (desiredPos - m_position) * std::clamp(m_followLerp, 0.0f, 1.0f));
              (desiredPos - m_position) * std::clamp(m_followLerp, 0.0f, 1.0f));
 
 
-  if (!finite(newPos))
+  if (!finite(newPos)) {
     return;
     return;
+  }
 
 
   m_target = targetCenter;
   m_target = targetCenter;
   m_position = newPos;
   m_position = newPos;
@@ -424,8 +468,10 @@ void Camera::updateFollow(const QVector3D &targetCenter) {
 
 
 void Camera::setRTSView(const QVector3D &center, float distance, float angle,
 void Camera::setRTSView(const QVector3D &center, float distance, float angle,
                         float yawDeg) {
                         float yawDeg) {
-  if (!finite(center) || !finite(distance) || !finite(angle) || !finite(yawDeg))
+  if (!finite(center) || !finite(distance) || !finite(angle) ||
+      !finite(yawDeg)) {
     return;
     return;
+  }
 
 
   m_target = center;
   m_target = center;
 
 
@@ -448,8 +494,9 @@ void Camera::setRTSView(const QVector3D &center, float distance, float angle,
 }
 }
 
 
 void Camera::setTopDownView(const QVector3D &center, float distance) {
 void Camera::setTopDownView(const QVector3D &center, float distance) {
-  if (!finite(center) || !finite(distance))
+  if (!finite(center) || !finite(distance)) {
     return;
     return;
+  }
 
 
   m_target = center;
   m_target = center;
   m_position = center + QVector3D(0, std::max(distance, 0.01f), 0);
   m_position = center + QVector3D(0, std::max(distance, 0.01f), 0);
@@ -490,8 +537,9 @@ float Camera::getDistance() const { return (m_position - m_target).length(); }
 float Camera::getPitchDeg() const {
 float Camera::getPitchDeg() const {
   QVector3D off = m_position - m_target;
   QVector3D off = m_position - m_target;
   QVector3D dir = -off;
   QVector3D dir = -off;
-  if (dir.lengthSquared() < 1e-6f)
+  if (dir.lengthSquared() < 1e-6f) {
     return 0.0f;
     return 0.0f;
+  }
   float lenXZ = std::sqrt(dir.x() * dir.x() + dir.z() * dir.z());
   float lenXZ = std::sqrt(dir.x() * dir.x() + dir.z() * dir.z());
   float pitchRad = std::atan2(dir.y(), lenXZ);
   float pitchRad = std::atan2(dir.y(), lenXZ);
   return qRadiansToDegrees(pitchRad);
   return qRadiansToDegrees(pitchRad);
@@ -555,25 +603,29 @@ void Camera::applySoftBoundaries(bool isPanning) {
   QVector3D positionAdjustment(0, 0, 0);
   QVector3D positionAdjustment(0, 0, 0);
   QVector3D targetAdjustment(0, 0, 0);
   QVector3D targetAdjustment(0, 0, 0);
 
 
-  if (m_position.x() < extMinX)
+  if (m_position.x() < extMinX) {
     positionAdjustment.setX(extMinX - m_position.x());
     positionAdjustment.setX(extMinX - m_position.x());
-  else if (m_position.x() > extMaxX)
+  } else if (m_position.x() > extMaxX) {
     positionAdjustment.setX(extMaxX - m_position.x());
     positionAdjustment.setX(extMaxX - m_position.x());
+  }
 
 
-  if (m_position.z() < extMinZ)
+  if (m_position.z() < extMinZ) {
     positionAdjustment.setZ(extMinZ - m_position.z());
     positionAdjustment.setZ(extMinZ - m_position.z());
-  else if (m_position.z() > extMaxZ)
+  } else if (m_position.z() > extMaxZ) {
     positionAdjustment.setZ(extMaxZ - m_position.z());
     positionAdjustment.setZ(extMaxZ - m_position.z());
+  }
 
 
-  if (m_target.x() < mapMinX)
+  if (m_target.x() < mapMinX) {
     targetAdjustment.setX(mapMinX - m_target.x());
     targetAdjustment.setX(mapMinX - m_target.x());
-  else if (m_target.x() > mapMaxX)
+  } else if (m_target.x() > mapMaxX) {
     targetAdjustment.setX(mapMaxX - m_target.x());
     targetAdjustment.setX(mapMaxX - m_target.x());
+  }
 
 
-  if (m_target.z() < mapMinZ)
+  if (m_target.z() < mapMinZ) {
     targetAdjustment.setZ(mapMinZ - m_target.z());
     targetAdjustment.setZ(mapMinZ - m_target.z());
-  else if (m_target.z() > mapMaxZ)
+  } else if (m_target.z() > mapMaxZ) {
     targetAdjustment.setZ(mapMaxZ - m_target.z());
     targetAdjustment.setZ(mapMaxZ - m_target.z());
+  }
 
 
   if (isPanning) {
   if (isPanning) {
 
 
@@ -635,8 +687,9 @@ bool Camera::isInFrustum(const QVector3D &center, float radius) const {
 
 
   float m[16];
   float m[16];
   const float *data = vp.constData();
   const float *data = vp.constData();
-  for (int i = 0; i < 16; ++i)
+  for (int i = 0; i < 16; ++i) {
     m[i] = data[i];
     m[i] = data[i];
+  }
 
 
   QVector3D leftN(m[3] + m[0], m[7] + m[4], m[11] + m[8]);
   QVector3D leftN(m[3] + m[0], m[7] + m[4], m[11] + m[8]);
   float leftD = m[15] + m[12];
   float leftD = m[15] + m[12];
@@ -658,8 +711,9 @@ bool Camera::isInFrustum(const QVector3D &center, float radius) const {
 
 
   auto testPlane = [&center, radius](const QVector3D &n, float d) -> bool {
   auto testPlane = [&center, radius](const QVector3D &n, float d) -> bool {
     float len = n.length();
     float len = n.length();
-    if (len < 1e-6f)
+    if (len < 1e-6f) {
       return true;
       return true;
+    }
     float dist = QVector3D::dotProduct(center, n) + d;
     float dist = QVector3D::dotProduct(center, n) + d;
     return dist >= -radius * len;
     return dist >= -radius * len;
   };
   };

+ 4 - 2
render/gl/primitives.cpp

@@ -294,8 +294,9 @@ Mesh *createUnitTorsoMesh(int radialSegments, int heightSegments) {
   auto sampleAxes = [&](float t) -> Axes {
   auto sampleAxes = [&](float t) -> Axes {
     t = clampf(t, 0.0f, 1.0f);
     t = clampf(t, 0.0f, 1.0f);
     int i = 0;
     int i = 0;
-    while (i + 1 < KEY_COUNT && t > keys[i + 1].t)
+    while (i + 1 < KEY_COUNT && t > keys[i + 1].t) {
       ++i;
       ++i;
+    }
     int i0 = i > 0 ? i - 1 : 0;
     int i0 = i > 0 ? i - 1 : 0;
     int i1 = i;
     int i1 = i;
     int i2 = (i + 1 < KEY_COUNT) ? i + 1 : KEY_COUNT - 1;
     int i2 = (i + 1 < KEY_COUNT) ? i + 1 : KEY_COUNT - 1;
@@ -396,8 +397,9 @@ Mesh *createUnitTorsoMesh(int radialSegments, int heightSegments) {
       QVector3D dv = pv - p;
       QVector3D dv = pv - p;
 
 
       QVector3D n = QVector3D::crossProduct(du, dv);
       QVector3D n = QVector3D::crossProduct(du, dv);
-      if (n.lengthSquared() > 0.0f)
+      if (n.lengthSquared() > 0.0f) {
         n.normalize();
         n.normalize();
+      }
 
 
       v.push_back({{p.x(), p.y(), p.z()}, {n.x(), n.y(), n.z()}, {u, vCoord}});
       v.push_back({{p.x(), p.y(), p.z()}, {n.x(), n.y(), n.z()}, {u, vCoord}});
     }
     }

+ 4 - 2
render/gl/shader.cpp

@@ -27,15 +27,17 @@ bool Shader::loadFromFiles(const QString &vertexPath,
 
 
   if (!vertexFile.open(QIODevice::ReadOnly)) {
   if (!vertexFile.open(QIODevice::ReadOnly)) {
     qWarning() << "Failed to open vertex shader file:" << resolvedVert;
     qWarning() << "Failed to open vertex shader file:" << resolvedVert;
-    if (resolvedVert != vertexPath)
+    if (resolvedVert != vertexPath) {
       qWarning() << "  Requested path:" << vertexPath;
       qWarning() << "  Requested path:" << vertexPath;
+    }
     return false;
     return false;
   }
   }
 
 
   if (!fragmentFile.open(QIODevice::ReadOnly)) {
   if (!fragmentFile.open(QIODevice::ReadOnly)) {
     qWarning() << "Failed to open fragment shader file:" << resolvedFrag;
     qWarning() << "Failed to open fragment shader file:" << resolvedFrag;
-    if (resolvedFrag != fragmentPath)
+    if (resolvedFrag != fragmentPath) {
       qWarning() << "  Requested path:" << fragmentPath;
       qWarning() << "  Requested path:" << fragmentPath;
+    }
     vertexFile.close();
     vertexFile.close();
     return false;
     return false;
   }
   }

+ 34 - 18
render/ground/biome_renderer.cpp

@@ -216,24 +216,28 @@ void BiomeRenderer::generateGrassInstances() {
     int normalIdx = iz * m_width + ix;
     int normalIdx = iz * m_width + ix;
 
 
     if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::Mountain ||
     if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::Mountain ||
-        m_terrainTypes[normalIdx] == Game::Map::TerrainType::Hill)
+        m_terrainTypes[normalIdx] == Game::Map::TerrainType::Hill) {
       return false;
       return false;
+    }
 
 
-    if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::River)
+    if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::River) {
       return false;
       return false;
+    }
 
 
     constexpr int kRiverMargin = 1;
     constexpr int kRiverMargin = 1;
     int nearRiverCount = 0;
     int nearRiverCount = 0;
     for (int dz = -kRiverMargin; dz <= kRiverMargin; ++dz) {
     for (int dz = -kRiverMargin; dz <= kRiverMargin; ++dz) {
       for (int dx = -kRiverMargin; dx <= kRiverMargin; ++dx) {
       for (int dx = -kRiverMargin; dx <= kRiverMargin; ++dx) {
-        if (dx == 0 && dz == 0)
+        if (dx == 0 && dz == 0) {
           continue;
           continue;
+        }
         int nx = ix + dx;
         int nx = ix + dx;
         int nz = iz + dz;
         int nz = iz + dz;
         if (nx >= 0 && nx < m_width && nz >= 0 && nz < m_height) {
         if (nx >= 0 && nx < m_width && nz >= 0 && nz < m_height) {
           int nIdx = nz * m_width + nx;
           int nIdx = nz * m_width + nx;
-          if (m_terrainTypes[nIdx] == Game::Map::TerrainType::River)
+          if (m_terrainTypes[nIdx] == Game::Map::TerrainType::River) {
             nearRiverCount++;
             nearRiverCount++;
+          }
         }
         }
       }
       }
     }
     }
@@ -241,14 +245,16 @@ void BiomeRenderer::generateGrassInstances() {
     if (nearRiverCount > 0) {
     if (nearRiverCount > 0) {
 
 
       float riverbankDensity = 0.15f;
       float riverbankDensity = 0.15f;
-      if (rand01(state) > riverbankDensity)
+      if (rand01(state) > riverbankDensity) {
         return false;
         return false;
+      }
     }
     }
 
 
     QVector3D normal = normals[normalIdx];
     QVector3D normal = normals[normalIdx];
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
-    if (slope > 0.92f)
+    if (slope > 0.92f) {
       return false;
       return false;
+    }
 
 
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
@@ -356,14 +362,16 @@ void BiomeRenderer::generateGrassInstances() {
         }
         }
       }
       }
 
 
-      if (sampleCount == 0)
+      if (sampleCount == 0) {
         continue;
         continue;
+      }
 
 
       const float usableCoverage =
       const float usableCoverage =
           sampleCount > 0 ? float(flatCount + hillCount) / float(sampleCount)
           sampleCount > 0 ? float(flatCount + hillCount) / float(sampleCount)
                           : 0.0f;
                           : 0.0f;
-      if (usableCoverage < 0.05f)
+      if (usableCoverage < 0.05f) {
         continue;
         continue;
+      }
 
 
       bool isPrimarilyFlat = flatCount >= hillCount;
       bool isPrimarilyFlat = flatCount >= hillCount;
 
 
@@ -379,8 +387,9 @@ void BiomeRenderer::generateGrassInstances() {
                              slopePenalty * typeBias * usableCoverage);
                              slopePenalty * typeBias * usableCoverage);
       int clusterCount = static_cast<int>(std::floor(expectedClusters));
       int clusterCount = static_cast<int>(std::floor(expectedClusters));
       float frac = expectedClusters - float(clusterCount);
       float frac = expectedClusters - float(clusterCount);
-      if (rand01(state) < frac)
+      if (rand01(state) < frac) {
         clusterCount += 1;
         clusterCount += 1;
+      }
 
 
       if (clusterCount > 0) {
       if (clusterCount > 0) {
         float chunkSpanX = float(chunkMaxX - chunkX + 1);
         float chunkSpanX = float(chunkMaxX - chunkX + 1);
@@ -398,13 +407,15 @@ void BiomeRenderer::generateGrassInstances() {
             int cz = std::clamp(int(std::round(candidateGZ)), 0, m_height - 1);
             int cz = std::clamp(int(std::round(candidateGZ)), 0, m_height - 1);
             int centerIdx = cz * m_width + cx;
             int centerIdx = cz * m_width + cx;
             if (m_terrainTypes[centerIdx] == Game::Map::TerrainType::Mountain ||
             if (m_terrainTypes[centerIdx] == Game::Map::TerrainType::Mountain ||
-                m_terrainTypes[centerIdx] == Game::Map::TerrainType::River)
+                m_terrainTypes[centerIdx] == Game::Map::TerrainType::River) {
               continue;
               continue;
+            }
 
 
             QVector3D centerNormal = normals[centerIdx];
             QVector3D centerNormal = normals[centerIdx];
             float centerSlope = 1.0f - std::clamp(centerNormal.y(), 0.0f, 1.0f);
             float centerSlope = 1.0f - std::clamp(centerNormal.y(), 0.0f, 1.0f);
-            if (centerSlope > 0.92f)
+            if (centerSlope > 0.92f) {
               continue;
               continue;
+            }
 
 
             return QVector2D(candidateGX, candidateGZ);
             return QVector2D(candidateGX, candidateGZ);
           }
           }
@@ -413,8 +424,9 @@ void BiomeRenderer::generateGrassInstances() {
 
 
         for (int cluster = 0; cluster < clusterCount; ++cluster) {
         for (int cluster = 0; cluster < clusterCount; ++cluster) {
           auto center = pickClusterCenter(state);
           auto center = pickClusterCenter(state);
-          if (!center)
+          if (!center) {
             continue;
             continue;
+          }
 
 
           float centerGX = center->x();
           float centerGX = center->x();
           float centerGZ = center->y();
           float centerGZ = center->y();
@@ -446,20 +458,23 @@ void BiomeRenderer::generateGrassInstances() {
 
 
         if (m_terrainTypes[idx] == Game::Map::TerrainType::Mountain ||
         if (m_terrainTypes[idx] == Game::Map::TerrainType::Mountain ||
             m_terrainTypes[idx] == Game::Map::TerrainType::Hill ||
             m_terrainTypes[idx] == Game::Map::TerrainType::Hill ||
-            m_terrainTypes[idx] == Game::Map::TerrainType::River)
+            m_terrainTypes[idx] == Game::Map::TerrainType::River) {
           continue;
           continue;
+        }
 
 
         QVector3D normal = normals[idx];
         QVector3D normal = normals[idx];
         float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
         float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
-        if (slope > 0.95f)
+        if (slope > 0.95f) {
           continue;
           continue;
+        }
 
 
         uint32_t state = hashCoords(
         uint32_t state = hashCoords(
             x, z, m_noiseSeed ^ 0x51bda7u ^ static_cast<uint32_t>(idx));
             x, z, m_noiseSeed ^ 0x51bda7u ^ static_cast<uint32_t>(idx));
         int baseCount = static_cast<int>(std::floor(backgroundDensity));
         int baseCount = static_cast<int>(std::floor(backgroundDensity));
         float frac = backgroundDensity - float(baseCount);
         float frac = backgroundDensity - float(baseCount);
-        if (rand01(state) < frac)
+        if (rand01(state) < frac) {
           baseCount += 1;
           baseCount += 1;
+        }
 
 
         for (int i = 0; i < baseCount; ++i) {
         for (int i = 0; i < baseCount; ++i) {
           float gx = float(x) + rand01(state);
           float gx = float(x) + rand01(state);
@@ -477,12 +492,13 @@ void BiomeRenderer::generateGrassInstances() {
   int debugHillCount = 0;
   int debugHillCount = 0;
   int debugMountainCount = 0;
   int debugMountainCount = 0;
   for (const auto &type : m_terrainTypes) {
   for (const auto &type : m_terrainTypes) {
-    if (type == Game::Map::TerrainType::Flat)
+    if (type == Game::Map::TerrainType::Flat) {
       debugFlatCount++;
       debugFlatCount++;
-    else if (type == Game::Map::TerrainType::Hill)
+    } else if (type == Game::Map::TerrainType::Hill) {
       debugHillCount++;
       debugHillCount++;
-    else if (type == Game::Map::TerrainType::Mountain)
+    } else if (type == Game::Map::TerrainType::Mountain) {
       debugMountainCount++;
       debugMountainCount++;
+    }
   }
   }
 }
 }
 
 

+ 2 - 1
render/ground/bridge_renderer.cpp

@@ -226,8 +226,9 @@ void BridgeRenderer::submit(Renderer &renderer, ResourceManager *resources) {
 
 
   size_t meshIndex = 0;
   size_t meshIndex = 0;
   for (const auto &bridge : m_bridges) {
   for (const auto &bridge : m_bridges) {
-    if (meshIndex >= m_meshes.size())
+    if (meshIndex >= m_meshes.size()) {
       break;
       break;
+    }
 
 
     auto *mesh = m_meshes[meshIndex].get();
     auto *mesh = m_meshes[meshIndex].get();
     ++meshIndex;
     ++meshIndex;

+ 6 - 3
render/ground/firecamp_renderer.cpp

@@ -290,8 +290,9 @@ void FireCampRenderer::generateFireCampInstances() {
     QVector3D normal = normals[normalIdx];
     QVector3D normal = normals[normalIdx];
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
 
 
-    if (slope > 0.3f)
+    if (slope > 0.3f) {
       return false;
       return false;
+    }
 
 
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
@@ -323,8 +324,9 @@ void FireCampRenderer::generateFireCampInstances() {
 
 
       QVector3D normal = normals[idx];
       QVector3D normal = normals[idx];
       float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
       float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
-      if (slope > 0.3f)
+      if (slope > 0.3f) {
         continue;
         continue;
+      }
 
 
       uint32_t state = hashCoords(
       uint32_t state = hashCoords(
           x, z, m_noiseSeed ^ 0xF12ECA3Fu ^ static_cast<uint32_t>(idx));
           x, z, m_noiseSeed ^ 0xF12ECA3Fu ^ static_cast<uint32_t>(idx));
@@ -335,8 +337,9 @@ void FireCampRenderer::generateFireCampInstances() {
       float clusterNoise =
       float clusterNoise =
           valueNoise(worldX * 0.02f, worldZ * 0.02f, m_noiseSeed ^ 0xCA3F12E0u);
           valueNoise(worldX * 0.02f, worldZ * 0.02f, m_noiseSeed ^ 0xCA3F12E0u);
 
 
-      if (clusterNoise < 0.4f)
+      if (clusterNoise < 0.4f) {
         continue;
         continue;
+      }
 
 
       float densityMult = 1.0f;
       float densityMult = 1.0f;
       if (m_terrainTypes[idx] == Game::Map::TerrainType::Hill) {
       if (m_terrainTypes[idx] == Game::Map::TerrainType::Hill) {

+ 12 - 6
render/ground/fog_renderer.cpp

@@ -22,12 +22,15 @@ void FogRenderer::updateMask(int width, int height, float tileSize,
 }
 }
 
 
 void FogRenderer::submit(Renderer &renderer, ResourceManager *resources) {
 void FogRenderer::submit(Renderer &renderer, ResourceManager *resources) {
-  if (!m_enabled)
+  if (!m_enabled) {
     return;
     return;
-  if (m_width <= 0 || m_height <= 0)
+  }
+  if (m_width <= 0 || m_height <= 0) {
     return;
     return;
-  if (static_cast<int>(m_cells.size()) != m_width * m_height)
+  }
+  if (static_cast<int>(m_cells.size()) != m_width * m_height) {
     return;
     return;
+  }
 
 
   (void)resources;
   (void)resources;
 
 
@@ -39,10 +42,12 @@ void FogRenderer::submit(Renderer &renderer, ResourceManager *resources) {
 void FogRenderer::buildChunks() {
 void FogRenderer::buildChunks() {
   m_instances.clear();
   m_instances.clear();
 
 
-  if (m_width <= 0 || m_height <= 0)
+  if (m_width <= 0 || m_height <= 0) {
     return;
     return;
-  if (static_cast<int>(m_cells.size()) != m_width * m_height)
+  }
+  if (static_cast<int>(m_cells.size()) != m_width * m_height) {
     return;
     return;
+  }
 
 
   QElapsedTimer timer;
   QElapsedTimer timer;
   timer.start();
   timer.start();
@@ -55,8 +60,9 @@ void FogRenderer::buildChunks() {
   for (int z = 0; z < m_height; ++z) {
   for (int z = 0; z < m_height; ++z) {
     for (int x = 0; x < m_width; ++x) {
     for (int x = 0; x < m_width; ++x) {
       const std::uint8_t state = m_cells[z * m_width + x];
       const std::uint8_t state = m_cells[z * m_width + x];
-      if (state >= 2)
+      if (state >= 2) {
         continue;
         continue;
+      }
 
 
       FogInstance instance;
       FogInstance instance;
       const float worldX = (x - m_halfWidth) * m_tileSize;
       const float worldX = (x - m_halfWidth) * m_tileSize;

+ 2 - 1
render/ground/ground_renderer.cpp

@@ -119,8 +119,9 @@ TerrainChunkParams GroundRenderer::buildParams() const {
 }
 }
 
 
 void GroundRenderer::submit(Renderer &renderer, ResourceManager *resources) {
 void GroundRenderer::submit(Renderer &renderer, ResourceManager *resources) {
-  if (!resources)
+  if (!resources) {
     return;
     return;
+  }
 
 
   if (m_hasBiome) {
   if (m_hasBiome) {
     Mesh *plane = resources->ground();
     Mesh *plane = resources->ground();

+ 8 - 4
render/ground/pine_renderer.cpp

@@ -191,8 +191,9 @@ void PineRenderer::generatePineInstances() {
     QVector3D normal = normals[normalIdx];
     QVector3D normal = normals[normalIdx];
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
 
 
-    if (slope > 0.75f)
+    if (slope > 0.75f) {
       return false;
       return false;
+    }
 
 
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
@@ -240,8 +241,9 @@ void PineRenderer::generatePineInstances() {
 
 
       QVector3D normal = normals[idx];
       QVector3D normal = normals[idx];
       float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
       float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
-      if (slope > 0.75f)
+      if (slope > 0.75f) {
         continue;
         continue;
+      }
 
 
       uint32_t state = hashCoords(
       uint32_t state = hashCoords(
           x, z, m_noiseSeed ^ 0xAB12CD34u ^ static_cast<uint32_t>(idx));
           x, z, m_noiseSeed ^ 0xAB12CD34u ^ static_cast<uint32_t>(idx));
@@ -252,8 +254,9 @@ void PineRenderer::generatePineInstances() {
       float clusterNoise =
       float clusterNoise =
           valueNoise(worldX * 0.03f, worldZ * 0.03f, m_noiseSeed ^ 0x7F8E9D0Au);
           valueNoise(worldX * 0.03f, worldZ * 0.03f, m_noiseSeed ^ 0x7F8E9D0Au);
 
 
-      if (clusterNoise < 0.35f)
+      if (clusterNoise < 0.35f) {
         continue;
         continue;
+      }
 
 
       float densityMult = 1.0f;
       float densityMult = 1.0f;
       if (m_terrainTypes[idx] == Game::Map::TerrainType::Hill) {
       if (m_terrainTypes[idx] == Game::Map::TerrainType::Hill) {
@@ -265,8 +268,9 @@ void PineRenderer::generatePineInstances() {
       float effectiveDensity = pineDensity * densityMult * 0.8f;
       float effectiveDensity = pineDensity * densityMult * 0.8f;
       int pineCount = static_cast<int>(std::floor(effectiveDensity));
       int pineCount = static_cast<int>(std::floor(effectiveDensity));
       float frac = effectiveDensity - float(pineCount);
       float frac = effectiveDensity - float(pineCount);
-      if (rand01(state) < frac)
+      if (rand01(state) < frac) {
         pineCount += 1;
         pineCount += 1;
+      }
 
 
       for (int i = 0; i < pineCount; ++i) {
       for (int i = 0; i < pineCount; ++i) {
         float gx = float(x) + rand01(state) * 6.0f;
         float gx = float(x) + rand01(state) * 6.0f;

+ 18 - 9
render/ground/plant_renderer.cpp

@@ -236,23 +236,27 @@ void PlantRenderer::generatePlantInstances() {
     int iz = std::clamp(int(std::floor(sgz + 0.5f)), 0, m_height - 1);
     int iz = std::clamp(int(std::floor(sgz + 0.5f)), 0, m_height - 1);
     int normalIdx = iz * m_width + ix;
     int normalIdx = iz * m_width + ix;
 
 
-    if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::Mountain)
+    if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::Mountain) {
       return false;
       return false;
+    }
 
 
-    if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::River)
+    if (m_terrainTypes[normalIdx] == Game::Map::TerrainType::River) {
       return false;
       return false;
+    }
 
 
     constexpr int kRiverMargin = 1;
     constexpr int kRiverMargin = 1;
     for (int dz = -kRiverMargin; dz <= kRiverMargin; ++dz) {
     for (int dz = -kRiverMargin; dz <= kRiverMargin; ++dz) {
       for (int dx = -kRiverMargin; dx <= kRiverMargin; ++dx) {
       for (int dx = -kRiverMargin; dx <= kRiverMargin; ++dx) {
-        if (dx == 0 && dz == 0)
+        if (dx == 0 && dz == 0) {
           continue;
           continue;
+        }
         int nx = ix + dx;
         int nx = ix + dx;
         int nz = iz + dz;
         int nz = iz + dz;
         if (nx >= 0 && nx < m_width && nz >= 0 && nz < m_height) {
         if (nx >= 0 && nx < m_width && nz >= 0 && nz < m_height) {
           int nIdx = nz * m_width + nx;
           int nIdx = nz * m_width + nx;
-          if (m_terrainTypes[nIdx] == Game::Map::TerrainType::River)
+          if (m_terrainTypes[nIdx] == Game::Map::TerrainType::River) {
             return false;
             return false;
+          }
         }
         }
       }
       }
     }
     }
@@ -260,8 +264,9 @@ void PlantRenderer::generatePlantInstances() {
     QVector3D normal = normals[normalIdx];
     QVector3D normal = normals[normalIdx];
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
 
 
-    if (slope > 0.65f)
+    if (slope > 0.65f) {
       return false;
       return false;
+    }
 
 
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
@@ -313,13 +318,15 @@ void PlantRenderer::generatePlantInstances() {
       int idx = z * m_width + x;
       int idx = z * m_width + x;
 
 
       if (m_terrainTypes[idx] == Game::Map::TerrainType::Mountain ||
       if (m_terrainTypes[idx] == Game::Map::TerrainType::Mountain ||
-          m_terrainTypes[idx] == Game::Map::TerrainType::River)
+          m_terrainTypes[idx] == Game::Map::TerrainType::River) {
         continue;
         continue;
+      }
 
 
       QVector3D normal = normals[idx];
       QVector3D normal = normals[idx];
       float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
       float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
-      if (slope > 0.65f)
+      if (slope > 0.65f) {
         continue;
         continue;
+      }
 
 
       uint32_t state = hashCoords(
       uint32_t state = hashCoords(
           x, z, m_noiseSeed ^ 0x8F3C5A7Eu ^ static_cast<uint32_t>(idx));
           x, z, m_noiseSeed ^ 0x8F3C5A7Eu ^ static_cast<uint32_t>(idx));
@@ -330,8 +337,9 @@ void PlantRenderer::generatePlantInstances() {
       float clusterNoise =
       float clusterNoise =
           valueNoise(worldX * 0.05f, worldZ * 0.05f, m_noiseSeed ^ 0x4B9D2F1Au);
           valueNoise(worldX * 0.05f, worldZ * 0.05f, m_noiseSeed ^ 0x4B9D2F1Au);
 
 
-      if (clusterNoise < 0.45f)
+      if (clusterNoise < 0.45f) {
         continue;
         continue;
+      }
 
 
       cellsPassed++;
       cellsPassed++;
 
 
@@ -343,8 +351,9 @@ void PlantRenderer::generatePlantInstances() {
       float effectiveDensity = plantDensity * densityMult * 2.0f;
       float effectiveDensity = plantDensity * densityMult * 2.0f;
       int plantCount = static_cast<int>(std::floor(effectiveDensity));
       int plantCount = static_cast<int>(std::floor(effectiveDensity));
       float frac = effectiveDensity - float(plantCount);
       float frac = effectiveDensity - float(plantCount);
-      if (rand01(state) < frac)
+      if (rand01(state) < frac) {
         plantCount += 1;
         plantCount += 1;
+      }
 
 
       for (int i = 0; i < plantCount; ++i) {
       for (int i = 0; i < plantCount; ++i) {
         float gx = float(x) + rand01(state) * 3.0f;
         float gx = float(x) + rand01(state) * 3.0f;

+ 2 - 1
render/ground/river_renderer.cpp

@@ -167,8 +167,9 @@ void RiverRenderer::submit(Renderer &renderer, ResourceManager *resources) {
 
 
   size_t meshIndex = 0;
   size_t meshIndex = 0;
   for (const auto &segment : m_riverSegments) {
   for (const auto &segment : m_riverSegments) {
-    if (meshIndex >= m_meshes.size())
+    if (meshIndex >= m_meshes.size()) {
       break;
       break;
+    }
 
 
     auto *mesh = m_meshes[meshIndex].get();
     auto *mesh = m_meshes[meshIndex].get();
     ++meshIndex;
     ++meshIndex;

+ 10 - 5
render/ground/riverbank_asset_renderer.cpp

@@ -166,8 +166,9 @@ void RiverbankAssetRenderer::generateAssetInstances() {
 
 
     QVector3D dir = segment.end - segment.start;
     QVector3D dir = segment.end - segment.start;
     float length = dir.length();
     float length = dir.length();
-    if (length < 0.01f)
+    if (length < 0.01f) {
       continue;
       continue;
+    }
 
 
     dir.normalize();
     dir.normalize();
     QVector3D perpendicular(-dir.z(), 0.0f, dir.x());
     QVector3D perpendicular(-dir.z(), 0.0f, dir.x());
@@ -186,8 +187,9 @@ void RiverbankAssetRenderer::generateAssetInstances() {
       for (int side = 0; side < 2; ++side) {
       for (int side = 0; side < 2; ++side) {
         float sideSign = (side == 0) ? -1.0f : 1.0f;
         float sideSign = (side == 0) ? -1.0f : 1.0f;
 
 
-        if (rand01(rng) > 0.3f)
+        if (rand01(rng) > 0.3f) {
           continue;
           continue;
+        }
 
 
         float distFromWater = halfRiverWidth + rand01(rng) * bankZoneWidth;
         float distFromWater = halfRiverWidth + rand01(rng) * bankZoneWidth;
         float alongRiver = (rand01(rng) - 0.5f) * 0.6f;
         float alongRiver = (rand01(rng) - 0.5f) * 0.6f;
@@ -199,15 +201,17 @@ void RiverbankAssetRenderer::generateAssetInstances() {
         float gx = (assetPos.x() / m_tileSize) + halfWidth;
         float gx = (assetPos.x() / m_tileSize) + halfWidth;
         float gz = (assetPos.z() / m_tileSize) + halfHeight;
         float gz = (assetPos.z() / m_tileSize) + halfHeight;
 
 
-        if (gx < 0 || gx >= m_width - 1 || gz < 0 || gz >= m_height - 1)
+        if (gx < 0 || gx >= m_width - 1 || gz < 0 || gz >= m_height - 1) {
           continue;
           continue;
+        }
 
 
         int ix = static_cast<int>(gx);
         int ix = static_cast<int>(gx);
         int iz = static_cast<int>(gz);
         int iz = static_cast<int>(gz);
         int idx = iz * m_width + ix;
         int idx = iz * m_width + ix;
 
 
-        if (m_terrainTypes[idx] != Game::Map::TerrainType::Flat)
+        if (m_terrainTypes[idx] != Game::Map::TerrainType::Flat) {
           continue;
           continue;
+        }
 
 
         float worldY = sampleHeightAt(gx, gz);
         float worldY = sampleHeightAt(gx, gz);
 
 
@@ -243,8 +247,9 @@ void RiverbankAssetRenderer::generateAssetInstances() {
           instance.color[2] = colorVar * 0.9f;
           instance.color[2] = colorVar * 0.9f;
         } else {
         } else {
 
 
-          if (distFromWater > halfRiverWidth + 0.5f)
+          if (distFromWater > halfRiverWidth + 0.5f) {
             continue;
             continue;
+          }
 
 
           instance.assetType = 2.0f;
           instance.assetType = 2.0f;
           float size = 0.3f + rand01(rng) * 0.4f;
           float size = 0.3f + rand01(rng) * 0.4f;

+ 4 - 2
render/ground/riverbank_renderer.cpp

@@ -56,8 +56,9 @@ void RiverbankRenderer::buildMeshes() {
   };
   };
 
 
   auto sampleHeight = [&](float worldX, float worldZ) -> float {
   auto sampleHeight = [&](float worldX, float worldZ) -> float {
-    if (m_heights.empty() || m_gridWidth == 0 || m_gridHeight == 0)
+    if (m_heights.empty() || m_gridWidth == 0 || m_gridHeight == 0) {
       return 0.0f;
       return 0.0f;
+    }
 
 
     float halfWidth = m_gridWidth * 0.5f - 0.5f;
     float halfWidth = m_gridWidth * 0.5f - 0.5f;
     float halfHeight = m_gridHeight * 0.5f - 0.5f;
     float halfHeight = m_gridHeight * 0.5f - 0.5f;
@@ -250,8 +251,9 @@ void RiverbankRenderer::submit(Renderer &renderer, ResourceManager *resources) {
 
 
   size_t meshIndex = 0;
   size_t meshIndex = 0;
   for (const auto &segment : m_riverSegments) {
   for (const auto &segment : m_riverSegments) {
-    if (meshIndex >= m_meshes.size())
+    if (meshIndex >= m_meshes.size()) {
       break;
       break;
+    }
 
 
     auto *mesh = m_meshes[meshIndex].get();
     auto *mesh = m_meshes[meshIndex].get();
     ++meshIndex;
     ++meshIndex;

+ 14 - 7
render/ground/stone_renderer.cpp

@@ -188,8 +188,9 @@ void StoneRenderer::generateStoneInstances() {
     int iz = std::clamp(int(std::floor(sgz + 0.5f)), 0, m_height - 1);
     int iz = std::clamp(int(std::floor(sgz + 0.5f)), 0, m_height - 1);
     int normalIdx = iz * m_width + ix;
     int normalIdx = iz * m_width + ix;
 
 
-    if (m_terrainTypes[normalIdx] != Game::Map::TerrainType::Flat)
+    if (m_terrainTypes[normalIdx] != Game::Map::TerrainType::Flat) {
       return false;
       return false;
+    }
 
 
     constexpr int kRiverMargin = 1;
     constexpr int kRiverMargin = 1;
     for (int dz = -kRiverMargin; dz <= kRiverMargin; ++dz) {
     for (int dz = -kRiverMargin; dz <= kRiverMargin; ++dz) {
@@ -198,8 +199,9 @@ void StoneRenderer::generateStoneInstances() {
         int nz = iz + dz;
         int nz = iz + dz;
         if (nx >= 0 && nx < m_width && nz >= 0 && nz < m_height) {
         if (nx >= 0 && nx < m_width && nz >= 0 && nz < m_height) {
           int nIdx = nz * m_width + nx;
           int nIdx = nz * m_width + nx;
-          if (m_terrainTypes[nIdx] == Game::Map::TerrainType::River)
+          if (m_terrainTypes[nIdx] == Game::Map::TerrainType::River) {
             return false;
             return false;
+          }
         }
         }
       }
       }
     }
     }
@@ -207,8 +209,9 @@ void StoneRenderer::generateStoneInstances() {
     QVector3D normal = normals[normalIdx];
     QVector3D normal = normals[normalIdx];
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
     float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
 
 
-    if (slope > 0.15f)
+    if (slope > 0.15f) {
       return false;
       return false;
+    }
 
 
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldX = (gx - halfWidth) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
     float worldZ = (gz - halfHeight) * m_tileSize;
@@ -246,13 +249,15 @@ void StoneRenderer::generateStoneInstances() {
     for (int x = 0; x < m_width; x += 2) {
     for (int x = 0; x < m_width; x += 2) {
       int idx = z * m_width + x;
       int idx = z * m_width + x;
 
 
-      if (m_terrainTypes[idx] != Game::Map::TerrainType::Flat)
+      if (m_terrainTypes[idx] != Game::Map::TerrainType::Flat) {
         continue;
         continue;
+      }
 
 
       QVector3D normal = normals[idx];
       QVector3D normal = normals[idx];
       float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
       float slope = 1.0f - std::clamp(normal.y(), 0.0f, 1.0f);
-      if (slope > 0.15f)
+      if (slope > 0.15f) {
         continue;
         continue;
+      }
 
 
       uint32_t state = hashCoords(
       uint32_t state = hashCoords(
           x, z, m_noiseSeed ^ 0xABCDEF12u ^ static_cast<uint32_t>(idx));
           x, z, m_noiseSeed ^ 0xABCDEF12u ^ static_cast<uint32_t>(idx));
@@ -262,13 +267,15 @@ void StoneRenderer::generateStoneInstances() {
       float clusterNoise =
       float clusterNoise =
           valueNoise(worldX * 0.03f, worldZ * 0.03f, m_noiseSeed ^ 0x7F3A9B2Cu);
           valueNoise(worldX * 0.03f, worldZ * 0.03f, m_noiseSeed ^ 0x7F3A9B2Cu);
 
 
-      if (clusterNoise < 0.6f)
+      if (clusterNoise < 0.6f) {
         continue;
         continue;
+      }
 
 
       int stoneCount = static_cast<int>(std::floor(stoneDensity));
       int stoneCount = static_cast<int>(std::floor(stoneDensity));
       float frac = stoneDensity - float(stoneCount);
       float frac = stoneDensity - float(stoneCount);
-      if (rand01(state) < frac)
+      if (rand01(state) < frac) {
         stoneCount += 1;
         stoneCount += 1;
+      }
 
 
       for (int i = 0; i < stoneCount; ++i) {
       for (int i = 0; i < stoneCount; ++i) {
         float gx = float(x) + rand01(state) * 2.0f;
         float gx = float(x) + rand01(state) * 2.0f;

+ 21 - 11
render/ground/terrain_renderer.cpp

@@ -109,8 +109,9 @@ void TerrainRenderer::submit(Renderer &renderer, ResourceManager *resources) {
   const bool useVisibility = visibility.isInitialized();
   const bool useVisibility = visibility.isInitialized();
 
 
   for (const auto &chunk : m_chunks) {
   for (const auto &chunk : m_chunks) {
-    if (!chunk.mesh)
+    if (!chunk.mesh) {
       continue;
       continue;
+    }
 
 
     if (useVisibility) {
     if (useVisibility) {
       bool anyVisible = false;
       bool anyVisible = false;
@@ -123,8 +124,9 @@ void TerrainRenderer::submit(Renderer &renderer, ResourceManager *resources) {
           }
           }
         }
         }
       }
       }
-      if (!anyVisible)
+      if (!anyVisible) {
         continue;
         continue;
+      }
     }
     }
 
 
     renderer.terrainChunk(chunk.mesh.get(), kIdentityMatrix, chunk.params,
     renderer.terrainChunk(chunk.mesh.get(), kIdentityMatrix, chunk.params,
@@ -219,8 +221,9 @@ void TerrainRenderer::buildMeshes() {
     QVector3D dx(2.0f * m_tileSize, hR - hL, 0.0f);
     QVector3D dx(2.0f * m_tileSize, hR - hL, 0.0f);
     QVector3D dz(0.0f, hU - hD, 2.0f * m_tileSize);
     QVector3D dz(0.0f, hU - hD, 2.0f * m_tileSize);
     QVector3D n = QVector3D::crossProduct(dz, dx);
     QVector3D n = QVector3D::crossProduct(dz, dx);
-    if (n.lengthSquared() > 0.0f)
+    if (n.lengthSquared() > 0.0f) {
       n.normalize();
       n.normalize();
+    }
     return n.isNull() ? QVector3D(0, 1, 0) : n;
     return n.isNull() ? QVector3D(0, 1, 0) : n;
   };
   };
 
 
@@ -237,8 +240,9 @@ void TerrainRenderer::buildMeshes() {
 
 
   for (int i = 0; i < vertexCount; ++i) {
   for (int i = 0; i < vertexCount; ++i) {
     normals[i].normalize();
     normals[i].normalize();
-    if (normals[i].isNull())
+    if (normals[i].isNull()) {
       normals[i] = QVector3D(0.0f, 1.0f, 0.0f);
       normals[i] = QVector3D(0.0f, 1.0f, 0.0f);
+    }
     faceAccum[i] = normals[i];
     faceAccum[i] = normals[i];
   }
   }
 
 
@@ -383,8 +387,9 @@ void TerrainRenderer::buildMeshes() {
         float uu = pos.x() * texScale;
         float uu = pos.x() * texScale;
         float vv = pos.z() * texScale;
         float vv = pos.z() * texScale;
 
 
-        if (section.flipU)
+        if (section.flipU) {
           uu = -uu;
           uu = -uu;
+        }
         float ru = uu, rv = vv;
         float ru = uu, rv = vv;
         switch (static_cast<int>(section.rotationDeg)) {
         switch (static_cast<int>(section.rotationDeg)) {
         case 90: {
         case 90: {
@@ -481,12 +486,14 @@ void TerrainRenderer::buildMeshes() {
 
 
       for (int i = 0; i < 3; ++i) {
       for (int i = 0; i < 3; ++i) {
         SectionData &section = sections[i];
         SectionData &section = sections[i];
-        if (section.indices.empty())
+        if (section.indices.empty()) {
           continue;
           continue;
+        }
 
 
         auto mesh = std::make_unique<Mesh>(section.vertices, section.indices);
         auto mesh = std::make_unique<Mesh>(section.vertices, section.indices);
-        if (!mesh)
+        if (!mesh) {
           continue;
           continue;
+        }
 
 
         ChunkMesh chunk;
         ChunkMesh chunk;
         chunk.mesh = std::move(mesh);
         chunk.mesh = std::move(mesh);
@@ -561,8 +568,9 @@ void TerrainRenderer::buildMeshes() {
         float aoShade = 1.0f - 0.35f * aoAvg;
         float aoShade = 1.0f - 0.35f * aoAvg;
 
 
         QVector3D avgN = section.normalSum;
         QVector3D avgN = section.normalSum;
-        if (avgN.lengthSquared() > 0.0f)
+        if (avgN.lengthSquared() > 0.0f) {
           avgN.normalize();
           avgN.normalize();
+        }
         QVector3D north(0, 0, 1);
         QVector3D north(0, 0, 1);
         float northness = std::clamp(
         float northness = std::clamp(
             QVector3D::dotProduct(avgN, north) * 0.5f + 0.5f, 0.0f, 1.0f);
             QVector3D::dotProduct(avgN, north) * 0.5f + 0.5f, 0.0f, 1.0f);
@@ -625,10 +633,11 @@ void TerrainRenderer::buildMeshes() {
             std::max(1.0f, m_biomeSettings.terrainRockSharpness * sharpnessMul);
             std::max(1.0f, m_biomeSettings.terrainRockSharpness * sharpnessMul);
 
 
         float soilHeight = m_biomeSettings.terrainSoilHeight;
         float soilHeight = m_biomeSettings.terrainSoilHeight;
-        if (chunk.type == Game::Map::TerrainType::Hill)
+        if (chunk.type == Game::Map::TerrainType::Hill) {
           soilHeight -= 0.06f;
           soilHeight -= 0.06f;
-        else if (chunk.type == Game::Map::TerrainType::Mountain)
+        } else if (chunk.type == Game::Map::TerrainType::Mountain) {
           soilHeight -= 0.12f;
           soilHeight -= 0.12f;
+        }
         soilHeight += 0.05f * entranceFactor - 0.03f * plateauFactor;
         soilHeight += 0.05f * entranceFactor - 0.03f * plateauFactor;
         params.soilBlendHeight = soilHeight;
         params.soilBlendHeight = soilHeight;
 
 
@@ -648,8 +657,9 @@ void TerrainRenderer::buildMeshes() {
         float baseAmp =
         float baseAmp =
             m_biomeSettings.heightNoiseAmplitude *
             m_biomeSettings.heightNoiseAmplitude *
             (0.7f + 0.3f * std::clamp(roughness * 0.6f, 0.0f, 1.0f));
             (0.7f + 0.3f * std::clamp(roughness * 0.6f, 0.0f, 1.0f));
-        if (chunk.type == Game::Map::TerrainType::Mountain)
+        if (chunk.type == Game::Map::TerrainType::Mountain) {
           baseAmp *= 1.25f;
           baseAmp *= 1.25f;
+        }
         baseAmp *= (1.0f + 0.10f * edgeFactor - 0.08f * plateauFactor -
         baseAmp *= (1.0f + 0.10f * edgeFactor - 0.08f * plateauFactor -
                     0.06f * entranceFactor);
                     0.06f * entranceFactor);
         params.heightNoiseStrength = baseAmp;
         params.heightNoiseStrength = baseAmp;

+ 8 - 4
render/humanoid_base.cpp

@@ -92,11 +92,13 @@ AnimationInputs HumanoidRendererBase::sampleAnimState(const DrawContext &ctx) {
   anim.isExitingHold = false;
   anim.isExitingHold = false;
   anim.holdExitProgress = 0.0f;
   anim.holdExitProgress = 0.0f;
 
 
-  if (!ctx.entity)
+  if (!ctx.entity) {
     return anim;
     return anim;
+  }
 
 
-  if (ctx.entity->hasComponent<Engine::Core::PendingRemovalComponent>())
+  if (ctx.entity->hasComponent<Engine::Core::PendingRemovalComponent>()) {
     return anim;
     return anim;
+  }
 
 
   auto *movement = ctx.entity->getComponent<Engine::Core::MovementComponent>();
   auto *movement = ctx.entity->getComponent<Engine::Core::MovementComponent>();
   auto *attack = ctx.entity->getComponent<Engine::Core::AttackComponent>();
   auto *attack = ctx.entity->getComponent<Engine::Core::AttackComponent>();
@@ -246,8 +248,9 @@ void HumanoidRendererBase::computeLocomotionPose(
 
 
   QVector3D rightAxis = pose.shoulderR - pose.shoulderL;
   QVector3D rightAxis = pose.shoulderR - pose.shoulderL;
   rightAxis.setY(0.0f);
   rightAxis.setY(0.0f);
-  if (rightAxis.lengthSquared() < 1e-8f)
+  if (rightAxis.lengthSquared() < 1e-8f) {
     rightAxis = QVector3D(1, 0, 0);
     rightAxis = QVector3D(1, 0, 0);
+  }
   rightAxis.normalize();
   rightAxis.normalize();
   QVector3D outwardL = -rightAxis;
   QVector3D outwardL = -rightAxis;
   QVector3D outwardR = rightAxis;
   QVector3D outwardR = rightAxis;
@@ -270,8 +273,9 @@ void HumanoidRendererBase::drawCommonBody(const DrawContext &ctx,
   float headScale = scaling.z();
   float headScale = scaling.z();
 
 
   QVector3D rightAxis = pose.shoulderR - pose.shoulderL;
   QVector3D rightAxis = pose.shoulderR - pose.shoulderL;
-  if (rightAxis.lengthSquared() < 1e-8f)
+  if (rightAxis.lengthSquared() < 1e-8f) {
     rightAxis = QVector3D(1, 0, 0);
     rightAxis = QVector3D(1, 0, 0);
+  }
   rightAxis.normalize();
   rightAxis.normalize();
 
 
   const float yShoulder = 0.5f * (pose.shoulderL.y() + pose.shoulderR.y());
   const float yShoulder = 0.5f * (pose.shoulderL.y() + pose.shoulderR.y());

+ 2 - 1
render/humanoid_math.cpp

@@ -13,8 +13,9 @@ QVector3D elbowBendTorso(const QVector3D &shoulder, const QVector3D &hand,
   if (lateral.lengthSquared() < 1e-8f) {
   if (lateral.lengthSquared() < 1e-8f) {
     lateral = QVector3D::crossProduct(dir, QVector3D(0, 1, 0));
     lateral = QVector3D::crossProduct(dir, QVector3D(0, 1, 0));
   }
   }
-  if (QVector3D::dotProduct(lateral, outwardDir) < 0.0f)
+  if (QVector3D::dotProduct(lateral, outwardDir) < 0.0f) {
     lateral = -lateral;
     lateral = -lateral;
+  }
   lateral.normalize();
   lateral.normalize();
 
 
   return shoulder + dir * (dist * alongFrac) +
   return shoulder + dir * (dist * alongFrac) +

+ 48 - 24
render/scene_renderer.cpp

@@ -27,8 +27,9 @@ Renderer::Renderer() { m_activeQueue = &m_queues[m_fillQueueIndex]; }
 Renderer::~Renderer() { shutdown(); }
 Renderer::~Renderer() { shutdown(); }
 
 
 bool Renderer::initialize() {
 bool Renderer::initialize() {
-  if (!m_backend)
+  if (!m_backend) {
     m_backend = std::make_shared<Backend>();
     m_backend = std::make_shared<Backend>();
+  }
   m_backend->initialize();
   m_backend->initialize();
   m_entityRegistry = std::make_unique<EntityRendererRegistry>();
   m_entityRegistry = std::make_unique<EntityRendererRegistry>();
   registerBuiltInEntityRenderers(*m_entityRegistry);
   registerBuiltInEntityRenderers(*m_entityRegistry);
@@ -45,13 +46,15 @@ void Renderer::beginFrame() {
     m_viewProj = m_camera->getProjectionMatrix() * m_camera->getViewMatrix();
     m_viewProj = m_camera->getProjectionMatrix() * m_camera->getViewMatrix();
   }
   }
 
 
-  if (m_backend)
+  if (m_backend) {
     m_backend->beginFrame();
     m_backend->beginFrame();
+  }
 }
 }
 
 
 void Renderer::endFrame() {
 void Renderer::endFrame() {
-  if (m_paused.load())
+  if (m_paused.load()) {
     return;
     return;
+  }
   if (m_backend && m_camera) {
   if (m_backend && m_camera) {
     std::swap(m_fillQueueIndex, m_renderQueueIndex);
     std::swap(m_fillQueueIndex, m_renderQueueIndex);
     DrawQueue &renderQueue = m_queues[m_renderQueueIndex];
     DrawQueue &renderQueue = m_queues[m_renderQueueIndex];
@@ -64,15 +67,17 @@ void Renderer::endFrame() {
 void Renderer::setCamera(Camera *camera) { m_camera = camera; }
 void Renderer::setCamera(Camera *camera) { m_camera = camera; }
 
 
 void Renderer::setClearColor(float r, float g, float b, float a) {
 void Renderer::setClearColor(float r, float g, float b, float a) {
-  if (m_backend)
+  if (m_backend) {
     m_backend->setClearColor(r, g, b, a);
     m_backend->setClearColor(r, g, b, a);
+  }
 }
 }
 
 
 void Renderer::setViewport(int width, int height) {
 void Renderer::setViewport(int width, int height) {
   m_viewportWidth = width;
   m_viewportWidth = width;
   m_viewportHeight = height;
   m_viewportHeight = height;
-  if (m_backend)
+  if (m_backend) {
     m_backend->setViewport(width, height);
     m_backend->setViewport(width, height);
+  }
   if (m_camera && height > 0) {
   if (m_camera && height > 0) {
     float aspect = float(width) / float(height);
     float aspect = float(width) / float(height);
     m_camera->setPerspective(m_camera->getFOV(), aspect, m_camera->getNear(),
     m_camera->setPerspective(m_camera->getFOV(), aspect, m_camera->getNear(),
@@ -81,8 +86,9 @@ void Renderer::setViewport(int width, int height) {
 }
 }
 void Renderer::mesh(Mesh *mesh, const QMatrix4x4 &model, const QVector3D &color,
 void Renderer::mesh(Mesh *mesh, const QMatrix4x4 &model, const QVector3D &color,
                     Texture *texture, float alpha) {
                     Texture *texture, float alpha) {
-  if (!mesh)
+  if (!mesh) {
     return;
     return;
+  }
 
 
   if (mesh == getUnitCylinder() && (!texture) && (!m_currentShader)) {
   if (mesh == getUnitCylinder() && (!texture) && (!m_currentShader)) {
     QVector3D start, end;
     QVector3D start, end;
@@ -100,8 +106,9 @@ void Renderer::mesh(Mesh *mesh, const QMatrix4x4 &model, const QVector3D &color,
   cmd.color = color;
   cmd.color = color;
   cmd.alpha = alpha;
   cmd.alpha = alpha;
   cmd.shader = m_currentShader;
   cmd.shader = m_currentShader;
-  if (m_activeQueue)
+  if (m_activeQueue) {
     m_activeQueue->submit(cmd);
     m_activeQueue->submit(cmd);
+  }
 }
 }
 
 
 void Renderer::cylinder(const QVector3D &start, const QVector3D &end,
 void Renderer::cylinder(const QVector3D &start, const QVector3D &end,
@@ -112,13 +119,15 @@ void Renderer::cylinder(const QVector3D &start, const QVector3D &end,
   cmd.radius = radius;
   cmd.radius = radius;
   cmd.color = color;
   cmd.color = color;
   cmd.alpha = alpha;
   cmd.alpha = alpha;
-  if (m_activeQueue)
+  if (m_activeQueue) {
     m_activeQueue->submit(cmd);
     m_activeQueue->submit(cmd);
+  }
 }
 }
 
 
 void Renderer::fogBatch(const FogInstanceData *instances, std::size_t count) {
 void Renderer::fogBatch(const FogInstanceData *instances, std::size_t count) {
-  if (!instances || count == 0 || !m_activeQueue)
+  if (!instances || count == 0 || !m_activeQueue) {
     return;
     return;
+  }
   FogBatchCmd cmd;
   FogBatchCmd cmd;
   cmd.instances = instances;
   cmd.instances = instances;
   cmd.count = count;
   cmd.count = count;
@@ -127,8 +136,9 @@ void Renderer::fogBatch(const FogInstanceData *instances, std::size_t count) {
 
 
 void Renderer::grassBatch(Buffer *instanceBuffer, std::size_t instanceCount,
 void Renderer::grassBatch(Buffer *instanceBuffer, std::size_t instanceCount,
                           const GrassBatchParams &params) {
                           const GrassBatchParams &params) {
-  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue)
+  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
     return;
     return;
+  }
   GrassBatchCmd cmd;
   GrassBatchCmd cmd;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceCount = instanceCount;
   cmd.instanceCount = instanceCount;
@@ -139,8 +149,9 @@ void Renderer::grassBatch(Buffer *instanceBuffer, std::size_t instanceCount,
 
 
 void Renderer::stoneBatch(Buffer *instanceBuffer, std::size_t instanceCount,
 void Renderer::stoneBatch(Buffer *instanceBuffer, std::size_t instanceCount,
                           const StoneBatchParams &params) {
                           const StoneBatchParams &params) {
-  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue)
+  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
     return;
     return;
+  }
   StoneBatchCmd cmd;
   StoneBatchCmd cmd;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceCount = instanceCount;
   cmd.instanceCount = instanceCount;
@@ -150,8 +161,9 @@ void Renderer::stoneBatch(Buffer *instanceBuffer, std::size_t instanceCount,
 
 
 void Renderer::plantBatch(Buffer *instanceBuffer, std::size_t instanceCount,
 void Renderer::plantBatch(Buffer *instanceBuffer, std::size_t instanceCount,
                           const PlantBatchParams &params) {
                           const PlantBatchParams &params) {
-  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue)
+  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
     return;
     return;
+  }
   PlantBatchCmd cmd;
   PlantBatchCmd cmd;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceCount = instanceCount;
   cmd.instanceCount = instanceCount;
@@ -162,8 +174,9 @@ void Renderer::plantBatch(Buffer *instanceBuffer, std::size_t instanceCount,
 
 
 void Renderer::pineBatch(Buffer *instanceBuffer, std::size_t instanceCount,
 void Renderer::pineBatch(Buffer *instanceBuffer, std::size_t instanceCount,
                          const PineBatchParams &params) {
                          const PineBatchParams &params) {
-  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue)
+  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
     return;
     return;
+  }
   PineBatchCmd cmd;
   PineBatchCmd cmd;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceCount = instanceCount;
   cmd.instanceCount = instanceCount;
@@ -174,8 +187,9 @@ void Renderer::pineBatch(Buffer *instanceBuffer, std::size_t instanceCount,
 
 
 void Renderer::firecampBatch(Buffer *instanceBuffer, std::size_t instanceCount,
 void Renderer::firecampBatch(Buffer *instanceBuffer, std::size_t instanceCount,
                              const FireCampBatchParams &params) {
                              const FireCampBatchParams &params) {
-  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue)
+  if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
     return;
     return;
+  }
   FireCampBatchCmd cmd;
   FireCampBatchCmd cmd;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceBuffer = instanceBuffer;
   cmd.instanceCount = instanceCount;
   cmd.instanceCount = instanceCount;
@@ -188,8 +202,9 @@ void Renderer::terrainChunk(Mesh *mesh, const QMatrix4x4 &model,
                             const TerrainChunkParams &params,
                             const TerrainChunkParams &params,
                             std::uint16_t sortKey, bool depthWrite,
                             std::uint16_t sortKey, bool depthWrite,
                             float depthBias) {
                             float depthBias) {
-  if (!mesh || !m_activeQueue)
+  if (!mesh || !m_activeQueue) {
     return;
     return;
+  }
   TerrainChunkCmd cmd;
   TerrainChunkCmd cmd;
   cmd.mesh = mesh;
   cmd.mesh = mesh;
   cmd.model = model;
   cmd.model = model;
@@ -208,8 +223,9 @@ void Renderer::selectionRing(const QMatrix4x4 &model, float alphaInner,
   cmd.alphaInner = alphaInner;
   cmd.alphaInner = alphaInner;
   cmd.alphaOuter = alphaOuter;
   cmd.alphaOuter = alphaOuter;
   cmd.color = color;
   cmd.color = color;
-  if (m_activeQueue)
+  if (m_activeQueue) {
     m_activeQueue->submit(cmd);
     m_activeQueue->submit(cmd);
+  }
 }
 }
 
 
 void Renderer::grid(const QMatrix4x4 &model, const QVector3D &color,
 void Renderer::grid(const QMatrix4x4 &model, const QVector3D &color,
@@ -221,8 +237,9 @@ void Renderer::grid(const QMatrix4x4 &model, const QVector3D &color,
   cmd.cellSize = cellSize;
   cmd.cellSize = cellSize;
   cmd.thickness = thickness;
   cmd.thickness = thickness;
   cmd.extent = extent;
   cmd.extent = extent;
-  if (m_activeQueue)
+  if (m_activeQueue) {
     m_activeQueue->submit(cmd);
     m_activeQueue->submit(cmd);
+  }
 }
 }
 
 
 void Renderer::selectionSmoke(const QMatrix4x4 &model, const QVector3D &color,
 void Renderer::selectionSmoke(const QMatrix4x4 &model, const QVector3D &color,
@@ -232,16 +249,18 @@ void Renderer::selectionSmoke(const QMatrix4x4 &model, const QVector3D &color,
   cmd.mvp = m_viewProj * model;
   cmd.mvp = m_viewProj * model;
   cmd.color = color;
   cmd.color = color;
   cmd.baseAlpha = baseAlpha;
   cmd.baseAlpha = baseAlpha;
-  if (m_activeQueue)
+  if (m_activeQueue) {
     m_activeQueue->submit(cmd);
     m_activeQueue->submit(cmd);
+  }
 }
 }
 
 
 void Renderer::enqueueSelectionRing(Engine::Core::Entity *,
 void Renderer::enqueueSelectionRing(Engine::Core::Entity *,
                                     Engine::Core::TransformComponent *transform,
                                     Engine::Core::TransformComponent *transform,
                                     Engine::Core::UnitComponent *unitComp,
                                     Engine::Core::UnitComponent *unitComp,
                                     bool selected, bool hovered) {
                                     bool selected, bool hovered) {
-  if ((!selected && !hovered) || !transform)
+  if ((!selected && !hovered) || !transform) {
     return;
     return;
+  }
 
 
   float ringSize = 0.5f;
   float ringSize = 0.5f;
   float ringOffset = 0.05f;
   float ringOffset = 0.05f;
@@ -277,10 +296,12 @@ void Renderer::enqueueSelectionRing(Engine::Core::Entity *,
 }
 }
 
 
 void Renderer::renderWorld(Engine::Core::World *world) {
 void Renderer::renderWorld(Engine::Core::World *world) {
-  if (m_paused.load())
+  if (m_paused.load()) {
     return;
     return;
-  if (!world)
+  }
+  if (!world) {
     return;
     return;
+  }
 
 
   std::lock_guard<std::recursive_mutex> guard(world->getEntityMutex());
   std::lock_guard<std::recursive_mutex> guard(world->getEntityMutex());
 
 
@@ -366,8 +387,9 @@ void Renderer::renderWorld(Engine::Core::World *world) {
         drawnByRegistry = true;
         drawnByRegistry = true;
       }
       }
     }
     }
-    if (drawnByRegistry)
+    if (drawnByRegistry) {
       continue;
       continue;
+    }
 
 
     Mesh *meshToDraw = nullptr;
     Mesh *meshToDraw = nullptr;
     ResourceManager *res = resources();
     ResourceManager *res = resources();
@@ -391,10 +413,12 @@ void Renderer::renderWorld(Engine::Core::World *world) {
     default:
     default:
       break;
       break;
     }
     }
-    if (!meshToDraw && res)
+    if (!meshToDraw && res) {
       meshToDraw = res->unit();
       meshToDraw = res->unit();
-    if (!meshToDraw && res)
+    }
+    if (!meshToDraw && res) {
       meshToDraw = res->quad();
       meshToDraw = res->quad();
+    }
     QVector3D color = QVector3D(renderable->color[0], renderable->color[1],
     QVector3D color = QVector3D(renderable->color[0], renderable->color[1],
                                 renderable->color[2]);
                                 renderable->color[2]);
 
 

+ 365 - 0
scripts/run-clang-tidy-fixes.sh

@@ -0,0 +1,365 @@
+#!/usr/bin/env bash
+# clang-tidy fixer: git-only by default; --all to scan whole project
+# Runs only on files covered by compile_commands.json (safer).
+# Parallelized via xargs -P using a temp helper script (bash).
+
+set -euo pipefail
+
+# ---------- Defaults ----------
+BUILD_DIR_RELATIVE="build"
+DEFAULT_LANG_VALUE="en"
+SEARCH_PATHS_DEFAULT="app game render tools ui utils"
+GIT_ONLY=1
+GIT_BASE="${CLANG_TIDY_GIT_BASE:-origin/main}"
+
+DEFAULT_CHECKS="-*,readability-braces-around-statements"
+CHECKS_OVERRIDE="${CLANG_TIDY_AUTO_FIX_CHECKS:-$DEFAULT_CHECKS}"
+
+HEADER_FILTER="${CLANG_TIDY_HEADER_FILTER:-^(?!.*third_party).*$}"
+CLANG_TIDY_NICE="${CLANG_TIDY_NICE:-0}"
+
+if command -v nproc >/dev/null 2>&1; then
+  DEFAULT_JOBS=$(( ( $(nproc) + 1 ) / 2 ))
+else
+  DEFAULT_JOBS=2
+fi
+JOBS="${CLANG_TIDY_JOBS:-$DEFAULT_JOBS}"
+
+QUIET=1
+FIX_ERRORS=0
+INCLUDE_HEADERS=0            # <- do NOT feed headers directly
+ALLOW_UNCOVERED=0            # <- only run files present in compile DB by default
+PASSES=1
+RAW_PATHS=""
+USER_EXPORT_FIXES_DIR=""
+AGGRESSIVE=0
+
+print_help() {
+  cat <<'EOF'
+Usage: scripts/run-clang-tidy-fixes.sh [options]
+
+Options:
+  --all                    Run on the whole project (disables git-only; enables verbose)
+  --base=<ref>             Git base to diff against (default: origin/main)
+  --paths="<p1 p2 ...>"    Space- or comma-separated root paths to search
+  --jobs=<N>               Parallel jobs (xargs -P). Default: ~half cores
+  --checks="<pattern>"     Override -checks (e.g., "-*,bugprone-*")
+  --nice | --no-nice       Lower (or not) CPU/IO priority for clang-tidy
+  --build-dir=<dir>        Build dir with compile_commands.json (default: build)
+  --default-lang=<val>     CMake DEFAULT_LANG cache var (default: en)
+
+  --verbose | --no-quiet   Show clang-tidy output
+  --quiet                  Force quiet
+  --fix-errors             Use -fix-errors (stronger auto-fix)
+  --passes=<N>             Run up to N passes (default: 1)
+  --aggressive             Shortcut: --fix-errors + --passes=3
+  --no-headers             (ignored; headers not run directly by default)
+  --allow-uncovered        Attempt files not in compile DB (adds -std=c++20)
+  --export-fixes=<dir>     Save per-file fixes YAMLs into this directory
+
+  -h|--help                Show this help
+
+Env (also supported):
+  CLANG_TIDY_GIT_BASE, CLANG_TIDY_JOBS, CLANG_TIDY_AUTO_FIX_CHECKS,
+  CLANG_TIDY_HEADER_FILTER, CLANG_TIDY_NICE, CLANG_TIDY_FIX_PATHS,
+  CLANG_TIDY_EXTRA_ARG (single), CLANG_TIDY_EXTRA_ARGS (space-separated)
+EOF
+}
+
+# ---------- Parse CLI ----------
+while [[ $# -gt 0 ]]; do
+  case "$1" in
+    --all) GIT_ONLY=0; QUIET=0; shift ;;
+    --base=*) GIT_BASE="${1#*=}"; shift ;;
+    --base) GIT_BASE="${2:-$GIT_BASE}"; shift 2 ;;
+    --paths=*) RAW_PATHS="${1#*=}"; shift ;;
+    --paths) RAW_PATHS="${2:-}"; shift 2 ;;
+    --jobs=*) JOBS="${1#*=}"; shift ;;
+    --jobs) JOBS="${2:-$JOBS}"; shift 2 ;;
+    --checks=*) CHECKS_OVERRIDE="${1#*=}"; shift ;;
+    --checks) CHECKS_OVERRIDE="${2:-$CHECKS_OVERRIDE}"; shift 2 ;;
+    --nice) CLANG_TIDY_NICE=1; shift ;;
+    --no-nice) CLANG_TIDY_NICE=0; shift ;;
+    --build-dir=*) BUILD_DIR_RELATIVE="${1#*=}"; shift ;;
+    --build-dir) BUILD_DIR_RELATIVE="${2:-$BUILD_DIR_RELATIVE}"; shift 2 ;;
+    --default-lang=*) DEFAULT_LANG_VALUE="${1#*=}"; shift ;;
+    --default-lang) DEFAULT_LANG_VALUE="${2:-$DEFAULT_LANG_VALUE}"; shift 2 ;;
+    --verbose|--no-quiet) QUIET=0; VERBOSE_CMD=1; shift ;;
+    --quiet) QUIET=1; shift ;;
+    --fix-errors) FIX_ERRORS=1; shift ;;
+    --passes=*) PASSES="${1#*=}"; shift ;;
+    --passes) PASSES="${2:-$PASSES}"; shift 2 ;;
+    --aggressive) AGGRESSIVE=1; FIX_ERRORS=1; PASSES=$(( PASSES < 3 ? 3 : PASSES )); shift ;;
+    --no-headers) INCLUDE_HEADERS=0; shift ;;
+    --allow-uncovered) ALLOW_UNCOVERED=1; shift ;;
+    --export-fixes=*) USER_EXPORT_FIXES_DIR="${1#*=}"; shift ;;
+    -h|--help) print_help; exit 0 ;;
+    *) echo "Unknown option: $1"; print_help; exit 2 ;;
+  esac
+done
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$REPO_ROOT"
+
+# Paths to search
+if [[ -n "${RAW_PATHS:-}" ]]; then
+  RAW_PATHS="${RAW_PATHS//,/ }"
+  IFS=' ' read -r -a SEARCH_PATHS <<< "$RAW_PATHS"
+else
+  IFS=' ' read -r -a SEARCH_PATHS <<< "${CLANG_TIDY_FIX_PATHS:-$SEARCH_PATHS_DEFAULT}"
+fi
+
+# ---------- Tools / Setup ----------
+if ! command -v clang-tidy >/dev/null 2>&1; then
+  echo "⚠ clang-tidy not found; skipping automatic lint fixes."
+  exit 0
+fi
+
+[[ "$QUIET" -eq 0 ]] && clang-tidy --version || true
+
+BUILD_DIR="${REPO_ROOT}/${BUILD_DIR_RELATIVE}"
+mkdir -p "$BUILD_DIR"
+
+if [ ! -f "$BUILD_DIR/compile_commands.json" ]; then
+  echo "Generating compile_commands.json via CMake (DEFAULT_LANG=${DEFAULT_LANG_VALUE})..."
+  cmake -S "$REPO_ROOT" -B "$BUILD_DIR" -DDEFAULT_LANG="${DEFAULT_LANG_VALUE}" >/dev/null
+fi
+
+if [ ! -f "$BUILD_DIR/compile_commands.json" ]; then
+  echo "⚠ Unable to locate compile_commands.json in ${BUILD_DIR_RELATIVE}; skipping clang-tidy fixes."
+  exit 0
+fi
+
+# ---------- Collect sources (filesystem) ----------
+declare -a FS_SOURCES=()
+SRC_GLOBS=( '*.c' '*.cc' '*.cpp' '*.cxx' )
+# headers intentionally NOT included as standalone inputs
+
+add_sources_from_find() {
+  local root="$1"
+  local -a find_expr=( \( -name "${SRC_GLOBS[0]}" )
+  for g in "${SRC_GLOBS[@]:1}"; do find_expr+=( -o -name "$g" ); done
+  find_expr+=( \) )
+  while IFS= read -r -d '' FILE; do
+    REL_PATH="${FILE#$REPO_ROOT/}"
+    FS_SOURCES+=("$REL_PATH")
+  done < <(find "$root" \
+            -path "$root/third_party" -prune -o \
+            -type f "${find_expr[@]}" \
+            -print0)
+}
+
+if [[ "$GIT_ONLY" -eq 1 ]]; then
+  mapfile -t GIT_FILES < <(git diff --name-only --diff-filter=ACMR "$GIT_BASE"... -- "${SRC_GLOBS[@]}" 2>/dev/null || true)
+  for f in "${GIT_FILES[@]:-}"; do [[ -f "$f" ]] && FS_SOURCES+=("$f"); done
+else
+  for SEARCH_PATH in "${SEARCH_PATHS[@]}"; do
+    ABS_PATH="$REPO_ROOT/$SEARCH_PATH"
+    [[ -d "$ABS_PATH" ]] || continue
+    add_sources_from_find "$ABS_PATH"
+  done
+fi
+
+if [ ${#FS_SOURCES[@]} -eq 0 ]; then
+  echo "No C/C++ sources found under: ${SEARCH_PATHS[*]}"
+  exit 0
+fi
+
+# ---------- Build set of files from compile_commands.json ----------
+DB_FILES_TXT="$(mktemp)"
+if command -v jq >/dev/null 2>&1; then
+  jq -r '.[].file' "$BUILD_DIR/compile_commands.json" | sed 's#^\./##' > "$DB_FILES_TXT"
+else
+  # best-effort without jq
+  grep -oE '"file":\s*"[^"]+"' "$BUILD_DIR/compile_commands.json" | sed 's/^"file":\s*"\(.*\)"/\1/' > "$DB_FILES_TXT"
+fi
+
+# Normalize DB paths to repo-relative
+DB_REL_TXT="$(mktemp)"
+awk -v root="$REPO_ROOT/" '{ f=$0; sub("^"root, "", f); print f }' "$DB_FILES_TXT" > "$DB_REL_TXT"
+
+# ---------- Intersect (default) or union (if --allow-uncovered) ----------
+declare -a SOURCES=()
+if [[ "$ALLOW_UNCOVERED" -eq 1 ]]; then
+  # union: everything we found on FS; clang-tidy will guess for uncovered (may error)
+  SOURCES=("${FS_SOURCES[@]}")
+else
+  # intersection: only files present in compile DB
+  while IFS= read -r f; do
+    if grep -Fxq "$f" "$DB_REL_TXT"; then
+      SOURCES+=("$f")
+    fi
+  done < <(printf "%s\n" "${FS_SOURCES[@]}" | sort -u)
+fi
+
+covered=${#SOURCES[@]}
+total=${#FS_SOURCES[@]}
+echo "ℹ coverage: ${covered}/${total} source files are in compile_commands.json."
+
+if [ ${#SOURCES[@]} -eq 0 ]; then
+  echo "Nothing to run: none of the selected sources are in the compilation database."
+  echo "Tip: build with CMake/Ninja or use 'bear -- cmake --build build' to capture compile commands."
+  exit 0
+fi
+
+# ---------- Run config ----------
+NICE_PREFIX=()
+if [[ "$CLANG_TIDY_NICE" == "1" ]]; then
+  command -v nice >/dev/null 2>&1 && NICE_PREFIX+=(nice -n 10)
+  command -v ionice >/dev/null 2>&1 && NICE_PREFIX+=(ionice -c 2 -n 7)
+fi
+
+EXTRA_ARGS=()
+[[ -n "${CLANG_TIDY_EXTRA_ARG:-}" ]] && EXTRA_ARGS+=("--extra-arg=${CLANG_TIDY_EXTRA_ARG}")
+if [[ -n "${CLANG_TIDY_EXTRA_ARGS:-}" ]]; then
+  # shellcheck disable=SC2206
+  EXTRA_ARGS+=(${CLANG_TIDY_EXTRA_ARGS})
+fi
+
+# If attempting uncovered files, default to a reasonable standard to help parsing
+if [[ "$ALLOW_UNCOVERED" -eq 1 && -z "${CLANG_TIDY_EXTRA_ARG:-}" && -z "${CLANG_TIDY_EXTRA_ARGS:-}" ]]; then
+  EXTRA_ARGS+=("--extra-arg=-std=c++20")
+fi
+
+# Quote each extra arg so the helper can safely eval back to an array
+EXTRA_ARGS_STRING=""
+for a in "${EXTRA_ARGS[@]:-}"; do
+  EXTRA_ARGS_STRING+=" $(printf '%q' "$a")"
+done
+
+COMMON_ARGS_BASE=( -p "$BUILD_DIR" "-header-filter=$HEADER_FILTER" )
+[[ -n "$CHECKS_OVERRIDE" ]] && COMMON_ARGS_BASE+=("-checks=$CHECKS_OVERRIDE")
+[[ "$FIX_ERRORS" -eq 1 ]] && COMMON_ARGS_BASE+=(-fix-errors)
+
+# Prepare export dir (per-file) if requested
+if [[ -n "$USER_EXPORT_FIXES_DIR" ]]; then
+  mkdir -p "$USER_EXPORT_FIXES_DIR"
+fi
+TMP_EXPORT_DIR="$(mktemp -d "${BUILD_DIR}/clang-tidy-fixes-XXXX")"
+trap 'rm -rf "$TMP_EXPORT_DIR"' EXIT
+
+echo "Running clang-tidy fixes on ${#SOURCES[@]} file(s) ..."
+echo "  checks: ${CHECKS_OVERRIDE}"
+echo "  parallel jobs: ${JOBS}"
+[[ "$FIX_ERRORS" -eq 1 ]] && echo "  using -fix-errors"
+[[ "$PASSES" -gt 1 ]] && echo "  multi-pass: ${PASSES} passes (aggressive=${AGGRESSIVE})"
+
+# ---------- Helper script (bash) ----------
+TMP_HELPER="$(mktemp "${BUILD_DIR}/clang-tidy-one-XXXX.sh")"
+cat > "$TMP_HELPER" <<'HLP'
+#!/usr/bin/env bash
+set -euo pipefail
+f="$1"
+export_dir="$2"
+
+yaml="${export_dir}/$(echo "$f" | tr '/ ' '__').yaml"
+
+if [[ "$f" = /* ]]; then
+  tu="$f"
+else
+  tu="$REPO_ROOT/$f"
+fi
+
+cmd=(clang-tidy -fix -p "$BUILD_DIR" "-header-filter=$HEADER_FILTER")
+[[ -n "${CHECKS:-}" ]] && cmd+=("-checks=$CHECKS")
+[[ "${FIX_ERRORS:-0}" -eq 1 ]] && cmd+=(-fix-errors)
+
+cmd+=("-export-fixes=$yaml" "$tu")
+
+if [[ -n "${EXTRA_ARGS_STRING:-}" ]]; then
+  eval "extra=( ${EXTRA_ARGS_STRING} )"
+  filtered_extra=()
+  for arg in "${extra[@]}"; do
+    [[ -n "$arg" ]] && filtered_extra+=("$arg")
+  done
+  if [[ ${#filtered_extra[@]} -gt 0 ]]; then
+    cmd+=(-- "${filtered_extra[@]}")
+  fi
+fi
+
+run_cmd() {
+  if [[ "${NICE:-0}" -eq 1 ]]; then
+    if command -v ionice >/dev/null 2>&1; then
+      ionice -c 2 -n 7 nice -n 10 "${cmd[@]}"
+    else
+      nice -n 10 "${cmd[@]}"
+    fi
+  else
+    "${cmd[@]}"
+  fi
+}
+
+if [[ "${QUIET:-1}" -eq 1 ]]; then
+  run_cmd >/dev/null 2>&1 || true
+else
+  echo "[clang-tidy] $f"
+  if [[ "${VERBOSE_CMD:-0}" -eq 1 ]]; then
+    printf '        %s\n' "$(printf '%q ' "${cmd[@]}")"
+  fi
+  run_cmd || true
+fi
+HLP
+chmod +x "$TMP_HELPER"
+
+# Export env for helper
+export BUILD_DIR HEADER_FILTER EXTRA_ARGS_STRING QUIET
+export REPO_ROOT VERBOSE_CMD
+export CHECKS="${CHECKS_OVERRIDE}"
+export FIX_ERRORS
+export NICE="${CLANG_TIDY_NICE}"
+
+# ---------- Run (parallel) ----------
+pass=1
+while [[ $pass -le $PASSES ]]; do
+  [[ $PASSES -gt 1 ]] && echo "==> Pass ${pass}/${PASSES}"
+
+  if command -v xargs >/dev/null 2>&1; then
+    printf '%s\0' "${SOURCES[@]}" | xargs -0 -P "$JOBS" -I{} bash "$TMP_HELPER" "{}" "$TMP_EXPORT_DIR"
+  else
+    for f in "${SOURCES[@]}"; do bash "$TMP_HELPER" "$f" "$TMP_EXPORT_DIR"; done
+  fi
+
+  # Early stop if using multiple passes and nothing else changed
+  if [[ $PASSES -gt 1 ]] && command -v git >/dev/null 2>&1; then
+    if git diff --quiet -- "${SOURCES[@]}"; then
+      echo "No further changes detected; stopping early."
+      break
+    fi
+  fi
+
+  pass=$((pass + 1))
+done
+
+# ---------- Summaries ----------
+repl_total=0
+diag_total=0
+if ls "$TMP_EXPORT_DIR"/*.yaml >/dev/null 2>&1; then
+  while IFS= read -r y; do
+    r=$(grep -c 'ReplacementText:' "$y" || true)
+    d=$(grep -c 'DiagnosticMessage:' "$y" || true)
+    repl_total=$((repl_total + r))
+    diag_total=$((diag_total + d))
+  done < <(ls "$TMP_EXPORT_DIR"/*.yaml 2>/dev/null || true)
+  echo "Summary: diagnostics=${diag_total}, replacements=${repl_total} (from per-file YAMLs)."
+  if [[ -n "$USER_EXPORT_FIXES_DIR" ]]; then
+    mkdir -p "$USER_EXPORT_FIXES_DIR"
+    cp -f "$TMP_EXPORT_DIR"/*.yaml "$USER_EXPORT_FIXES_DIR"/ 2>/dev/null || true
+    echo "Per-file fixes exported to: $USER_EXPORT_FIXES_DIR"
+  fi
+else
+  echo "Summary: no fixes exported (no applicable fix-its)."
+fi
+
+# Changed files summary (git)
+if command -v git >/dev/null 2>&1; then
+  mapfile -t changed < <(git diff --name-only -- "${SOURCES[@]}")
+  if [[ ${#changed[@]} -gt 0 ]]; then
+    echo "Changed files (${#changed[@]}):"
+    printf '  %s\n' "${changed[@]:0:20}"
+    [[ ${#changed[@]} -gt 20 ]] && echo "  ... and $(( ${#changed[@]} - 20 )) more"
+  else
+    echo "No tracked files changed (git diff is clean for the selected sources)."
+  fi
+fi
+
+exit 0

+ 4 - 2
ui/gl_view.cpp

@@ -14,8 +14,9 @@ QQuickFramebufferObject::Renderer *GLView::createRenderer() const {
 QObject *GLView::engine() const { return m_engine; }
 QObject *GLView::engine() const { return m_engine; }
 
 
 void GLView::setEngine(QObject *eng) {
 void GLView::setEngine(QObject *eng) {
-  if (m_engine == eng)
+  if (m_engine == eng) {
     return;
     return;
+  }
   m_engine = qobject_cast<GameEngine *>(eng);
   m_engine = qobject_cast<GameEngine *>(eng);
   emit engineChanged();
   emit engineChanged();
   update();
   update();
@@ -25,8 +26,9 @@ GLView::GLRenderer::GLRenderer(QPointer<GameEngine> engine)
     : m_engine(engine) {}
     : m_engine(engine) {}
 
 
 void GLView::GLRenderer::render() {
 void GLView::GLRenderer::render() {
-  if (!m_engine)
+  if (!m_engine) {
     return;
     return;
+  }
   m_engine->ensureInitialized();
   m_engine->ensureInitialized();
   m_engine->update(1.0f / 60.0f);
   m_engine->update(1.0f / 60.0f);
   m_engine->render(m_size.width(), m_size.height());
   m_engine->render(m_size.width(), m_size.height());