💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3636 lines
117 KiB

5 years ago
5 years ago
5 years ago
5 years ago
  1. /*
  2. * Copyright (C) 2017-2019 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper Source Code.
  5. *
  6. * Antkeeper Source Code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper Source Code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "game.hpp"
  20. #include "resources/string-table.hpp"
  21. #include "filesystem.hpp"
  22. #include "timestamp.hpp"
  23. #include "ui/ui.hpp"
  24. #include "graphics/ui-render-pass.hpp"
  25. #include "graphics/shadow-map-render-pass.hpp"
  26. #include "graphics/clear-render-pass.hpp"
  27. #include "graphics/sky-render-pass.hpp"
  28. #include "graphics/lighting-render-pass.hpp"
  29. #include "graphics/silhouette-render-pass.hpp"
  30. #include "graphics/final-render-pass.hpp"
  31. #include "resources/resource-manager.hpp"
  32. #include "resources/text-file.hpp"
  33. #include "game/camera-rig.hpp"
  34. #include "game/lens.hpp"
  35. #include "game/forceps.hpp"
  36. #include "game/brush.hpp"
  37. #include "entity/component-manager.hpp"
  38. #include "entity/components/transform-component.hpp"
  39. #include "entity/components/camera-component.hpp"
  40. #include "entity/components/orbit-constraint-component.hpp"
  41. #include "entity/components/model-component.hpp"
  42. #include "entity/components/terrain-patch-component.hpp"
  43. #include "entity/entity-manager.hpp"
  44. #include "entity/entity-template.hpp"
  45. #include "entity/system-manager.hpp"
  46. #include "entity/systems/sound-system.hpp"
  47. #include "entity/systems/collision-system.hpp"
  48. #include "entity/systems/render-system.hpp"
  49. #include "entity/systems/constraint-system.hpp"
  50. #include "entity/systems/tool-system.hpp"
  51. #include "entity/systems/locomotion-system.hpp"
  52. #include "entity/systems/behavior-system.hpp"
  53. #include "entity/systems/steering-system.hpp"
  54. #include "entity/systems/particle-system.hpp"
  55. #include "entity/systems/terrain-system.hpp"
  56. #include "configuration.hpp"
  57. #include "stb/stb_image_write.h"
  58. #include "menu.hpp"
  59. #include <algorithm>
  60. #include <cctype>
  61. #include <fstream>
  62. #include <sstream>
  63. #include <stdexcept>
  64. #include <thread>
  65. #include "debug/command-interpreter.hpp"
  66. #include "debug/logger.hpp"
  67. #include "debug/ansi-escape-codes.hpp"
  68. Game::Game(int argc, char* argv[]):
  69. window(nullptr)
  70. {
  71. // Determine application name
  72. std::string applicationName;
  73. #if defined(_WIN32)
  74. applicationName = "Antkeeper";
  75. #else
  76. applicationName = "antkeeper";
  77. #endif
  78. // Form resource paths
  79. dataPath = getDataPath(applicationName) + "data/";
  80. configPath = getConfigPath(applicationName);
  81. controlsPath = configPath + "controls/";
  82. // Create nonexistent config directories
  83. std::vector<std::string> configPaths;
  84. configPaths.push_back(configPath);
  85. configPaths.push_back(controlsPath);
  86. for (const std::string& path: configPaths)
  87. {
  88. if (!pathExists(path))
  89. {
  90. createDirectory(path);
  91. }
  92. }
  93. // Setup resource manager
  94. resourceManager = new ResourceManager();
  95. // Include resource search paths in order of priority
  96. resourceManager->include(controlsPath);
  97. resourceManager->include(configPath);
  98. resourceManager->include(dataPath);
  99. // Subscribe the game to scheduled function events
  100. eventDispatcher.subscribe<ScheduledFunctionEvent>(this);
  101. toggleFullscreenDisabled = false;
  102. float3x3 m1;
  103. float3x3 m2;
  104. float3x3 m3 = m1 + m2;
  105. float3x3 m4 = m2 - m3;
  106. float4x4 projection = perspective(radians(45.0f), 3.0f / 4.0f, -1.0f, 1.0f);
  107. float4x4 ortho_proj = ortho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
  108. }
  109. Game::~Game()
  110. {
  111. if (window)
  112. {
  113. windowManager->destroyWindow(window);
  114. }
  115. }
  116. std::string Game::getString(const std::string& name, std::optional<std::size_t> languageIndex) const
  117. {
  118. std::string value;
  119. if (languageIndex == std::nullopt)
  120. {
  121. languageIndex = currentLanguageIndex;
  122. }
  123. auto it = stringTableIndex.find(name);
  124. if (it != stringTableIndex.end())
  125. {
  126. value = (*stringTable)[it->second][(*languageIndex) + 2];
  127. if (value.empty())
  128. {
  129. value = std::string("# EMPTY STRING: ") + name + std::string(" #");
  130. }
  131. }
  132. else
  133. {
  134. value = std::string("# MISSING STRING: ") + name + std::string(" #");
  135. }
  136. return value;
  137. }
  138. void Game::changeLanguage(std::size_t nextLanguageIndex)
  139. {
  140. // Get names of fonts
  141. std::string menuFontFilename = getString("menu-font-filename");
  142. // Unload fonts
  143. delete menuFont;
  144. resourceManager->unload(menuFontFilename);
  145. // Change current language index
  146. currentLanguageIndex = nextLanguageIndex;
  147. // Reload fonts
  148. loadFonts();
  149. // Set window title
  150. window->setTitle(getString("title").c_str());
  151. // Repopulate UI element strings
  152. restringUI();
  153. // Resize the UI
  154. resizeUI(w, h);
  155. // Reselect menu item
  156. if (currentMenuItem)
  157. {
  158. menuSelectorSlideAnimation.stop();
  159. selectMenuItem(menuItemIndex, false);
  160. uiRootElement->update();
  161. currentMenu->getContainer()->resetTweens();
  162. }
  163. // Save settings
  164. language = getString("language-code");
  165. saveSettings();
  166. }
  167. void Game::nextLanguage()
  168. {
  169. changeLanguage((currentLanguageIndex + 1) % languageCount);
  170. }
  171. void Game::openMenu(Menu* menu, int selectedItemIndex)
  172. {
  173. if (currentMenu)
  174. {
  175. closeCurrentMenu();
  176. }
  177. currentMenu = menu;
  178. uiRootElement->addChild(currentMenu->getContainer());
  179. currentMenu->getContainer()->addChild(menuSelectorImage);
  180. currentMenu->getContainer()->setTintColor(Vector4(1.0f));
  181. for (MenuItem* item: *currentMenu->getItems())
  182. {
  183. item->getContainer()->setTintColor(menuItemInactiveColor);
  184. }
  185. selectMenuItem(selectedItemIndex, false);
  186. uiRootElement->update();
  187. currentMenu->getContainer()->resetTweens();
  188. }
  189. void Game::closeCurrentMenu()
  190. {
  191. uiRootElement->removeChild(currentMenu->getContainer());
  192. currentMenu->getContainer()->removeChild(menuSelectorImage);
  193. currentMenu->getContainer()->setTintColor(Vector4(1.0f));
  194. for (MenuItem* item: *currentMenu->getItems())
  195. {
  196. item->getContainer()->setTintColor(menuItemInactiveColor);
  197. }
  198. currentMenu = nullptr;
  199. currentMenuItem = nullptr;
  200. menuItemIndex = -1;
  201. menuFadeAnimation.stop();
  202. menuSelectorSlideAnimation.stop();
  203. menuItemSelectAnimation.stop();
  204. menuItemDeselectAnimation.stop();
  205. previousMenu = currentMenu;
  206. currentMenu = nullptr;
  207. }
  208. void Game::selectMenuItem(int index, bool tween)
  209. {
  210. bool reselected = false;
  211. if (index != menuItemIndex)
  212. {
  213. if (menuItemSelectAnimation.isPlaying())
  214. {
  215. menuItemSelectAnimation.stop();
  216. currentMenuItem->getContainer()->setTintColor(menuItemActiveColor);
  217. }
  218. if (menuItemDeselectAnimation.isPlaying())
  219. {
  220. menuItemDeselectAnimation.stop();
  221. previousMenuItem->getContainer()->setTintColor(menuItemInactiveColor);
  222. }
  223. // Save previous menu item
  224. previousMenuItem = currentMenuItem;
  225. // Determine current menu item
  226. menuItemIndex = index;
  227. currentMenuItem = (*(currentMenu->getItems()))[index];
  228. }
  229. else
  230. {
  231. reselected = true;
  232. }
  233. // Determine target position of menu item selector
  234. Vector2 itemTranslation = currentMenuItem->getContainer()->getPosition() - currentMenu->getContainer()->getPosition();
  235. Vector2 itemDimensions = currentMenuItem->getContainer()->getDimensions();
  236. float spacing = fontSizePX;
  237. Vector2 translation;
  238. translation.x = itemTranslation.x - menuSelectorImage->getDimensions().x - spacing;
  239. translation.y = itemTranslation.y + itemDimensions.y * 0.5f - menuSelectorImage->getDimensions().y * 0.5;
  240. // Create tween animations
  241. if (!reselected && tween && previousMenuItem != nullptr)
  242. {
  243. float tweenDuration = 0.2f;
  244. Vector2 oldTranslation = menuSelectorImage->getTranslation();
  245. Vector2 newTranslation = translation;
  246. // Slide animation
  247. {
  248. menuSelectorSlideClip.removeChannels();
  249. AnimationChannel<float>* channel = menuSelectorSlideClip.addChannel(0);
  250. channel->insertKeyframe(0.0f, oldTranslation.y);
  251. channel->insertKeyframe(tweenDuration, newTranslation.y);
  252. menuSelectorSlideAnimation.setTimeFrame(menuSelectorSlideClip.getTimeFrame());
  253. menuSelectorSlideAnimation.rewind();
  254. menuSelectorSlideAnimation.play();
  255. }
  256. // Color animations
  257. {
  258. menuItemSelectClip.removeChannels();
  259. AnimationChannel<Vector4>* channel = menuItemSelectClip.addChannel(0);
  260. channel->insertKeyframe(0.0f, menuItemInactiveColor);
  261. channel->insertKeyframe(tweenDuration, menuItemActiveColor);
  262. menuItemSelectAnimation.setTimeFrame(menuItemSelectClip.getTimeFrame());
  263. menuItemSelectAnimation.rewind();
  264. menuItemSelectAnimation.play();
  265. if (previousMenuItem)
  266. {
  267. menuItemDeselectClip.removeChannels();
  268. channel = menuItemDeselectClip.addChannel(0);
  269. channel->insertKeyframe(0.0f, menuItemActiveColor);
  270. channel->insertKeyframe(tweenDuration, menuItemInactiveColor);
  271. menuItemDeselectAnimation.setTimeFrame(menuItemDeselectClip.getTimeFrame());
  272. menuItemDeselectAnimation.rewind();
  273. menuItemDeselectAnimation.play();
  274. }
  275. }
  276. menuSelectorImage->setTranslation(Vector2(newTranslation.x, oldTranslation.y));
  277. }
  278. else if (!tween)
  279. {
  280. menuSelectorImage->setTranslation(translation);
  281. currentMenuItem->getContainer()->setTintColor(menuItemActiveColor);
  282. if (previousMenuItem)
  283. {
  284. previousMenuItem->getContainer()->setTintColor(menuItemInactiveColor);
  285. }
  286. }
  287. }
  288. void Game::selectNextMenuItem()
  289. {
  290. int index = (menuItemIndex + 1) % currentMenu->getItems()->size();
  291. selectMenuItem(index, true);
  292. }
  293. void Game::selectPreviousMenuItem()
  294. {
  295. int index = (menuItemIndex + (currentMenu->getItems()->size() - 1)) % currentMenu->getItems()->size();
  296. selectMenuItem(index, true);
  297. }
  298. void Game::activateMenuItem()
  299. {
  300. currentMenuItem->activate();
  301. }
  302. void Game::activateLastMenuItem()
  303. {
  304. if (currentMenu)
  305. {
  306. (*currentMenu->getItems())[currentMenu->getItems()->size() - 1]->activate();
  307. }
  308. }
  309. void Game::toggleFullscreen()
  310. {
  311. if (!toggleFullscreenDisabled)
  312. {
  313. fullscreen = !(*fullscreen);
  314. //window->setFullscreen(*fullscreen);
  315. if (!(*fullscreen))
  316. {
  317. const Display* display = deviceManager->getDisplays()->front();
  318. int displayWidth = std::get<0>(display->getDimensions());
  319. int displayHeight = std::get<1>(display->getDimensions());
  320. w = (*windowResolution)[0];
  321. h = (*windowResolution)[1];
  322. window->setBordered(true);
  323. window->setResizable(true);
  324. window->setDimensions(w, h);
  325. window->setPosition((*windowPosition)[0], (*windowPosition)[1]);
  326. }
  327. else
  328. {
  329. const Display* display = deviceManager->getDisplays()->front();
  330. int displayWidth = std::get<0>(display->getDimensions());
  331. int displayHeight = std::get<1>(display->getDimensions());
  332. w = displayWidth;
  333. h = displayHeight;
  334. window->setBordered(false);
  335. window->setResizable(false);
  336. window->setPosition(0, 0);
  337. window->setDimensions(w, h);
  338. }
  339. restringUI();
  340. // Disable fullscreen toggles for 500ms
  341. toggleFullscreenDisabled = true;
  342. ScheduledFunctionEvent event;
  343. event.caller = static_cast<void*>(this);
  344. event.function = [this]()
  345. {
  346. toggleFullscreenDisabled = false;
  347. };
  348. eventDispatcher.schedule(event, time + 0.5f);
  349. // Save settings
  350. saveSettings();
  351. }
  352. }
  353. void Game::toggleVSync()
  354. {
  355. vsync = !(*vsync);
  356. window->setVSync(*vsync);
  357. restringUI();
  358. // Save settings
  359. saveSettings();
  360. }
  361. void Game::setUpdateRate(double frequency)
  362. {
  363. stepScheduler.setStepFrequency(frequency);
  364. }
  365. void Game::disableNonSystemControls()
  366. {
  367. controls.setCallbacksEnabled(false);
  368. systemControls.setCallbacksEnabled(true);
  369. }
  370. void Game::setup()
  371. {
  372. setupDebugging();
  373. loadSettings();
  374. setupLocalization();
  375. setupWindow();
  376. setupGraphics();
  377. setupControls();
  378. setupUI();
  379. setupGameplay();
  380. screenshotQueued = false;
  381. paused = false;
  382. // Load model resources
  383. try
  384. {
  385. lensModel = resourceManager->load<Model>("lens.mdl");
  386. forcepsModel = resourceManager->load<Model>("forceps.mdl");
  387. brushModel = resourceManager->load<Model>("brush.mdl");
  388. smokeMaterial = resourceManager->load<Material>("smoke.mtl");
  389. }
  390. catch (const std::exception& e)
  391. {
  392. logger->error("Failed to load one or more models: \"" + std::string(e.what()) + "\"\n");
  393. close(EXIT_FAILURE);
  394. }
  395. time = 0.0f;
  396. // Tools
  397. currentTool = nullptr;
  398. lens = new Lens(lensModel, &animator);
  399. lens->setOrbitCam(orbitCam);
  400. worldScene->addObject(lens->getModelInstance());
  401. worldScene->addObject(lens->getSpotlight());
  402. lens->setSunDirection(-sunlightCamera.getForward());
  403. // Forceps
  404. forceps = new Forceps(forcepsModel, &animator);
  405. forceps->setOrbitCam(orbitCam);
  406. worldScene->addObject(forceps->getModelInstance());
  407. // Brush
  408. brush = new Brush(brushModel, &animator);
  409. brush->setOrbitCam(orbitCam);
  410. worldScene->addObject(brush->getModelInstance());
  411. // Initialize component manager
  412. componentManager = new ComponentManager();
  413. // Initialize entity manager
  414. entityManager = new EntityManager(componentManager);
  415. // Initialize systems
  416. soundSystem = new SoundSystem(componentManager);
  417. collisionSystem = new CollisionSystem(componentManager);
  418. constraintSystem = new ConstraintSystem(componentManager);
  419. renderSystem = new RenderSystem(componentManager, worldScene);
  420. toolSystem = new ToolSystem(componentManager);
  421. toolSystem->setPickingCamera(&camera);
  422. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  423. eventDispatcher.subscribe<MouseMovedEvent>(toolSystem);
  424. behaviorSystem = new BehaviorSystem(componentManager);
  425. steeringSystem = new SteeringSystem(componentManager);
  426. locomotionSystem = new LocomotionSystem(componentManager);
  427. terrainSystem = new TerrainSystem(componentManager);
  428. terrainSystem->setPatchSize(500.0f);
  429. particleSystem = new ParticleSystem(componentManager);
  430. particleSystem->resize(1000);
  431. particleSystem->setMaterial(smokeMaterial);
  432. particleSystem->setDirection(Vector3(0, 1, 0));
  433. lens->setParticleSystem(particleSystem);
  434. particleSystem->getBillboardBatch()->setAlignment(&camera, BillboardAlignmentMode::SPHERICAL);
  435. worldScene->addObject(particleSystem->getBillboardBatch());
  436. // Initialize system manager
  437. systemManager = new SystemManager();
  438. systemManager->addSystem(soundSystem);
  439. systemManager->addSystem(behaviorSystem);
  440. systemManager->addSystem(steeringSystem);
  441. systemManager->addSystem(locomotionSystem);
  442. systemManager->addSystem(collisionSystem);
  443. systemManager->addSystem(toolSystem);
  444. systemManager->addSystem(terrainSystem);
  445. systemManager->addSystem(particleSystem);
  446. systemManager->addSystem(constraintSystem);
  447. systemManager->addSystem(renderSystem);
  448. // Create focus entity
  449. focusEntity = createInstance();
  450. componentManager->addComponent(focusEntity, new TransformComponent());
  451. setTranslation(focusEntity, {0, 0, 0});
  452. // Create camera entity
  453. cameraEntity = createInstance();
  454. CameraComponent* cameraComponent = new CameraComponent();
  455. cameraComponent->camera = &camera;
  456. TransformComponent* transformComponent = new TransformComponent();
  457. OrbitConstraintComponent* orbitConstraintComponent = new OrbitConstraintComponent();
  458. orbitConstraintComponent->target = 0;
  459. orbitConstraintComponent->elevation = 0.0f;
  460. orbitConstraintComponent->azimuth = 0.0f;
  461. orbitConstraintComponent->distance = 0.0f;
  462. componentManager->addComponent(cameraEntity, cameraComponent);
  463. componentManager->addComponent(cameraEntity, transformComponent);
  464. componentManager->addComponent(cameraEntity, orbitConstraintComponent);
  465. // Load navmesh
  466. TriangleMesh* navmesh = resourceManager->load<TriangleMesh>("sidewalk.mesh");
  467. int highResolutionDiameter = 3;
  468. int mediumResolutionDiameter = highResolutionDiameter + 2;
  469. int lowResolutionDiameter = 20;
  470. float lowResolutionRadius = static_cast<float>(lowResolutionDiameter) / 2.0f;
  471. float mediumResolutionRadius = static_cast<float>(mediumResolutionDiameter) / 2.0f;
  472. float highResolutionRadius = static_cast<float>(highResolutionDiameter) / 2.0f;
  473. for (int i = 0; i < lowResolutionDiameter; ++i)
  474. {
  475. for (int j = 0; j < lowResolutionDiameter; ++j)
  476. {
  477. EntityID patch;
  478. int x = i - lowResolutionDiameter / 2;
  479. int z = j - lowResolutionDiameter / 2;
  480. if (std::abs(x) < highResolutionRadius && std::abs(z) < highResolutionRadius)
  481. {
  482. patch = createInstanceOf("terrain-patch-high-resolution");
  483. }
  484. else if (std::abs(x) < mediumResolutionRadius && std::abs(z) < mediumResolutionRadius)
  485. {
  486. patch = createInstanceOf("terrain-patch-medium-resolution");
  487. }
  488. else
  489. {
  490. patch = createInstanceOf("terrain-patch-low-resolution");
  491. }
  492. setTerrainPatchPosition(patch, {x, z});
  493. }
  494. }
  495. // Setup state machine states
  496. languageSelectState =
  497. {
  498. std::bind(&Game::enterLanguageSelectState, this),
  499. std::bind(&Game::exitLanguageSelectState, this)
  500. };
  501. splashState =
  502. {
  503. std::bind(&Game::enterSplashState, this),
  504. std::bind(&Game::exitSplashState, this)
  505. };
  506. loadingState =
  507. {
  508. std::bind(&Game::enterLoadingState, this),
  509. std::bind(&Game::exitLoadingState, this)
  510. };
  511. titleState =
  512. {
  513. std::bind(&Game::enterTitleState, this),
  514. std::bind(&Game::exitTitleState, this)
  515. };
  516. playState =
  517. {
  518. std::bind(&Game::enterPlayState, this),
  519. std::bind(&Game::exitPlayState, this)
  520. };
  521. // Initialize state machine
  522. if (firstRun)
  523. {
  524. StateMachine::changeState(&languageSelectState);
  525. }
  526. else
  527. {
  528. #if defined(DEBUG)
  529. StateMachine::changeState(&titleState);
  530. #else
  531. StateMachine::changeState(&splashState);
  532. #endif
  533. }
  534. }
  535. void Game::update(float t, float dt)
  536. {
  537. this->time = t;
  538. // Update systems
  539. systemManager->update(t, dt);
  540. // Update animations
  541. animator.animate(dt);
  542. if (fpsLabel->isVisible())
  543. {
  544. std::stringstream stream;
  545. stream.precision(2);
  546. stream << std::fixed << (performanceSampler.getMeanFrameDuration() * 1000.0f);
  547. fpsLabel->setText(stream.str());
  548. }
  549. uiRootElement->update();
  550. }
  551. void Game::input()
  552. {
  553. controls.update();
  554. }
  555. void Game::render()
  556. {
  557. // Perform sub-frame interpolation on UI elements
  558. uiRootElement->interpolate(stepScheduler.getScheduledSubsteps());
  559. // Update and batch UI elements
  560. uiBatcher->batch(uiBatch, uiRootElement);
  561. // Perform sub-frame interpolation particles
  562. particleSystem->getBillboardBatch()->interpolate(stepScheduler.getScheduledSubsteps());
  563. particleSystem->getBillboardBatch()->batch();
  564. // Render scene
  565. renderer.render(*worldScene);
  566. renderer.render(*uiScene);
  567. if (screenshotQueued)
  568. {
  569. screenshot();
  570. screenshotQueued = false;
  571. }
  572. // Swap window framebuffers
  573. window->swapBuffers();
  574. }
  575. void Game::exit()
  576. {}
  577. void Game::handleEvent(const WindowResizedEvent& event)
  578. {
  579. w = event.width;
  580. h = event.height;
  581. if (*fullscreen)
  582. {
  583. logger->log("Resized fullscreen window to " + std::to_string(w) + "x" + std::to_string(h));
  584. fullscreenResolution = {event.width, event.height};
  585. }
  586. else
  587. {
  588. logger->log("Resized window to " + std::to_string(w) + "x" + std::to_string(h));
  589. windowResolution = {event.width, event.height};
  590. }
  591. // Save resolution settings
  592. saveSettings();
  593. defaultRenderTarget.width = event.width;
  594. defaultRenderTarget.height = event.height;
  595. glViewport(0, 0, event.width, event.height);
  596. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  597. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  598. resizeUI(event.width, event.height);
  599. skipSplash();
  600. }
  601. void Game::handleEvent(const WindowMovedEvent& event)
  602. {
  603. if (!(*fullscreen))
  604. {
  605. windowPosition = {event.x, event.y};
  606. saveSettings();
  607. }
  608. }
  609. void Game::handleEvent(const GamepadConnectedEvent& event)
  610. {
  611. // Unmap all controls
  612. inputRouter->reset();
  613. // Reload control profile
  614. loadControlProfile(*controlProfileName);
  615. }
  616. void Game::handleEvent(const GamepadDisconnectedEvent& event)
  617. {}
  618. void Game::handleEvent(const ScheduledFunctionEvent& event)
  619. {
  620. if (event.caller == static_cast<void*>(this))
  621. {
  622. event.function();
  623. }
  624. }
  625. void Game::setupDebugging()
  626. {
  627. // Setup logging
  628. {
  629. logger = new Logger();
  630. // Style log format
  631. std::string logPrefix = std::string();
  632. std::string logPostfix = "\n";
  633. std::string warningPrefix = "Warning: ";
  634. std::string warningPostfix = std::string();
  635. std::string errorPrefix = "Error: ";
  636. std::string errorPostfix = std::string();
  637. std::string successPrefix = std::string();
  638. std::string successPostfix = std::string();
  639. // Enable colored messages on debug builds
  640. #if defined(DEBUG)
  641. warningPrefix = std::string(ANSI_CODE_BOLD) + std::string(ANSI_CODE_YELLOW) + std::string("Warning: ") + std::string(ANSI_CODE_RESET) + std::string(ANSI_CODE_YELLOW);
  642. warningPostfix.append(ANSI_CODE_RESET);
  643. errorPrefix = std::string(ANSI_CODE_BOLD) + std::string(ANSI_CODE_RED) + std::string("Error: ") + std::string(ANSI_CODE_RESET) + std::string(ANSI_CODE_RED);
  644. errorPostfix.append(ANSI_CODE_RESET);
  645. successPrefix.insert(0, ANSI_CODE_GREEN);
  646. successPostfix.append(ANSI_CODE_RESET);
  647. #endif
  648. logger->setLogPrefix(logPrefix);
  649. logger->setLogPostfix(logPostfix);
  650. logger->setWarningPrefix(warningPrefix);
  651. logger->setWarningPostfix(warningPostfix);
  652. logger->setErrorPrefix(errorPrefix);
  653. logger->setErrorPostfix(errorPostfix);
  654. logger->setSuccessPrefix(successPrefix);
  655. logger->setSuccessPostfix(successPostfix);
  656. // Redirect logger output to log file on release builds
  657. #if !defined(DEBUG)
  658. std::string logFilename = configPath + "log.txt";
  659. logFileStream.open(logFilename.c_str());
  660. logger->redirect(&logFileStream);
  661. #endif
  662. }
  663. // Create CLI
  664. cli = new CommandInterpreter();
  665. // Register CLI commands
  666. std::function<void(std::string, std::string)> setCommand = std::bind(&CommandInterpreter::set, cli, std::placeholders::_1, std::placeholders::_2);
  667. std::function<void(std::string)> unsetCommand = std::bind(&CommandInterpreter::unset, cli, std::placeholders::_1);
  668. std::function<void()> exitCommand = std::bind(std::exit, EXIT_SUCCESS);
  669. std::function<void(int, float, float, float)> setScaleCommand = [this](int id, float x, float y, float z) {
  670. setScale(id, {x, y, z});
  671. };
  672. std::function<void(int, float, float, float)> setTranslationCommand = [this](int id, float x, float y, float z) {
  673. setTranslation(id, {x, y, z});
  674. };
  675. std::function<void()> createInstanceCommand = std::bind(&Game::createInstance, this);
  676. std::function<void(std::string)> createNamedInstanceCommand = std::bind(&Game::createNamedInstance, this, std::placeholders::_1);
  677. std::function<void(std::string)> createInstanceOfCommand = std::bind(&Game::createInstanceOf, this, std::placeholders::_1);
  678. std::function<void(std::string, std::string)> createNamedInstanceOfCommand = std::bind(&Game::createNamedInstanceOf, this, std::placeholders::_1, std::placeholders::_2);
  679. std::function<void(float)> toggleWireframeCommand = [this](float width){ lightingPass->setWireframeLineWidth(width); };
  680. std::function<void()> helpCommand = [this]()
  681. {
  682. auto& helpStrings = cli->help();
  683. for (auto it = helpStrings.begin(); it != helpStrings.end(); ++it)
  684. {
  685. if (it->second.empty())
  686. {
  687. continue;
  688. }
  689. std::cout << it->second << std::endl;
  690. }
  691. };
  692. std::function<void()> variablesCommand = [this]()
  693. {
  694. auto& variables = cli->variables();
  695. for (auto it = variables.begin(); it != variables.end(); ++it)
  696. {
  697. std::cout << it->first << "=\"" << it->second << "\"" << std::endl;
  698. }
  699. };
  700. std::string exitHelp = "exit";
  701. std::string setHelp = "set <variable name> <value>";
  702. std::string unsetHelp = "unset <variable name>";
  703. std::string createInstanceHelp = "createinstance <template name>";
  704. std::string createNamedInstanceHelp = "createnamedinstance <template name> <instance name>";
  705. std::string createInstanceOfHelp = "createinstanceof <template name>";
  706. std::string createNamedInstanceOfHelp = "createnamedinstanceof <template name> <instance name>";
  707. std::string setTranslationHelp = "settranslation <id> <x> <y> <z>";
  708. std::string setScaleHelp = "setscale <id> <sx> <sy> <sz>";
  709. std::string wireframeHelp = "wireframe <width>";
  710. std::string variablesHelp = "variables";
  711. cli->registerCommand("exit", exitCommand, exitHelp);
  712. cli->registerCommand("set", setCommand, setHelp);
  713. cli->registerCommand("unset", setCommand, unsetHelp);
  714. cli->registerCommand("createinstance", createInstanceCommand, createInstanceHelp);
  715. cli->registerCommand("createnamedinstance", createNamedInstanceCommand, createNamedInstanceHelp);
  716. cli->registerCommand("createinstanceof", createInstanceOfCommand, createInstanceOfHelp);
  717. cli->registerCommand("createnamedinstanceof", createNamedInstanceOfCommand, createNamedInstanceOfHelp);
  718. cli->registerCommand("setscale", setScaleCommand, setScaleHelp);
  719. cli->registerCommand("settranslation", setTranslationCommand, setTranslationHelp);
  720. cli->registerCommand("wireframe", toggleWireframeCommand, wireframeHelp);
  721. cli->registerCommand("variables", variablesCommand, variablesHelp);
  722. cli->registerCommand("help", helpCommand);
  723. // Start CLI thread
  724. std::thread cliThread(&Game::interpretCommands, this);
  725. cliThread.detach();
  726. // Setup performance sampling
  727. performanceSampler.setSampleSize(30);
  728. }
  729. void Game::setupLocalization()
  730. {
  731. // Load strings
  732. loadStrings();
  733. // Determine number of available languages
  734. languageCount = (*stringTable)[0].size() - 2;
  735. // Match language code with language index
  736. currentLanguageIndex = 0;
  737. StringTableRow* languageCodes = &(*stringTable)[1];
  738. for (std::size_t i = 2; i < languageCodes->size(); ++i)
  739. {
  740. if (*language == (*languageCodes)[i])
  741. {
  742. currentLanguageIndex = i - 2;
  743. break;
  744. }
  745. }
  746. }
  747. void Game::setupWindow()
  748. {
  749. // Get display resolution
  750. const Display* display = deviceManager->getDisplays()->front();
  751. int displayWidth = std::get<0>(display->getDimensions());
  752. int displayHeight = std::get<1>(display->getDimensions());
  753. int flags = 0;
  754. int x;
  755. int y;
  756. if (*fullscreen)
  757. {
  758. w = displayWidth;
  759. h = displayHeight;
  760. x = std::get<0>(display->getPosition());
  761. y = std::get<1>(display->getPosition());
  762. flags |= WindowFlag::BORDERLESS;
  763. }
  764. else
  765. {
  766. w = (*windowResolution)[0];
  767. h = (*windowResolution)[1];
  768. x = (*windowPosition)[0];
  769. y = (*windowPosition)[1];
  770. flags |= WindowFlag::RESIZABLE;
  771. }
  772. // Read title string
  773. std::string title = getString("title");
  774. // Create window
  775. window = windowManager->createWindow(title.c_str(), x, y, w, h, flags);
  776. if (!window)
  777. {
  778. throw std::runtime_error("Game::Game(): Failed to create window.");
  779. }
  780. // Set v-sync mode
  781. window->setVSync(*vsync);
  782. debugFont = nullptr;
  783. menuFont = nullptr;
  784. }
  785. void Game::setupGraphics()
  786. {
  787. // Setup OpenGL
  788. glEnable(GL_MULTISAMPLE);
  789. // Setup default render target
  790. defaultRenderTarget.width = w;
  791. defaultRenderTarget.height = h;
  792. defaultRenderTarget.framebuffer = 0;
  793. // Set shadow map resolution
  794. shadowMapResolution = 4096;
  795. // Setup shadow map framebuffer
  796. glGenFramebuffers(1, &shadowMapFramebuffer);
  797. glBindFramebuffer(GL_FRAMEBUFFER, shadowMapFramebuffer);
  798. glGenTextures(1, &shadowMapDepthTextureID);
  799. glBindTexture(GL_TEXTURE_2D, shadowMapDepthTextureID);
  800. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadowMapResolution, shadowMapResolution, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
  801. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  802. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  803. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  804. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  805. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  806. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  807. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMapDepthTextureID, 0);
  808. glDrawBuffer(GL_NONE);
  809. glReadBuffer(GL_NONE);
  810. glBindTexture(GL_TEXTURE_2D, 0);
  811. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  812. // Setup shadow map render target
  813. shadowMapRenderTarget.width = shadowMapResolution;
  814. shadowMapRenderTarget.height = shadowMapResolution;
  815. shadowMapRenderTarget.framebuffer = shadowMapFramebuffer;
  816. // Setup shadow map depth texture
  817. shadowMapDepthTexture.setTextureID(shadowMapDepthTextureID);
  818. shadowMapDepthTexture.setWidth(shadowMapResolution);
  819. shadowMapDepthTexture.setHeight(shadowMapResolution);
  820. // Setup silhouette framebuffer
  821. glGenTextures(1, &silhouetteRenderTarget.texture);
  822. glBindTexture(GL_TEXTURE_2D, silhouetteRenderTarget.texture);
  823. glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
  824. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  825. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  826. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  827. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  828. glGenFramebuffers(1, &silhouetteRenderTarget.framebuffer);
  829. glBindFramebuffer(GL_FRAMEBUFFER, silhouetteRenderTarget.framebuffer);
  830. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, silhouetteRenderTarget.texture, 0);
  831. glDrawBuffer(GL_COLOR_ATTACHMENT0);
  832. glReadBuffer(GL_NONE);
  833. glBindTexture(GL_TEXTURE_2D, 0);
  834. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  835. // Setup silhouette render target
  836. silhouetteRenderTarget.width = w;
  837. silhouetteRenderTarget.height = h;
  838. // Setup shadow map render pass
  839. shadowMapPass = new ShadowMapRenderPass(resourceManager);
  840. shadowMapPass->setRenderTarget(&shadowMapRenderTarget);
  841. shadowMapPass->setViewCamera(&camera);
  842. shadowMapPass->setLightCamera(&sunlightCamera);
  843. // Setup shadow map compositor
  844. shadowMapCompositor.addPass(shadowMapPass);
  845. shadowMapCompositor.load(nullptr);
  846. // Setup clear render pass
  847. clearPass = new ClearRenderPass();
  848. clearPass->setRenderTarget(&defaultRenderTarget);
  849. clearPass->setClear(true, true, false);
  850. clearPass->setClearColor(Vector4(0.0f));
  851. clearPass->setClearDepth(1.0f);
  852. // Setup sky render pass
  853. skyPass = new SkyRenderPass(resourceManager);
  854. skyPass->setRenderTarget(&defaultRenderTarget);
  855. // Setup lighting pass
  856. lightingPass = new LightingRenderPass(resourceManager);
  857. lightingPass->setRenderTarget(&defaultRenderTarget);
  858. lightingPass->setShadowMapPass(shadowMapPass);
  859. lightingPass->setShadowMap(&shadowMapDepthTexture);
  860. // Setup clear silhouette pass
  861. clearSilhouettePass = new ClearRenderPass();
  862. clearSilhouettePass->setRenderTarget(&silhouetteRenderTarget);
  863. clearSilhouettePass->setClear(true, false, false);
  864. clearSilhouettePass->setClearColor(Vector4(0.0f));
  865. // Setup silhouette pass
  866. silhouettePass = new SilhouetteRenderPass(resourceManager);
  867. silhouettePass->setRenderTarget(&silhouetteRenderTarget);
  868. // Setup final pass
  869. finalPass = new FinalRenderPass(resourceManager);
  870. finalPass->setRenderTarget(&defaultRenderTarget);
  871. finalPass->setSilhouetteRenderTarget(&silhouetteRenderTarget);
  872. // Setup default compositor
  873. defaultCompositor.addPass(clearPass);
  874. defaultCompositor.addPass(skyPass);
  875. defaultCompositor.addPass(lightingPass);
  876. defaultCompositor.addPass(clearSilhouettePass);
  877. defaultCompositor.addPass(silhouettePass);
  878. //defaultCompositor.addPass(finalPass);
  879. defaultCompositor.load(nullptr);
  880. // Setup UI render pass
  881. uiPass = new UIRenderPass(resourceManager);
  882. uiPass->setRenderTarget(&defaultRenderTarget);
  883. // Setup UI compositor
  884. uiCompositor.addPass(uiPass);
  885. uiCompositor.load(nullptr);
  886. // Create scenes
  887. worldScene = new Scene(&stepInterpolator);
  888. uiScene = new Scene(&stepInterpolator);
  889. // Setup camera
  890. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  891. camera.lookAt(Vector3(0.0f, 4.0f, 2.0f), Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f));
  892. camera.setCompositor(&defaultCompositor);
  893. camera.setCompositeIndex(1);
  894. worldScene->addObject(&camera);
  895. // Setup sun
  896. sunlight.setDirection(Vector3(0, -1, 0));
  897. setTimeOfDay(11.0f);
  898. worldScene->addObject(&sunlight);
  899. // Setup sunlight camera
  900. sunlightCamera.setOrthographic(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
  901. sunlightCamera.setCompositor(&shadowMapCompositor);
  902. sunlightCamera.setCompositeIndex(0);
  903. sunlightCamera.setCullingEnabled(true);
  904. sunlightCamera.setCullingMask(&camera.getViewFrustum());
  905. worldScene->addObject(&sunlightCamera);
  906. }
  907. void Game::setupUI()
  908. {
  909. // Get DPI and convert font size to pixels
  910. const Display* display = deviceManager->getDisplays()->front();
  911. dpi = display->getDPI();
  912. fontSizePX = (*fontSize) * (1.0f / 96.0f) * dpi;
  913. logger->log("Detected display DPI as " + std::to_string(dpi) + ".");
  914. logger->log("Font size = " + std::to_string(*fontSize) + " PT = " + std::to_string(fontSizePX) + " PX.");
  915. // Load fonts
  916. loadFonts();
  917. // Load splash screen texture
  918. splashTexture = resourceManager->load<Texture2D>("splash.png");
  919. // Load HUD texture
  920. hudSpriteSheetTexture = resourceManager->load<Texture2D>("hud.png");
  921. // Read texture atlas file
  922. StringTable* atlasTable = resourceManager->load<StringTable>("hud-atlas.csv");
  923. // Build texture atlas
  924. for (int row = 0; row < atlasTable->size(); ++row)
  925. {
  926. std::stringstream ss;
  927. float x;
  928. float y;
  929. float w;
  930. float h;
  931. ss << (*atlasTable)[row][1];
  932. ss >> x;
  933. ss.str(std::string());
  934. ss.clear();
  935. ss << (*atlasTable)[row][2];
  936. ss >> y;
  937. ss.str(std::string());
  938. ss.clear();
  939. ss << (*atlasTable)[row][3];
  940. ss >> w;
  941. ss.str(std::string());
  942. ss.clear();
  943. ss << (*atlasTable)[row][4];
  944. ss >> h;
  945. ss.str(std::string());
  946. y = static_cast<float>(hudSpriteSheetTexture->getHeight()) - y - h;
  947. x = (int)(x + 0.5f);
  948. y = (int)(y + 0.5f);
  949. w = (int)(w + 0.5f);
  950. h = (int)(h + 0.5f);
  951. hudTextureAtlas.insert((*atlasTable)[row][0], Rect(Vector2(x, y), Vector2(x + w, y + h)));
  952. }
  953. // Setup UI batching
  954. uiBatch = new BillboardBatch();
  955. uiBatch->resize(1024);
  956. uiBatcher = new UIBatcher();
  957. // Setup root UI element
  958. uiRootElement = new UIContainer();
  959. eventDispatcher.subscribe<MouseMovedEvent>(uiRootElement);
  960. eventDispatcher.subscribe<MouseButtonPressedEvent>(uiRootElement);
  961. eventDispatcher.subscribe<MouseButtonReleasedEvent>(uiRootElement);
  962. // Create splash screen background element
  963. splashBackgroundImage = new UIImage();
  964. splashBackgroundImage->setLayerOffset(-1);
  965. splashBackgroundImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  966. splashBackgroundImage->setVisible(false);
  967. uiRootElement->addChild(splashBackgroundImage);
  968. // Create splash screen element
  969. splashImage = new UIImage();
  970. splashImage->setTexture(splashTexture);
  971. splashImage->setVisible(false);
  972. uiRootElement->addChild(splashImage);
  973. Rect hudTextureAtlasBounds(Vector2(0), Vector2(hudSpriteSheetTexture->getWidth(), hudSpriteSheetTexture->getHeight()));
  974. auto normalizeTextureBounds = [](const Rect& texture, const Rect& atlas)
  975. {
  976. Vector2 atlasDimensions = Vector2(atlas.getWidth(), atlas.getHeight());
  977. return Rect(texture.getMin() / atlasDimensions, texture.getMax() / atlasDimensions);
  978. };
  979. // Create HUD elements
  980. hudContainer = new UIContainer();
  981. hudContainer->setVisible(false);
  982. uiRootElement->addChild(hudContainer);
  983. toolIndicatorBGImage = new UIImage();
  984. toolIndicatorBGImage->setTexture(hudSpriteSheetTexture);
  985. toolIndicatorBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds));
  986. hudContainer->addChild(toolIndicatorBGImage);
  987. toolIndicatorsBounds = new Rect[8];
  988. toolIndicatorsBounds[0] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-brush"), hudTextureAtlasBounds);
  989. toolIndicatorsBounds[1] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-spade"), hudTextureAtlasBounds);
  990. toolIndicatorsBounds[2] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-lens"), hudTextureAtlasBounds);
  991. toolIndicatorsBounds[3] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-test-tube"), hudTextureAtlasBounds);
  992. toolIndicatorsBounds[4] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-forceps"), hudTextureAtlasBounds);
  993. toolIndicatorsBounds[5] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  994. toolIndicatorsBounds[6] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  995. toolIndicatorsBounds[7] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  996. toolIndicatorIconImage = new UIImage();
  997. toolIndicatorIconImage->setTexture(hudSpriteSheetTexture);
  998. toolIndicatorIconImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  999. toolIndicatorBGImage->addChild(toolIndicatorIconImage);
  1000. buttonContainer = new UIContainer();
  1001. hudContainer->addChild(buttonContainer);
  1002. playButtonBGImage = new UIImage();
  1003. playButtonBGImage->setTexture(hudSpriteSheetTexture);
  1004. playButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  1005. //buttonContainer->addChild(playButtonBGImage);
  1006. pauseButtonBGImage = new UIImage();
  1007. pauseButtonBGImage->setTexture(hudSpriteSheetTexture);
  1008. pauseButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  1009. //buttonContainer->addChild(pauseButtonBGImage);
  1010. fastForwardButtonBGImage = new UIImage();
  1011. fastForwardButtonBGImage->setTexture(hudSpriteSheetTexture);
  1012. fastForwardButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  1013. //buttonContainer->addChild(fastForwardButtonBGImage);
  1014. playButtonImage = new UIImage();
  1015. playButtonImage->setTexture(hudSpriteSheetTexture);
  1016. playButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-play"), hudTextureAtlasBounds));
  1017. //buttonContainer->addChild(playButtonImage);
  1018. fastForwardButtonImage = new UIImage();
  1019. fastForwardButtonImage->setTexture(hudSpriteSheetTexture);
  1020. fastForwardButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-fast-forward-2x"), hudTextureAtlasBounds));
  1021. //buttonContainer->addChild(fastForwardButtonImage);
  1022. pauseButtonImage = new UIImage();
  1023. pauseButtonImage->setTexture(hudSpriteSheetTexture);
  1024. pauseButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-pause"), hudTextureAtlasBounds));
  1025. //buttonContainer->addChild(pauseButtonImage);
  1026. radialMenuContainer = new UIContainer();
  1027. radialMenuContainer->setVisible(false);
  1028. uiRootElement->addChild(radialMenuContainer);
  1029. radialMenuBackgroundImage = new UIImage();
  1030. radialMenuBackgroundImage->setTintColor(Vector4(Vector3(0.0f), 0.25f));
  1031. radialMenuContainer->addChild(radialMenuBackgroundImage);
  1032. radialMenuImage = new UIImage();
  1033. radialMenuImage->setTexture(hudSpriteSheetTexture);
  1034. radialMenuImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu"), hudTextureAtlasBounds));
  1035. radialMenuContainer->addChild(radialMenuImage);
  1036. radialMenuSelectorImage = new UIImage();
  1037. radialMenuSelectorImage->setTexture(hudSpriteSheetTexture);
  1038. radialMenuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu-selector"), hudTextureAtlasBounds));
  1039. radialMenuContainer->addChild(radialMenuSelectorImage);
  1040. toolIconBrushImage = new UIImage();
  1041. toolIconBrushImage->setTexture(hudSpriteSheetTexture);
  1042. toolIconBrushImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  1043. radialMenuImage->addChild(toolIconBrushImage);
  1044. toolIconLensImage = new UIImage();
  1045. toolIconLensImage->setTexture(hudSpriteSheetTexture);
  1046. toolIconLensImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-lens"), hudTextureAtlasBounds));
  1047. radialMenuImage->addChild(toolIconLensImage);
  1048. toolIconForcepsImage = new UIImage();
  1049. toolIconForcepsImage->setTexture(hudSpriteSheetTexture);
  1050. toolIconForcepsImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-forceps"), hudTextureAtlasBounds));
  1051. radialMenuImage->addChild(toolIconForcepsImage);
  1052. toolIconSpadeImage = new UIImage();
  1053. toolIconSpadeImage->setTexture(hudSpriteSheetTexture);
  1054. toolIconSpadeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-spade"), hudTextureAtlasBounds));
  1055. //radialMenuImage->addChild(toolIconSpadeImage);
  1056. toolIconCameraImage = new UIImage();
  1057. toolIconCameraImage->setTexture(hudSpriteSheetTexture);
  1058. toolIconCameraImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-camera"), hudTextureAtlasBounds));
  1059. radialMenuImage->addChild(toolIconCameraImage);
  1060. toolIconMicrochipImage = new UIImage();
  1061. toolIconMicrochipImage->setTexture(hudSpriteSheetTexture);
  1062. toolIconMicrochipImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-microchip"), hudTextureAtlasBounds));
  1063. radialMenuImage->addChild(toolIconMicrochipImage);
  1064. toolIconTestTubeImage = new UIImage();
  1065. toolIconTestTubeImage->setTexture(hudSpriteSheetTexture);
  1066. toolIconTestTubeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-test-tube"), hudTextureAtlasBounds));
  1067. //radialMenuImage->addChild(toolIconTestTubeImage);
  1068. antTag = new UIContainer();
  1069. antTag->setLayerOffset(-10);
  1070. antTag->setVisible(false);
  1071. uiRootElement->addChild(antTag);
  1072. antLabelContainer = new UIContainer();
  1073. antTag->addChild(antLabelContainer);
  1074. antLabelTL = new UIImage();
  1075. antLabelTR = new UIImage();
  1076. antLabelBL = new UIImage();
  1077. antLabelBR = new UIImage();
  1078. antLabelCC = new UIImage();
  1079. antLabelCT = new UIImage();
  1080. antLabelCB = new UIImage();
  1081. antLabelCL = new UIImage();
  1082. antLabelCR = new UIImage();
  1083. antLabelTL->setTexture(hudSpriteSheetTexture);
  1084. antLabelTR->setTexture(hudSpriteSheetTexture);
  1085. antLabelBL->setTexture(hudSpriteSheetTexture);
  1086. antLabelBR->setTexture(hudSpriteSheetTexture);
  1087. antLabelCC->setTexture(hudSpriteSheetTexture);
  1088. antLabelCT->setTexture(hudSpriteSheetTexture);
  1089. antLabelCB->setTexture(hudSpriteSheetTexture);
  1090. antLabelCL->setTexture(hudSpriteSheetTexture);
  1091. antLabelCR->setTexture(hudSpriteSheetTexture);
  1092. Rect labelTLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tl"), hudTextureAtlasBounds);
  1093. Rect labelTRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tr"), hudTextureAtlasBounds);
  1094. Rect labelBLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-bl"), hudTextureAtlasBounds);
  1095. Rect labelBRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-br"), hudTextureAtlasBounds);
  1096. Rect labelCCBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cc"), hudTextureAtlasBounds);
  1097. Rect labelCTBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-ct"), hudTextureAtlasBounds);
  1098. Rect labelCBBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cb"), hudTextureAtlasBounds);
  1099. Rect labelCLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cl"), hudTextureAtlasBounds);
  1100. Rect labelCRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cr"), hudTextureAtlasBounds);
  1101. Vector2 labelTLMin = labelTLBounds.getMin();
  1102. Vector2 labelTRMin = labelTRBounds.getMin();
  1103. Vector2 labelBLMin = labelBLBounds.getMin();
  1104. Vector2 labelBRMin = labelBRBounds.getMin();
  1105. Vector2 labelCCMin = labelCCBounds.getMin();
  1106. Vector2 labelCTMin = labelCTBounds.getMin();
  1107. Vector2 labelCBMin = labelCBBounds.getMin();
  1108. Vector2 labelCLMin = labelCLBounds.getMin();
  1109. Vector2 labelCRMin = labelCRBounds.getMin();
  1110. Vector2 labelTLMax = labelTLBounds.getMax();
  1111. Vector2 labelTRMax = labelTRBounds.getMax();
  1112. Vector2 labelBLMax = labelBLBounds.getMax();
  1113. Vector2 labelBRMax = labelBRBounds.getMax();
  1114. Vector2 labelCCMax = labelCCBounds.getMax();
  1115. Vector2 labelCTMax = labelCTBounds.getMax();
  1116. Vector2 labelCBMax = labelCBBounds.getMax();
  1117. Vector2 labelCLMax = labelCLBounds.getMax();
  1118. Vector2 labelCRMax = labelCRBounds.getMax();
  1119. antLabelTL->setTextureBounds(labelTLBounds);
  1120. antLabelTR->setTextureBounds(labelTRBounds);
  1121. antLabelBL->setTextureBounds(labelBLBounds);
  1122. antLabelBR->setTextureBounds(labelBRBounds);
  1123. antLabelCC->setTextureBounds(labelCCBounds);
  1124. antLabelCT->setTextureBounds(labelCTBounds);
  1125. antLabelCB->setTextureBounds(labelCBBounds);
  1126. antLabelCL->setTextureBounds(labelCLBounds);
  1127. antLabelCR->setTextureBounds(labelCRBounds);
  1128. antLabelContainer->addChild(antLabelTL);
  1129. antLabelContainer->addChild(antLabelTR);
  1130. antLabelContainer->addChild(antLabelBL);
  1131. antLabelContainer->addChild(antLabelBR);
  1132. antLabelContainer->addChild(antLabelCC);
  1133. antLabelContainer->addChild(antLabelCT);
  1134. antLabelContainer->addChild(antLabelCB);
  1135. antLabelContainer->addChild(antLabelCL);
  1136. antLabelContainer->addChild(antLabelCR);
  1137. antLabel = new UILabel();
  1138. antLabel->setFont(nullptr);
  1139. antLabel->setText("");
  1140. antLabel->setTintColor(Vector4(Vector3(0.0f), 1.0f));
  1141. antLabel->setLayerOffset(1);
  1142. antLabelContainer->addChild(antLabel);
  1143. fpsLabel = new UILabel();
  1144. fpsLabel->setFont(debugFont);
  1145. fpsLabel->setTintColor(Vector4(1, 1, 0, 1));
  1146. fpsLabel->setLayerOffset(50);
  1147. fpsLabel->setAnchor(Anchor::TOP_LEFT);
  1148. uiRootElement->addChild(fpsLabel);
  1149. antPin = new UIImage();
  1150. antPin->setTexture(hudSpriteSheetTexture);
  1151. antPin->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin"), hudTextureAtlasBounds));
  1152. antTag->addChild(antPin);
  1153. antLabelPinHole = new UIImage();
  1154. antLabelPinHole->setTexture(hudSpriteSheetTexture);
  1155. antLabelPinHole->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin-hole"), hudTextureAtlasBounds));
  1156. antLabelContainer->addChild(antLabelPinHole);
  1157. // Construct box selection
  1158. boxSelectionImageBackground = new UIImage();
  1159. boxSelectionImageBackground->setAnchor(Anchor::CENTER);
  1160. boxSelectionImageTop = new UIImage();
  1161. boxSelectionImageTop->setAnchor(Anchor::TOP_LEFT);
  1162. boxSelectionImageBottom = new UIImage();
  1163. boxSelectionImageBottom->setAnchor(Anchor::BOTTOM_LEFT);
  1164. boxSelectionImageLeft = new UIImage();
  1165. boxSelectionImageLeft->setAnchor(Anchor::TOP_LEFT);
  1166. boxSelectionImageRight = new UIImage();
  1167. boxSelectionImageRight->setAnchor(Anchor::TOP_RIGHT);
  1168. boxSelectionContainer = new UIContainer();
  1169. boxSelectionContainer->setLayerOffset(80);
  1170. boxSelectionContainer->addChild(boxSelectionImageBackground);
  1171. boxSelectionContainer->addChild(boxSelectionImageTop);
  1172. boxSelectionContainer->addChild(boxSelectionImageBottom);
  1173. boxSelectionContainer->addChild(boxSelectionImageLeft);
  1174. boxSelectionContainer->addChild(boxSelectionImageRight);
  1175. boxSelectionContainer->setVisible(false);
  1176. uiRootElement->addChild(boxSelectionContainer);
  1177. boxSelectionImageBackground->setTintColor(Vector4(1.0f, 1.0f, 1.0f, 0.5f));
  1178. boxSelectionContainer->setTintColor(Vector4(1.0f, 0.0f, 0.0f, 1.0f));
  1179. boxSelectionBorderWidth = 2.0f;
  1180. cameraGridColor = Vector4(1, 1, 1, 0.5f);
  1181. cameraReticleColor = Vector4(1, 1, 1, 0.75f);
  1182. cameraGridY0Image = new UIImage();
  1183. cameraGridY0Image->setAnchor(Vector2(0.5f, (1.0f / 3.0f)));
  1184. cameraGridY0Image->setTintColor(cameraGridColor);
  1185. cameraGridY1Image = new UIImage();
  1186. cameraGridY1Image->setAnchor(Vector2(0.5f, (2.0f / 3.0f)));
  1187. cameraGridY1Image->setTintColor(cameraGridColor);
  1188. cameraGridX0Image = new UIImage();
  1189. cameraGridX0Image->setAnchor(Vector2((1.0f / 3.0f), 0.5f));
  1190. cameraGridX0Image->setTintColor(cameraGridColor);
  1191. cameraGridX1Image = new UIImage();
  1192. cameraGridX1Image->setAnchor(Vector2((2.0f / 3.0f), 0.5f));
  1193. cameraGridX1Image->setTintColor(cameraGridColor);
  1194. cameraReticleImage = new UIImage();
  1195. cameraReticleImage->setAnchor(Anchor::CENTER);
  1196. cameraReticleImage->setTintColor(cameraReticleColor);
  1197. cameraReticleImage->setTexture(hudSpriteSheetTexture);
  1198. cameraReticleImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("camera-reticle"), hudTextureAtlasBounds));
  1199. cameraGridContainer = new UIContainer();
  1200. cameraGridContainer->addChild(cameraGridY0Image);
  1201. cameraGridContainer->addChild(cameraGridY1Image);
  1202. cameraGridContainer->addChild(cameraGridX0Image);
  1203. cameraGridContainer->addChild(cameraGridX1Image);
  1204. cameraGridContainer->addChild(cameraReticleImage);
  1205. cameraGridContainer->setVisible(false);
  1206. uiRootElement->addChild(cameraGridContainer);
  1207. cameraFlashImage = new UIImage();
  1208. cameraFlashImage->setLayerOffset(99);
  1209. cameraFlashImage->setTintColor(Vector4(1.0f));
  1210. cameraFlashImage->setVisible(false);
  1211. uiRootElement->addChild(cameraFlashImage);
  1212. blackoutImage = new UIImage();
  1213. blackoutImage->setLayerOffset(98);
  1214. blackoutImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1215. blackoutImage->setVisible(false);
  1216. uiRootElement->addChild(blackoutImage);
  1217. languageSelectBGImage = new UIImage();
  1218. languageSelectBGImage->setLayerOffset(-1);
  1219. languageSelectBGImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1220. languageSelectBGImage->setVisible(true);
  1221. standardMenuActiveColor = Vector4(Vector3(0.2f), 1.0f);
  1222. standardMenuInactiveColor = Vector4(Vector3(0.2f), 0.5f);
  1223. languageMenuActiveColor = Vector4(Vector3(1.0f), 1.0f);
  1224. languageMenuInactiveColor = Vector4(Vector3(1.0f), 0.5f);
  1225. menuItemActiveColor = standardMenuActiveColor;
  1226. menuItemInactiveColor = standardMenuInactiveColor;
  1227. menuItemIndex = -1;
  1228. currentMenu = nullptr;
  1229. currentMenuItem = nullptr;
  1230. previousMenuItem = nullptr;
  1231. previousMenu = nullptr;
  1232. menuSelectorImage = new UIImage();
  1233. menuSelectorImage->setAnchor(Anchor::TOP_LEFT);
  1234. menuSelectorImage->setTexture(hudSpriteSheetTexture);
  1235. menuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("menu-selector"), hudTextureAtlasBounds));
  1236. menuSelectorImage->setTintColor(menuItemActiveColor);
  1237. // Build main menu
  1238. mainMenu = new Menu();
  1239. mainMenuContinueItem = mainMenu->addItem();
  1240. mainMenuNewGameItem = mainMenu->addItem();
  1241. mainMenuColoniesItem = mainMenu->addItem();
  1242. mainMenuSettingsItem = mainMenu->addItem();
  1243. mainMenuQuitItem = mainMenu->addItem();
  1244. // Build settings menu
  1245. settingsMenu = new Menu();
  1246. settingsMenuControlsItem = settingsMenu->addItem();
  1247. settingsMenuFullscreenItem = settingsMenu->addItem();
  1248. settingsMenuVSyncItem = settingsMenu->addItem();
  1249. settingsMenuLanguageItem = settingsMenu->addItem();
  1250. settingsMenuBackItem = settingsMenu->addItem();
  1251. // Build controls menu
  1252. controlsMenu = new Menu();
  1253. controlsMenuMoveForwardItem = controlsMenu->addItem();
  1254. controlsMenuMoveLeftItem = controlsMenu->addItem();
  1255. controlsMenuMoveBackItem = controlsMenu->addItem();
  1256. controlsMenuMoveRightItem = controlsMenu->addItem();
  1257. controlsMenuChangeToolItem = controlsMenu->addItem();
  1258. controlsMenuUseToolItem = controlsMenu->addItem();
  1259. controlsMenuAdjustCameraItem = controlsMenu->addItem();
  1260. controlsMenuPauseItem = controlsMenu->addItem();
  1261. controlsMenuToggleFullscreenItem = controlsMenu->addItem();
  1262. controlsMenuTakeScreenshotItem = controlsMenu->addItem();
  1263. controlsMenuResetToDefaultItem = controlsMenu->addItem();
  1264. controlsMenuBackItem = controlsMenu->addItem();
  1265. // Build pause menu
  1266. pauseMenu = new Menu();
  1267. pauseMenuResumeItem = pauseMenu->addItem();
  1268. pauseMenuSettingsItem = pauseMenu->addItem();
  1269. pauseMenuMainMenuItem = pauseMenu->addItem();
  1270. pauseMenuQuitItem = pauseMenu->addItem();
  1271. // Build language menu
  1272. languageMenu = new Menu();
  1273. for (std::size_t i = 0; i < languageCount; ++i)
  1274. {
  1275. MenuItem* item = languageMenu->addItem();
  1276. item->setActivatedCallback
  1277. (
  1278. [this, i]()
  1279. {
  1280. changeLanguage(i);
  1281. languageSelected();
  1282. }
  1283. );
  1284. item->getContainer()->setTintColor(languageMenuInactiveColor);
  1285. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1286. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1287. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1288. languageMenuItems.push_back(item);
  1289. }
  1290. // Setup main menu callbacks
  1291. mainMenuContinueItem->setActivatedCallback(std::bind(&Game::continueGame, this));
  1292. mainMenuNewGameItem->setActivatedCallback(std::bind(&Game::newGame, this));
  1293. mainMenuSettingsItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1294. mainMenuQuitItem->setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1295. // Setup settings menu callbacks
  1296. settingsMenuControlsItem->setActivatedCallback(std::bind(&Game::openMenu, this, controlsMenu, 0));
  1297. settingsMenuFullscreenItem->setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1298. settingsMenuVSyncItem->setActivatedCallback(std::bind(&Game::toggleVSync, this));
  1299. settingsMenuLanguageItem->setActivatedCallback(std::bind(&Game::nextLanguage, this));
  1300. settingsMenuBackItem->setActivatedCallback(std::bind(&Game::openMenu, this, mainMenu, 3));
  1301. // Setup controls menu callbacks
  1302. controlsMenuMoveForwardItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveForwardControl));
  1303. controlsMenuMoveLeftItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveLeftControl));
  1304. controlsMenuMoveBackItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveBackControl));
  1305. controlsMenuMoveRightItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveRightControl));
  1306. controlsMenuChangeToolItem->setActivatedCallback(std::bind(&Game::remapControl, this, &changeToolControl));
  1307. controlsMenuUseToolItem->setActivatedCallback(std::bind(&Game::remapControl, this, &useToolControl));
  1308. controlsMenuAdjustCameraItem->setActivatedCallback(std::bind(&Game::remapControl, this, &adjustCameraControl));
  1309. controlsMenuPauseItem->setActivatedCallback(std::bind(&Game::remapControl, this, &pauseControl));
  1310. controlsMenuToggleFullscreenItem->setActivatedCallback(std::bind(&Game::remapControl, this, &toggleFullscreenControl));
  1311. controlsMenuTakeScreenshotItem->setActivatedCallback(std::bind(&Game::remapControl, this, &takeScreenshotControl));
  1312. controlsMenuResetToDefaultItem->setActivatedCallback(std::bind(&Game::resetControls, this));
  1313. controlsMenuBackItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1314. // Setup pause menu callbacks
  1315. pauseMenuResumeItem->setActivatedCallback(std::bind(&Game::togglePause, this));
  1316. pauseMenuSettingsItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1317. pauseMenuMainMenuItem->setActivatedCallback(std::bind(&Game::returnToMainMenu, this));
  1318. pauseMenuQuitItem->setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1319. // Setup standard callbacks for all menu items
  1320. for (std::size_t i = 0; i < mainMenu->getItems()->size(); ++i)
  1321. {
  1322. MenuItem* item = (*mainMenu->getItems())[i];
  1323. item->getContainer()->setTintColor(menuItemInactiveColor);
  1324. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1325. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1326. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1327. }
  1328. for (std::size_t i = 0; i < settingsMenu->getItems()->size(); ++i)
  1329. {
  1330. MenuItem* item = (*settingsMenu->getItems())[i];
  1331. item->getContainer()->setTintColor(menuItemInactiveColor);
  1332. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1333. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1334. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1335. }
  1336. for (std::size_t i = 0; i < controlsMenu->getItems()->size(); ++i)
  1337. {
  1338. MenuItem* item = (*controlsMenu->getItems())[i];
  1339. item->getContainer()->setTintColor(menuItemInactiveColor);
  1340. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1341. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1342. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1343. }
  1344. for (std::size_t i = 0; i < pauseMenu->getItems()->size(); ++i)
  1345. {
  1346. MenuItem* item = (*pauseMenu->getItems())[i];
  1347. item->getContainer()->setTintColor(menuItemInactiveColor);
  1348. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1349. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1350. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1351. }
  1352. // Set fonts for all menus
  1353. mainMenu->setFonts(menuFont);
  1354. settingsMenu->setFonts(menuFont);
  1355. controlsMenu->setFonts(menuFont);
  1356. pauseMenu->setFonts(menuFont);
  1357. AnimationChannel<float>* channel;
  1358. // Setup splash fade-in animation
  1359. splashFadeInClip.setInterpolator(easeOutCubic<float>);
  1360. channel = splashFadeInClip.addChannel(0);
  1361. channel->insertKeyframe(0.0f, 0.0f);
  1362. channel->insertKeyframe(1.0f, 1.0f);
  1363. channel->insertKeyframe(3.0f, 1.0f);
  1364. splashFadeInAnimation.setClip(&splashFadeInClip);
  1365. splashFadeInAnimation.setTimeFrame(splashFadeInClip.getTimeFrame());
  1366. splashFadeInAnimation.setAnimateCallback
  1367. (
  1368. [this](std::size_t id, float opacity)
  1369. {
  1370. Vector3 color = Vector3(splashImage->getTintColor());
  1371. splashImage->setTintColor(Vector4(color, opacity));
  1372. }
  1373. );
  1374. splashFadeInAnimation.setEndCallback
  1375. (
  1376. [this]()
  1377. {
  1378. splashFadeOutAnimation.rewind();
  1379. splashFadeOutAnimation.play();
  1380. }
  1381. );
  1382. // Setup splash fade-out animation
  1383. splashFadeOutClip.setInterpolator(easeOutCubic<float>);
  1384. channel = splashFadeOutClip.addChannel(0);
  1385. channel->insertKeyframe(0.0f, 1.0f);
  1386. channel->insertKeyframe(1.0f, 0.0f);
  1387. channel->insertKeyframe(1.5f, 0.0f);
  1388. splashFadeOutAnimation.setClip(&splashFadeOutClip);
  1389. splashFadeOutAnimation.setTimeFrame(splashFadeOutClip.getTimeFrame());
  1390. splashFadeOutAnimation.setAnimateCallback
  1391. (
  1392. [this](std::size_t id, float opacity)
  1393. {
  1394. Vector3 color = Vector3(splashImage->getTintColor());
  1395. splashImage->setTintColor(Vector4(color, opacity));
  1396. }
  1397. );
  1398. splashFadeOutAnimation.setEndCallback(std::bind(&StateMachine::changeState, this, &titleState));
  1399. // Ant-hill zoom animation
  1400. antHillZoomClip.setInterpolator(easeOutCubic<float>);
  1401. channel = antHillZoomClip.addChannel(0);
  1402. channel->insertKeyframe(0.0f, 0.0f);
  1403. channel->insertKeyframe(3.0f, 40.0f);
  1404. antHillZoomAnimation.setClip(&antHillZoomClip);
  1405. antHillZoomAnimation.setTimeFrame(antHillZoomClip.getTimeFrame());
  1406. antHillZoomAnimation.setAnimateCallback
  1407. (
  1408. [this](std::size_t id, float distance)
  1409. {
  1410. orbitCam->setFocalDistance(distance);
  1411. orbitCam->setTargetFocalDistance(distance);
  1412. }
  1413. );
  1414. // Menu fade animation
  1415. menuFadeInClip.setInterpolator(easeOutCubic<float>);
  1416. channel = menuFadeInClip.addChannel(0);
  1417. channel->insertKeyframe(0.0f, 0.0f);
  1418. channel->insertKeyframe(3.0f, 0.0f);
  1419. channel->insertKeyframe(5.0f, 1.0f);
  1420. menuFadeOutClip.setInterpolator(easeOutCubic<float>);
  1421. channel = menuFadeOutClip.addChannel(0);
  1422. channel->insertKeyframe(0.0f, 1.0f);
  1423. channel->insertKeyframe(0.125f, 0.0f);
  1424. menuFadeAnimation.setClip(&menuFadeInClip);
  1425. menuFadeAnimation.setTimeFrame(menuFadeInClip.getTimeFrame());
  1426. menuFadeAnimation.setAnimateCallback
  1427. (
  1428. [this](std::size_t id, float opacity)
  1429. {
  1430. currentMenu->getContainer()->setTintColor(Vector4(opacity));
  1431. }
  1432. );
  1433. animator.addAnimation(&menuFadeAnimation);
  1434. // Menu selector animation
  1435. menuSelectorSlideClip.setInterpolator(easeOutCubic<float>);
  1436. menuSelectorSlideAnimation.setClip(&menuSelectorSlideClip);
  1437. menuSelectorSlideAnimation.setAnimateCallback
  1438. (
  1439. [this](std::size_t id, float offset)
  1440. {
  1441. Vector2 translation = menuSelectorImage->getTranslation();
  1442. translation.y = offset;
  1443. menuSelectorImage->setTranslation(translation);
  1444. }
  1445. );
  1446. animator.addAnimation(&menuSelectorSlideAnimation);
  1447. // Menu item select animation
  1448. menuItemSelectClip.setInterpolator(easeOutCubic<Vector4>);
  1449. menuItemSelectAnimation.setClip(&menuItemSelectClip);
  1450. menuItemSelectAnimation.setAnimateCallback
  1451. (
  1452. [this](std::size_t id, const Vector4& color)
  1453. {
  1454. currentMenuItem->getContainer()->setTintColor(color);
  1455. }
  1456. );
  1457. // Menu item deselect animation
  1458. menuItemDeselectClip.setInterpolator(easeOutCubic<Vector4>);
  1459. menuItemDeselectAnimation.setClip(&menuItemDeselectClip);
  1460. menuItemDeselectAnimation.setAnimateCallback
  1461. (
  1462. [this](std::size_t id, const Vector4& color)
  1463. {
  1464. previousMenuItem->getContainer()->setTintColor(color);
  1465. }
  1466. );
  1467. animator.addAnimation(&menuItemSelectAnimation);
  1468. animator.addAnimation(&menuItemDeselectAnimation);
  1469. // Construct fade-in animation clip
  1470. fadeInClip.setInterpolator(easeOutCubic<float>);
  1471. channel = fadeInClip.addChannel(0);
  1472. channel->insertKeyframe(0.0f, 1.0f);
  1473. channel->insertKeyframe(1.0f, 0.0f);
  1474. // Construct fade-out animation clip
  1475. fadeOutClip.setInterpolator(easeOutCubic<float>);
  1476. channel = fadeOutClip.addChannel(0);
  1477. channel->insertKeyframe(0.0f, 0.0f);
  1478. channel->insertKeyframe(1.0f, 1.0f);
  1479. // Setup fade-in animation callbacks
  1480. fadeInAnimation.setAnimateCallback
  1481. (
  1482. [this](std::size_t id, float opacity)
  1483. {
  1484. Vector3 color = Vector3(blackoutImage->getTintColor());
  1485. blackoutImage->setTintColor(Vector4(color, opacity));
  1486. }
  1487. );
  1488. fadeInAnimation.setEndCallback
  1489. (
  1490. [this]()
  1491. {
  1492. blackoutImage->setVisible(false);
  1493. if (fadeInEndCallback != nullptr)
  1494. {
  1495. fadeInEndCallback();
  1496. }
  1497. }
  1498. );
  1499. // Setup fade-out animation callbacks
  1500. fadeOutAnimation.setAnimateCallback
  1501. (
  1502. [this](std::size_t id, float opacity)
  1503. {
  1504. Vector3 color = Vector3(blackoutImage->getTintColor());
  1505. blackoutImage->setTintColor(Vector4(color, opacity));
  1506. }
  1507. );
  1508. fadeOutAnimation.setEndCallback
  1509. (
  1510. [this]()
  1511. {
  1512. blackoutImage->setVisible(false);
  1513. if (fadeOutEndCallback != nullptr)
  1514. {
  1515. fadeOutEndCallback();
  1516. }
  1517. }
  1518. );
  1519. animator.addAnimation(&fadeInAnimation);
  1520. animator.addAnimation(&fadeOutAnimation);
  1521. // Construct camera flash animation clip
  1522. cameraFlashClip.setInterpolator(easeOutQuad<float>);
  1523. channel = cameraFlashClip.addChannel(0);
  1524. channel->insertKeyframe(0.0f, 1.0f);
  1525. channel->insertKeyframe(1.0f, 0.0f);
  1526. // Setup camera flash animation
  1527. float flashDuration = 0.5f;
  1528. cameraFlashAnimation.setSpeed(1.0f / flashDuration);
  1529. cameraFlashAnimation.setLoop(false);
  1530. cameraFlashAnimation.setClip(&cameraFlashClip);
  1531. cameraFlashAnimation.setTimeFrame(cameraFlashClip.getTimeFrame());
  1532. cameraFlashAnimation.setAnimateCallback
  1533. (
  1534. [this](std::size_t id, float opacity)
  1535. {
  1536. cameraFlashImage->setTintColor(Vector4(Vector3(1.0f), opacity));
  1537. }
  1538. );
  1539. cameraFlashAnimation.setStartCallback
  1540. (
  1541. [this]()
  1542. {
  1543. cameraFlashImage->setVisible(true);
  1544. cameraFlashImage->setTintColor(Vector4(1.0f));
  1545. cameraFlashImage->resetTweens();
  1546. }
  1547. );
  1548. cameraFlashAnimation.setEndCallback
  1549. (
  1550. [this]()
  1551. {
  1552. cameraFlashImage->setVisible(false);
  1553. }
  1554. );
  1555. animator.addAnimation(&cameraFlashAnimation);
  1556. // Setup UI scene
  1557. uiScene->addObject(uiBatch);
  1558. uiScene->addObject(&uiCamera);
  1559. // Setup UI camera
  1560. uiCamera.lookAt(Vector3(0), Vector3(0, 0, -1), Vector3(0, 1, 0));
  1561. uiCamera.resetTweens();
  1562. uiCamera.setCompositor(&uiCompositor);
  1563. uiCamera.setCompositeIndex(0);
  1564. uiCamera.setCullingEnabled(false);
  1565. restringUI();
  1566. resizeUI(w, h);
  1567. }
  1568. void Game::setupControls()
  1569. {
  1570. // Get keyboard and mouse
  1571. keyboard = deviceManager->getKeyboards()->front();
  1572. mouse = deviceManager->getMice()->front();
  1573. // Build the master control set
  1574. controls.addControl(&exitControl);
  1575. controls.addControl(&toggleFullscreenControl);
  1576. controls.addControl(&takeScreenshotControl);
  1577. controls.addControl(&menuUpControl);
  1578. controls.addControl(&menuDownControl);
  1579. controls.addControl(&menuLeftControl);
  1580. controls.addControl(&menuRightControl);
  1581. controls.addControl(&menuActivateControl);
  1582. controls.addControl(&menuBackControl);
  1583. controls.addControl(&moveForwardControl);
  1584. controls.addControl(&moveBackControl);
  1585. controls.addControl(&moveLeftControl);
  1586. controls.addControl(&moveRightControl);
  1587. controls.addControl(&zoomInControl);
  1588. controls.addControl(&zoomOutControl);
  1589. controls.addControl(&orbitCCWControl);
  1590. controls.addControl(&orbitCWControl);
  1591. controls.addControl(&adjustCameraControl);
  1592. controls.addControl(&dragCameraControl);
  1593. controls.addControl(&pauseControl);
  1594. controls.addControl(&changeToolControl);
  1595. controls.addControl(&useToolControl);
  1596. controls.addControl(&toggleEditModeControl);
  1597. // Build the system control set
  1598. systemControls.addControl(&exitControl);
  1599. systemControls.addControl(&toggleFullscreenControl);
  1600. systemControls.addControl(&takeScreenshotControl);
  1601. // Build the menu control set
  1602. menuControls.addControl(&menuUpControl);
  1603. menuControls.addControl(&menuDownControl);
  1604. menuControls.addControl(&menuLeftControl);
  1605. menuControls.addControl(&menuRightControl);
  1606. menuControls.addControl(&menuActivateControl);
  1607. menuControls.addControl(&menuBackControl);
  1608. // Build the camera control set
  1609. cameraControls.addControl(&moveForwardControl);
  1610. cameraControls.addControl(&moveBackControl);
  1611. cameraControls.addControl(&moveLeftControl);
  1612. cameraControls.addControl(&moveRightControl);
  1613. cameraControls.addControl(&zoomInControl);
  1614. cameraControls.addControl(&zoomOutControl);
  1615. cameraControls.addControl(&orbitCCWControl);
  1616. cameraControls.addControl(&orbitCWControl);
  1617. cameraControls.addControl(&adjustCameraControl);
  1618. cameraControls.addControl(&dragCameraControl);
  1619. cameraControls.addControl(&pauseControl);
  1620. // Build the tool control set
  1621. toolControls.addControl(&changeToolControl);
  1622. toolControls.addControl(&useToolControl);
  1623. // Build the editor control set
  1624. editorControls.addControl(&toggleEditModeControl);
  1625. // Setup control callbacks
  1626. menuDownControl.setActivatedCallback(std::bind(&Game::selectNextMenuItem, this));
  1627. menuUpControl.setActivatedCallback(std::bind(&Game::selectPreviousMenuItem, this));
  1628. menuActivateControl.setActivatedCallback(std::bind(&Game::activateMenuItem, this));
  1629. menuBackControl.setActivatedCallback(std::bind(&Game::activateLastMenuItem, this));
  1630. pauseControl.setActivatedCallback(std::bind(&Game::togglePause, this));
  1631. exitControl.setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1632. toggleFullscreenControl.setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1633. takeScreenshotControl.setActivatedCallback(std::bind(&Game::queueScreenshot, this));
  1634. // Build map of control names
  1635. controlNameMap["exit"] = &exitControl;
  1636. controlNameMap["toggle-fullscreen"] = &toggleFullscreenControl;
  1637. controlNameMap["take-screenshot"] = &takeScreenshotControl;
  1638. controlNameMap["menu-up"] = &menuUpControl;
  1639. controlNameMap["menu-down"] = &menuDownControl;
  1640. controlNameMap["menu-left"] = &menuLeftControl;
  1641. controlNameMap["menu-right"] = &menuRightControl;
  1642. controlNameMap["menu-activate"] = &menuActivateControl;
  1643. controlNameMap["menu-back"] = &menuBackControl;
  1644. controlNameMap["move-forward"] = &moveForwardControl;
  1645. controlNameMap["move-back"] = &moveBackControl;
  1646. controlNameMap["move-left"] = &moveLeftControl;
  1647. controlNameMap["move-right"] = &moveRightControl;
  1648. controlNameMap["zoom-in"] = &zoomInControl;
  1649. controlNameMap["zoom-out"] = &zoomOutControl;
  1650. controlNameMap["orbit-ccw"] = &orbitCCWControl;
  1651. controlNameMap["orbit-cw"] = &orbitCWControl;
  1652. controlNameMap["adjust-camera"] = &adjustCameraControl;
  1653. controlNameMap["drag-camera"] = &dragCameraControl;
  1654. controlNameMap["pause"] = &pauseControl;
  1655. controlNameMap["change-tool"] = &changeToolControl;
  1656. controlNameMap["use-tool"] = &useToolControl;
  1657. controlNameMap["toggle-edit-mode"] = &toggleEditModeControl;
  1658. // Load control profile
  1659. if (pathExists(controlsPath + (*controlProfileName) + ".csv"))
  1660. {
  1661. loadControlProfile(*controlProfileName);
  1662. }
  1663. else
  1664. {
  1665. loadControlProfile("default-keyboard-controls");
  1666. saveControlProfile(*controlProfileName);
  1667. }
  1668. // Setup input mapper
  1669. inputMapper = new InputMapper(&eventDispatcher);
  1670. inputMapper->setCallback(std::bind(&Game::inputMapped, this, std::placeholders::_1));
  1671. inputMapper->setControl(nullptr);
  1672. inputMapper->setEnabled(false);
  1673. }
  1674. void Game::setupGameplay()
  1675. {
  1676. // Setup step scheduler
  1677. double maxFrameDuration = 0.25;
  1678. double stepFrequency = 60.0;
  1679. stepScheduler.setMaxFrameDuration(maxFrameDuration);
  1680. stepScheduler.setStepFrequency(stepFrequency);
  1681. timestep = stepScheduler.getStepPeriod();
  1682. // Setup camera rigs
  1683. orbitCam = new OrbitCam();
  1684. orbitCam->attachCamera(&camera);
  1685. freeCam = new FreeCam();
  1686. freeCam->attachCamera(&camera);
  1687. cameraRig = orbitCam;
  1688. }
  1689. void Game::loadSettings()
  1690. {
  1691. firstRun = false;
  1692. // Load settings
  1693. try
  1694. {
  1695. settings = resourceManager->load<ParameterDict>("settings.csv");
  1696. }
  1697. catch (const std::exception& e)
  1698. {
  1699. logger->warning("No user settings found. First run assumed.");
  1700. firstRun = true;
  1701. try
  1702. {
  1703. settings = resourceManager->load<ParameterDict>("default-settings.csv");
  1704. }
  1705. catch (const std::exception& e)
  1706. {
  1707. logger->error("Failed to load default settings.");
  1708. settings = new ParameterDict();
  1709. }
  1710. }
  1711. // Read settings
  1712. language = settings->get<std::string>("language");
  1713. windowPosition = settings->get<int, 2>("window-position");
  1714. windowResolution = settings->get<int, 2>("window-resolution");
  1715. fullscreenResolution = settings->get<int, 2>("window-resolution");
  1716. fullscreen = settings->get<bool>("fullscreen");
  1717. vsync = settings->get<bool>("vsync");
  1718. fontSize = settings->get<float>("font-size");
  1719. controlProfileName = settings->get<std::string>("control-profile");
  1720. // Use default values for unset parameters
  1721. {
  1722. if (language == std::nullopt)
  1723. {
  1724. language = "en-us";
  1725. }
  1726. // Get display dimensions
  1727. const Display* display = deviceManager->getDisplays()->front();
  1728. int displayWidth = std::get<0>(display->getDimensions());
  1729. int displayHeight = std::get<1>(display->getDimensions());
  1730. if (windowResolution == std::nullopt)
  1731. {
  1732. const float windowResolutionRatio = 5.0f / 6.0f;
  1733. int windowWidth = static_cast<int>(static_cast<float>(displayWidth) * windowResolutionRatio);
  1734. int windowHeight = static_cast<int>(static_cast<float>(displayHeight) * windowResolutionRatio);
  1735. windowResolution = {windowWidth, windowHeight};
  1736. }
  1737. if (windowPosition == std::nullopt)
  1738. {
  1739. int windowX = std::get<0>(display->getPosition()) + displayWidth / 2 - (*windowResolution)[0] / 2;
  1740. int windowY = std::get<1>(display->getPosition()) + displayHeight / 2 - (*windowResolution)[1] / 2;
  1741. windowPosition = {windowX, windowY};
  1742. }
  1743. if (fullscreen == std::nullopt)
  1744. {
  1745. fullscreen = true;
  1746. }
  1747. if (vsync == std::nullopt)
  1748. {
  1749. vsync = true;
  1750. }
  1751. if (fontSize == std::nullopt)
  1752. {
  1753. fontSize = 14.0f;
  1754. }
  1755. if (controlProfileName == std::nullopt)
  1756. {
  1757. controlProfileName = "controls";
  1758. }
  1759. }
  1760. }
  1761. void Game::saveSettings()
  1762. {
  1763. // Update settings
  1764. settings->set("language", *language);
  1765. settings->set("window-position", *windowPosition);
  1766. settings->set("window-resolution", *windowResolution);
  1767. settings->set("fullscreen-resolution", *fullscreenResolution);
  1768. settings->set("fullscreen", *fullscreen);
  1769. settings->set("vsync", *vsync);
  1770. settings->set("font-size", *fontSize);
  1771. settings->set("control-profile", *controlProfileName);
  1772. // Form full path to settings file
  1773. std::string settingsPath = configPath + "settings.csv";
  1774. // Save settings
  1775. resourceManager->save<ParameterDict>(settings, settingsPath);
  1776. }
  1777. void Game::loadStrings()
  1778. {
  1779. // Read strings file
  1780. stringTable = resourceManager->load<StringTable>("strings.csv");
  1781. // Build string table index
  1782. stringTableIndex = createIndex(*stringTable);
  1783. }
  1784. void Game::loadFonts()
  1785. {
  1786. // If the language selection fonts haven't been loaded
  1787. if (languageSelectionFonts.empty())
  1788. {
  1789. // Load one font for each available language
  1790. for (std::size_t i = 0; i < languageCount; ++i)
  1791. {
  1792. // Get language name and font filename for that language
  1793. std::string languageName = getString("language-name", i);
  1794. std::string fontFilename = getString("menu-font-filename", i);
  1795. // Check if language has a name
  1796. if (languageName.empty())
  1797. {
  1798. logger->error("Language #" + std::to_string(i) + " has no name string.");
  1799. languageSelectionFonts.push_back(nullptr);
  1800. continue;
  1801. }
  1802. // Check if language has a font filename
  1803. if (fontFilename.empty())
  1804. {
  1805. logger->error("No font for language #" + std::to_string(i) + ".");
  1806. languageSelectionFonts.push_back(nullptr);
  1807. continue;
  1808. }
  1809. // Load typeface for the font
  1810. Typeface* typeface = resourceManager->load<Typeface>(fontFilename);
  1811. // Create a font at default font size
  1812. Font* font = typeface->createFont(fontSizePX);
  1813. // Build a character set containing only the characters in the language name
  1814. std::set<char32_t> characterSet;
  1815. std::u32string languageNameUTF32 = toUTF32(languageName);
  1816. for (char32_t charcode: languageNameUTF32)
  1817. {
  1818. characterSet.emplace(charcode);
  1819. }
  1820. // Load glyphs for all characters in the character set
  1821. typeface->loadCharset(font, characterSet);
  1822. // Unload the typeface
  1823. resourceManager->unload(fontFilename);
  1824. // Add the font to the language selection fonts
  1825. languageSelectionFonts.push_back(font);
  1826. }
  1827. }
  1828. // Get filenames of fonts
  1829. std::string menuFontFilename = getString("menu-font-filename");
  1830. std::string debugFontFilename = "inconsolata-bold.ttf";
  1831. // Load debugging font
  1832. if (!debugFont)
  1833. {
  1834. // Load debug font typeface
  1835. Typeface* debugTypeface = resourceManager->load<Typeface>(debugFontFilename);
  1836. // Create debug font
  1837. debugFont = debugTypeface->createFont(fontSizePX);
  1838. // Load basic latin characyer set
  1839. debugTypeface->loadCharset(debugFont, UnicodeRange::BASIC_LATIN);
  1840. // Unload debug font typeface
  1841. resourceManager->unload(debugFontFilename);
  1842. }
  1843. // Load menu font typeface
  1844. Typeface* menuTypeface = resourceManager->load<Typeface>(menuFontFilename);
  1845. // Create menu font
  1846. menuFont = menuTypeface->createFont(fontSizePX);
  1847. // Load basic latin character set
  1848. menuTypeface->loadCharset(menuFont, UnicodeRange::BASIC_LATIN);
  1849. // Build character set for all strings in current language
  1850. std::set<char32_t> characterSet;
  1851. for (const StringTableRow& row: *stringTable)
  1852. {
  1853. // Convert to UTF-8 string to UTF-32
  1854. std::u32string string = toUTF32(row[currentLanguageIndex + 2]);
  1855. // Add each character in the string to the charater set
  1856. for (char32_t charcode: string)
  1857. {
  1858. characterSet.emplace(charcode);
  1859. }
  1860. }
  1861. // Load custom character set
  1862. menuTypeface->loadCharset(menuFont, characterSet);
  1863. // Unload menu typeface
  1864. resourceManager->unload(menuFontFilename);
  1865. }
  1866. void Game::loadControlProfile(const std::string& profileName)
  1867. {
  1868. // Load control profile
  1869. std::string controlProfilePath = profileName + ".csv";
  1870. StringTable* controlProfile = resourceManager->load<StringTable>(controlProfilePath);
  1871. for (const StringTableRow& row: *controlProfile)
  1872. {
  1873. // Skip empty rows and comments
  1874. if (row.empty() || row[0].empty() || row[0][0] == '#')
  1875. {
  1876. continue;
  1877. }
  1878. // Get control name
  1879. const std::string& controlName = row[0];
  1880. // Lookup control in control name map
  1881. auto it = controlNameMap.find(controlName);
  1882. if (it == controlNameMap.end())
  1883. {
  1884. logger->warning("Game::loadControlProfile(): Unknown control name \"" + controlName + "\"\n");
  1885. continue;
  1886. }
  1887. // Get pointer to the control
  1888. Control* control = it->second;
  1889. // Determine type of input mapping
  1890. const std::string& deviceType = row[1];
  1891. if (deviceType == "keyboard")
  1892. {
  1893. const std::string& eventType = row[2];
  1894. const std::string& scancodeName = row[3];
  1895. // Get scancode from string
  1896. Scancode scancode = Keyboard::getScancodeFromName(scancodeName.c_str());
  1897. // Map control
  1898. if (scancode != Scancode::UNKNOWN)
  1899. {
  1900. inputRouter->addMapping(KeyMapping(control, keyboard, scancode));
  1901. }
  1902. }
  1903. else if (deviceType == "mouse")
  1904. {
  1905. const std::string& eventType = row[2];
  1906. if (eventType == "motion")
  1907. {
  1908. const std::string& axisName = row[3];
  1909. // Get axis from string
  1910. MouseMotionAxis axis;
  1911. bool negative = (axisName.find('-') != std::string::npos);
  1912. if (axisName.find('x') != std::string::npos)
  1913. {
  1914. axis = (negative) ? MouseMotionAxis::NEGATIVE_X : MouseMotionAxis::POSITIVE_X;
  1915. }
  1916. else if (axisName.find('y') != std::string::npos)
  1917. {
  1918. axis = (negative) ? MouseMotionAxis::NEGATIVE_Y : MouseMotionAxis::POSITIVE_Y;
  1919. }
  1920. else
  1921. {
  1922. logger->warning("Game::loadControlProfile(): Unknown mouse motion axis \"" + axisName + "\"\n");
  1923. continue;
  1924. }
  1925. // Map control
  1926. inputRouter->addMapping(MouseMotionMapping(control, mouse, axis));
  1927. }
  1928. else if (eventType == "wheel")
  1929. {
  1930. const std::string& axisName = row[3];
  1931. // Get axis from string
  1932. MouseWheelAxis axis;
  1933. bool negative = (axisName.find('-') != std::string::npos);
  1934. if (axisName.find('x') != std::string::npos)
  1935. {
  1936. axis = (negative) ? MouseWheelAxis::NEGATIVE_X : MouseWheelAxis::POSITIVE_X;
  1937. }
  1938. else if (axisName.find('y') != std::string::npos)
  1939. {
  1940. axis = (negative) ? MouseWheelAxis::NEGATIVE_Y : MouseWheelAxis::POSITIVE_Y;
  1941. }
  1942. else
  1943. {
  1944. logger->warning("Game::loadControlProfile(): Unknown mouse wheel axis \"" + axisName + "\"\n");
  1945. continue;
  1946. }
  1947. // Map control
  1948. inputRouter->addMapping(MouseWheelMapping(control, mouse, axis));
  1949. }
  1950. else if (eventType == "button")
  1951. {
  1952. const std::string& buttonName = row[3];
  1953. // Get button from string
  1954. int button;
  1955. std::stringstream stream;
  1956. stream << buttonName;
  1957. stream >> button;
  1958. // Map control
  1959. inputRouter->addMapping(MouseButtonMapping(control, mouse, button));
  1960. }
  1961. else
  1962. {
  1963. logger->warning("Game::loadControlProfile(): Unknown mouse event type \"" + eventType + "\"\n");
  1964. continue;
  1965. }
  1966. }
  1967. else if (deviceType == "gamepad")
  1968. {
  1969. const std::string& eventType = row[2];
  1970. if (eventType == "axis")
  1971. {
  1972. std::string axisName = row[3];
  1973. // Determine whether axis is negative or positive
  1974. bool negative = (axisName.find('-') != std::string::npos);
  1975. // Remove sign from axis name
  1976. std::size_t plusPosition = axisName.find('+');
  1977. std::size_t minusPosition = axisName.find('-');
  1978. if (plusPosition != std::string::npos)
  1979. {
  1980. axisName.erase(plusPosition);
  1981. }
  1982. else if (minusPosition != std::string::npos)
  1983. {
  1984. axisName.erase(minusPosition);
  1985. }
  1986. // Get axis from string
  1987. int axis;
  1988. std::stringstream stream;
  1989. stream << axisName;
  1990. stream >> axis;
  1991. // Map control to each gamepad
  1992. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1993. for (Gamepad* gamepad: *gamepads)
  1994. {
  1995. inputRouter->addMapping(GamepadAxisMapping(control, gamepad, axis, negative));
  1996. }
  1997. }
  1998. else if (eventType == "button")
  1999. {
  2000. const std::string& buttonName = row[3];
  2001. // Get button from string
  2002. int button;
  2003. std::stringstream stream;
  2004. stream << buttonName;
  2005. stream >> button;
  2006. // Map control to each gamepad
  2007. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  2008. for (Gamepad* gamepad: *gamepads)
  2009. {
  2010. inputRouter->addMapping(GamepadButtonMapping(control, gamepad, button));
  2011. }
  2012. }
  2013. else
  2014. {
  2015. logger->warning("Game::loadControlProfile(): Unknown gamepad event type \"" + eventType + "\"\n");
  2016. continue;
  2017. }
  2018. }
  2019. else
  2020. {
  2021. logger->warning("Game::loadControlProfile(): Unknown input device type \"" + deviceType + "\"\n");
  2022. continue;
  2023. }
  2024. }
  2025. }
  2026. void Game::saveControlProfile(const std::string& profileName)
  2027. {
  2028. // Build control profile string table
  2029. StringTable* table = new StringTable();
  2030. for (auto it = controlNameMap.begin(); it != controlNameMap.end(); ++it)
  2031. {
  2032. // Get control name
  2033. const std::string& controlName = it->first;
  2034. // Get pointer to the control
  2035. Control* control = it->second;
  2036. // Look up list of mappings for the control
  2037. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  2038. if (!mappings)
  2039. {
  2040. continue;
  2041. }
  2042. // For each input mapping
  2043. for (const InputMapping* mapping: *mappings)
  2044. {
  2045. // Add row to the table
  2046. table->push_back(StringTableRow());
  2047. StringTableRow* row = &table->back();
  2048. // Add control name column
  2049. row->push_back(controlName);
  2050. switch (mapping->getType())
  2051. {
  2052. case InputMappingType::KEY:
  2053. {
  2054. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  2055. row->push_back("keyboard");
  2056. row->push_back("key");
  2057. std::string scancodeName = std::string("\"") + std::string(Keyboard::getScancodeName(keyMapping->scancode)) + std::string("\"");
  2058. row->push_back(scancodeName);
  2059. break;
  2060. }
  2061. case InputMappingType::MOUSE_MOTION:
  2062. {
  2063. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  2064. row->push_back("mouse");
  2065. row->push_back("motion");
  2066. std::string axisName;
  2067. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  2068. {
  2069. axisName = "+x";
  2070. }
  2071. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  2072. {
  2073. axisName = "-x";
  2074. }
  2075. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  2076. {
  2077. axisName = "+y";
  2078. }
  2079. else
  2080. {
  2081. axisName = "-y";
  2082. }
  2083. row->push_back(axisName);
  2084. break;
  2085. }
  2086. case InputMappingType::MOUSE_WHEEL:
  2087. {
  2088. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  2089. row->push_back("mouse");
  2090. row->push_back("wheel");
  2091. std::string axisName;
  2092. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  2093. {
  2094. axisName = "+x";
  2095. }
  2096. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  2097. {
  2098. axisName = "-x";
  2099. }
  2100. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  2101. {
  2102. axisName = "+y";
  2103. }
  2104. else
  2105. {
  2106. axisName = "-y";
  2107. }
  2108. row->push_back(axisName);
  2109. break;
  2110. }
  2111. case InputMappingType::MOUSE_BUTTON:
  2112. {
  2113. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  2114. row->push_back("mouse");
  2115. row->push_back("button");
  2116. std::string buttonName;
  2117. std::stringstream stream;
  2118. stream << static_cast<int>(mouseButtonMapping->button);
  2119. stream >> buttonName;
  2120. row->push_back(buttonName);
  2121. break;
  2122. }
  2123. case InputMappingType::GAMEPAD_AXIS:
  2124. {
  2125. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  2126. row->push_back("gamepad");
  2127. row->push_back("axis");
  2128. std::stringstream stream;
  2129. if (gamepadAxisMapping->negative)
  2130. {
  2131. stream << "-";
  2132. }
  2133. else
  2134. {
  2135. stream << "+";
  2136. }
  2137. stream << gamepadAxisMapping->axis;
  2138. std::string axisName;
  2139. stream >> axisName;
  2140. row->push_back(axisName);
  2141. break;
  2142. }
  2143. case InputMappingType::GAMEPAD_BUTTON:
  2144. {
  2145. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  2146. row->push_back("gamepad");
  2147. row->push_back("button");
  2148. std::string buttonName;
  2149. std::stringstream stream;
  2150. stream << static_cast<int>(gamepadButtonMapping->button);
  2151. stream >> buttonName;
  2152. row->push_back(buttonName);
  2153. break;
  2154. }
  2155. default:
  2156. break;
  2157. }
  2158. }
  2159. }
  2160. // Form full path to control profile file
  2161. std::string controlProfilePath = controlsPath + profileName + ".csv";
  2162. // Save control profile
  2163. resourceManager->save<StringTable>(table, controlProfilePath);
  2164. // Free control profile string table
  2165. delete table;
  2166. }
  2167. std::array<std::string, 3> Game::getInputMappingStrings(const InputMapping* mapping)
  2168. {
  2169. std::string deviceString;
  2170. std::string typeString;
  2171. std::string eventString;
  2172. switch (mapping->getType())
  2173. {
  2174. case InputMappingType::KEY:
  2175. {
  2176. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  2177. deviceString = "keyboard";
  2178. typeString = "key";
  2179. eventString = std::string(Keyboard::getScancodeName(keyMapping->scancode));
  2180. break;
  2181. }
  2182. case InputMappingType::MOUSE_MOTION:
  2183. {
  2184. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  2185. deviceString = "mouse";
  2186. eventString = "motion";
  2187. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  2188. {
  2189. eventString = "+x";
  2190. }
  2191. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  2192. {
  2193. eventString = "-x";
  2194. }
  2195. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  2196. {
  2197. eventString = "+y";
  2198. }
  2199. else
  2200. {
  2201. eventString = "-y";
  2202. }
  2203. break;
  2204. }
  2205. case InputMappingType::MOUSE_WHEEL:
  2206. {
  2207. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  2208. deviceString = "mouse";
  2209. typeString = "wheel";
  2210. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  2211. {
  2212. eventString = "+x";
  2213. }
  2214. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  2215. {
  2216. eventString = "-x";
  2217. }
  2218. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  2219. {
  2220. eventString = "+y";
  2221. }
  2222. else
  2223. {
  2224. eventString = "-y";
  2225. }
  2226. break;
  2227. }
  2228. case InputMappingType::MOUSE_BUTTON:
  2229. {
  2230. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  2231. deviceString = "mouse";
  2232. typeString = "button";
  2233. std::stringstream stream;
  2234. stream << static_cast<int>(mouseButtonMapping->button);
  2235. stream >> eventString;
  2236. break;
  2237. }
  2238. case InputMappingType::GAMEPAD_AXIS:
  2239. {
  2240. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  2241. deviceString = "gamepad";
  2242. typeString = "axis";
  2243. std::stringstream stream;
  2244. if (gamepadAxisMapping->negative)
  2245. {
  2246. stream << "-";
  2247. }
  2248. else
  2249. {
  2250. stream << "+";
  2251. }
  2252. stream << gamepadAxisMapping->axis;
  2253. stream >> eventString;
  2254. break;
  2255. }
  2256. case InputMappingType::GAMEPAD_BUTTON:
  2257. {
  2258. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  2259. deviceString = "gamepad";
  2260. typeString = "button";
  2261. std::stringstream stream;
  2262. stream << static_cast<int>(gamepadButtonMapping->button);
  2263. stream >> eventString;
  2264. break;
  2265. }
  2266. default:
  2267. break;
  2268. }
  2269. return {deviceString, typeString, eventString};
  2270. }
  2271. void Game::remapControl(Control* control)
  2272. {
  2273. // Remove previously set input mappings for the control
  2274. inputRouter->removeMappings(control);
  2275. // Start mapping new input
  2276. inputMapper->setControl(control);
  2277. inputMapper->setEnabled(true);
  2278. // Restring UI to show control mappings have been removed.
  2279. restringUI();
  2280. // Disable UI callbacks
  2281. uiRootElement->setCallbacksEnabled(false);
  2282. // Disable menu control callbacks
  2283. menuControls.setCallbacksEnabled(false);
  2284. }
  2285. void Game::resetControls()
  2286. {
  2287. inputRouter->reset();
  2288. loadControlProfile("default-keyboard-controls");
  2289. saveControlProfile(*controlProfileName);
  2290. restringUI();
  2291. }
  2292. void Game::resizeUI(int w, int h)
  2293. {
  2294. // Adjust root element dimensions
  2295. uiRootElement->setDimensions(Vector2(w, h));
  2296. uiRootElement->update();
  2297. splashBackgroundImage->setDimensions(Vector2(w, h));
  2298. splashBackgroundImage->setAnchor(Anchor::TOP_LEFT);
  2299. // Resize splash screen image
  2300. splashImage->setAnchor(Anchor::CENTER);
  2301. splashImage->setDimensions(Vector2(splashTexture->getWidth(), splashTexture->getHeight()));
  2302. // Adjust UI camera projection matrix
  2303. uiCamera.setOrthographic(0.0f, w, h, 0.0f, -1.0f, 1.0f);
  2304. uiCamera.resetTweens();
  2305. // Resize camera flash image
  2306. cameraFlashImage->setDimensions(Vector2(w, h));
  2307. cameraFlashImage->setAnchor(Anchor::CENTER);
  2308. // Resize blackout image
  2309. blackoutImage->setDimensions(Vector2(w, h));
  2310. blackoutImage->setAnchor(Anchor::CENTER);
  2311. // Resize language select background image
  2312. languageSelectBGImage->setDimensions(Vector2(w, h));
  2313. languageSelectBGImage->setAnchor(Anchor::CENTER);
  2314. // Resize HUD
  2315. float hudPadding = 20.0f;
  2316. hudContainer->setDimensions(Vector2(w - hudPadding * 2.0f, h - hudPadding * 2.0f));
  2317. hudContainer->setAnchor(Anchor::CENTER);
  2318. // Tool indicator
  2319. Rect toolIndicatorBounds = hudTextureAtlas.getBounds("tool-indicator");
  2320. toolIndicatorBGImage->setDimensions(Vector2(toolIndicatorBounds.getWidth(), toolIndicatorBounds.getHeight()));
  2321. toolIndicatorBGImage->setAnchor(Anchor::TOP_LEFT);
  2322. Rect toolIndicatorIconBounds = hudTextureAtlas.getBounds("tool-indicator-lens");
  2323. toolIndicatorIconImage->setDimensions(Vector2(toolIndicatorIconBounds.getWidth(), toolIndicatorIconBounds.getHeight()));
  2324. toolIndicatorIconImage->setAnchor(Anchor::CENTER);
  2325. // Buttons
  2326. Rect playButtonBounds = hudTextureAtlas.getBounds("button-play");
  2327. Rect fastForwardButtonBounds = hudTextureAtlas.getBounds("button-fast-forward-2x");
  2328. Rect pauseButtonBounds = hudTextureAtlas.getBounds("button-pause");
  2329. Rect buttonBackgroundBounds = hudTextureAtlas.getBounds("button-background");
  2330. Vector2 buttonBGDimensions = Vector2(buttonBackgroundBounds.getWidth(), buttonBackgroundBounds.getHeight());
  2331. float buttonMargin = 10.0f;
  2332. float buttonDepth = 15.0f;
  2333. float buttonContainerWidth = fastForwardButtonBounds.getWidth();
  2334. float buttonContainerHeight = fastForwardButtonBounds.getHeight();
  2335. buttonContainer->setDimensions(Vector2(buttonContainerWidth, buttonContainerHeight));
  2336. buttonContainer->setAnchor(Anchor::TOP_RIGHT);
  2337. playButtonImage->setDimensions(Vector2(playButtonBounds.getWidth(), playButtonBounds.getHeight()));
  2338. playButtonImage->setAnchor(Vector2(0.0f, 0.0f));
  2339. playButtonBGImage->setDimensions(buttonBGDimensions);
  2340. playButtonBGImage->setAnchor(Vector2(0.0f, 1.0f));
  2341. fastForwardButtonImage->setDimensions(Vector2(fastForwardButtonBounds.getWidth(), fastForwardButtonBounds.getHeight()));
  2342. fastForwardButtonImage->setAnchor(Vector2(0.5f, 5.0f));
  2343. fastForwardButtonBGImage->setDimensions(buttonBGDimensions);
  2344. fastForwardButtonBGImage->setAnchor(Vector2(0.5f, 0.5f));
  2345. pauseButtonImage->setDimensions(Vector2(pauseButtonBounds.getWidth(), pauseButtonBounds.getHeight()));
  2346. pauseButtonImage->setAnchor(Vector2(1.0f, 0.0f));
  2347. pauseButtonBGImage->setDimensions(buttonBGDimensions);
  2348. pauseButtonBGImage->setAnchor(Vector2(1.0f, 1.0f));
  2349. // Radial menu
  2350. Rect radialMenuBounds = hudTextureAtlas.getBounds("radial-menu");
  2351. radialMenuContainer->setDimensions(Vector2(w, h));
  2352. radialMenuContainer->setAnchor(Anchor::CENTER);
  2353. radialMenuContainer->setLayerOffset(30);
  2354. radialMenuBackgroundImage->setDimensions(Vector2(w, h));
  2355. radialMenuBackgroundImage->setAnchor(Anchor::CENTER);
  2356. radialMenuBackgroundImage->setLayerOffset(-1);
  2357. //radialMenuImage->setDimensions(Vector2(w * 0.5f, h * 0.5f));
  2358. radialMenuImage->setDimensions(Vector2(radialMenuBounds.getWidth(), radialMenuBounds.getHeight()));
  2359. radialMenuImage->setAnchor(Anchor::CENTER);
  2360. Rect radialMenuSelectorBounds = hudTextureAtlas.getBounds("radial-menu-selector");
  2361. radialMenuSelectorImage->setDimensions(Vector2(radialMenuSelectorBounds.getWidth(), radialMenuSelectorBounds.getHeight()));
  2362. radialMenuSelectorImage->setAnchor(Anchor::CENTER);
  2363. Rect toolIconBrushBounds = hudTextureAtlas.getBounds("tool-icon-brush");
  2364. toolIconBrushImage->setDimensions(Vector2(toolIconBrushBounds.getWidth(), toolIconBrushBounds.getHeight()));
  2365. toolIconBrushImage->setAnchor(Anchor::CENTER);
  2366. Rect toolIconLensBounds = hudTextureAtlas.getBounds("tool-icon-lens");
  2367. toolIconLensImage->setDimensions(Vector2(toolIconLensBounds.getWidth(), toolIconLensBounds.getHeight()));
  2368. toolIconLensImage->setAnchor(Anchor::CENTER);
  2369. Rect toolIconForcepsBounds = hudTextureAtlas.getBounds("tool-icon-forceps");
  2370. toolIconForcepsImage->setDimensions(Vector2(toolIconForcepsBounds.getWidth(), toolIconForcepsBounds.getHeight()));
  2371. toolIconForcepsImage->setAnchor(Anchor::CENTER);
  2372. Rect toolIconSpadeBounds = hudTextureAtlas.getBounds("tool-icon-spade");
  2373. toolIconSpadeImage->setDimensions(Vector2(toolIconSpadeBounds.getWidth(), toolIconSpadeBounds.getHeight()));
  2374. toolIconSpadeImage->setAnchor(Anchor::CENTER);
  2375. Rect toolIconCameraBounds = hudTextureAtlas.getBounds("tool-icon-camera");
  2376. toolIconCameraImage->setDimensions(Vector2(toolIconCameraBounds.getWidth(), toolIconCameraBounds.getHeight()));
  2377. toolIconCameraImage->setAnchor(Anchor::CENTER);
  2378. Rect toolIconMicrochipBounds = hudTextureAtlas.getBounds("tool-icon-microchip");
  2379. toolIconMicrochipImage->setDimensions(Vector2(toolIconMicrochipBounds.getWidth(), toolIconMicrochipBounds.getHeight()));
  2380. toolIconMicrochipImage->setAnchor(Anchor::CENTER);
  2381. Rect toolIconTestTubeBounds = hudTextureAtlas.getBounds("tool-icon-test-tube");
  2382. toolIconTestTubeImage->setDimensions(Vector2(toolIconTestTubeBounds.getWidth(), toolIconTestTubeBounds.getHeight()));
  2383. toolIconTestTubeImage->setAnchor(Anchor::CENTER);
  2384. Rect labelCornerBounds = hudTextureAtlas.getBounds("label-tl");
  2385. Vector2 labelCornerDimensions(labelCornerBounds.getWidth(), labelCornerBounds.getHeight());
  2386. Vector2 antLabelPadding(10.0f, 6.0f);
  2387. antLabelContainer->setDimensions(antLabel->getDimensions() + antLabelPadding * 2.0f);
  2388. antLabelContainer->setTranslation(Vector2(0.0f, (int)(-antPin->getDimensions().y * 0.125f)));
  2389. antLabelTL->setDimensions(labelCornerDimensions);
  2390. antLabelTR->setDimensions(labelCornerDimensions);
  2391. antLabelBL->setDimensions(labelCornerDimensions);
  2392. antLabelBR->setDimensions(labelCornerDimensions);
  2393. antLabelCC->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2394. antLabelCT->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  2395. antLabelCB->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  2396. antLabelCL->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2397. antLabelCR->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2398. antLabelContainer->setAnchor(Vector2(0.5f, 0.5f));
  2399. antLabelTL->setAnchor(Anchor::TOP_LEFT);
  2400. antLabelTR->setAnchor(Anchor::TOP_RIGHT);
  2401. antLabelBL->setAnchor(Anchor::BOTTOM_LEFT);
  2402. antLabelBR->setAnchor(Anchor::BOTTOM_RIGHT);
  2403. antLabelCC->setAnchor(Anchor::CENTER);
  2404. antLabelCT->setAnchor(Vector2(0.5f, 0.0f));
  2405. antLabelCB->setAnchor(Vector2(0.5f, 1.0f));
  2406. antLabelCL->setAnchor(Vector2(0.0f, 0.5f));
  2407. antLabelCR->setAnchor(Vector2(1.0f, 0.5f));
  2408. antLabel->setAnchor(Anchor::CENTER);
  2409. Rect antPinBounds = hudTextureAtlas.getBounds("label-pin");
  2410. antPin->setDimensions(Vector2(antPinBounds.getWidth(), antPinBounds.getHeight()));
  2411. antPin->setAnchor(Vector2(0.5f, 1.0f));
  2412. Rect pinHoleBounds = hudTextureAtlas.getBounds("label-pin-hole");
  2413. antLabelPinHole->setDimensions(Vector2(pinHoleBounds.getWidth(), pinHoleBounds.getHeight()));
  2414. antLabelPinHole->setAnchor(Vector2(0.5f, 0.0f));
  2415. antLabelPinHole->setTranslation(Vector2(0.0f, -antLabelPinHole->getDimensions().y * 0.5f));
  2416. antLabelPinHole->setLayerOffset(2);
  2417. float pinDistance = 20.0f;
  2418. antTag->setAnchor(Anchor::CENTER);
  2419. antTag->setDimensions(Vector2(antLabelContainer->getDimensions().x, antPin->getDimensions().y));
  2420. float cameraGridLineWidth = 2.0f;
  2421. float cameraReticleDiameter = 6.0f;
  2422. cameraGridContainer->setDimensions(Vector2(w, h));
  2423. cameraGridY0Image->setDimensions(Vector2(w, cameraGridLineWidth));
  2424. cameraGridY1Image->setDimensions(Vector2(w, cameraGridLineWidth));
  2425. cameraGridX0Image->setDimensions(Vector2(cameraGridLineWidth, h));
  2426. cameraGridX1Image->setDimensions(Vector2(cameraGridLineWidth, h));
  2427. cameraReticleImage->setDimensions(Vector2(cameraReticleDiameter));
  2428. cameraGridY0Image->setTranslation(Vector2(0));
  2429. cameraGridY1Image->setTranslation(Vector2(0));
  2430. cameraGridX0Image->setTranslation(Vector2(0));
  2431. cameraGridX1Image->setTranslation(Vector2(0));
  2432. cameraReticleImage->setTranslation(Vector2(0));
  2433. Rect menuSelectorBounds = hudTextureAtlas.getBounds("menu-selector");
  2434. menuSelectorImage->setDimensions(Vector2(menuSelectorBounds.getWidth(), menuSelectorBounds.getHeight()));
  2435. UIImage* icons[] =
  2436. {
  2437. toolIconBrushImage,
  2438. nullptr,
  2439. toolIconLensImage,
  2440. nullptr,
  2441. toolIconForcepsImage,
  2442. toolIconMicrochipImage,
  2443. toolIconCameraImage,
  2444. nullptr
  2445. };
  2446. Rect radialMenuIconRingBounds = hudTextureAtlas.getBounds("radial-menu-icon-ring");
  2447. float iconOffset = radialMenuIconRingBounds.getWidth() * 0.5f;
  2448. float sectorAngle = (2.0f * 3.14159264f) / 8.0f;
  2449. for (int i = 0; i < 8; ++i)
  2450. {
  2451. float angle = sectorAngle * static_cast<float>(i - 4);
  2452. Vector2 translation = Vector2(std::cos(angle), std::sin(angle)) * iconOffset;
  2453. translation.x = (int)(translation.x + 0.5f);
  2454. translation.y = (int)(translation.y + 0.5f);
  2455. if (icons[i] != nullptr)
  2456. {
  2457. icons[i]->setTranslation(translation);
  2458. }
  2459. }
  2460. // Main menu size
  2461. float mainMenuWidth = 0.0f;
  2462. float mainMenuHeight = 0.0f;
  2463. float mainMenuSpacing = 0.5f * fontSizePX;
  2464. float mainMenuPadding = fontSizePX * 4.0f;
  2465. for (const MenuItem* item: *mainMenu->getItems())
  2466. {
  2467. mainMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2468. mainMenuHeight += mainMenuSpacing;
  2469. mainMenuWidth = std::max<float>(mainMenuWidth, item->getNameLabel()->getDimensions().x);
  2470. }
  2471. mainMenuHeight -= mainMenuSpacing;
  2472. mainMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2473. mainMenu->resize(mainMenuWidth, mainMenuHeight);
  2474. mainMenu->getContainer()->setTranslation(Vector2(-mainMenuPadding));
  2475. // Settings menu size
  2476. float settingsMenuWidth = 0.0f;
  2477. float settingsMenuHeight = 0.0f;
  2478. float settingsMenuSpacing = 0.5f * fontSizePX;
  2479. float settingsMenuPadding = fontSizePX * 4.0f;
  2480. float settingsMenuValueMargin = fontSizePX * 4.0f;
  2481. for (const MenuItem* item: *settingsMenu->getItems())
  2482. {
  2483. settingsMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2484. settingsMenuHeight += settingsMenuSpacing;
  2485. float itemWidth = item->getNameLabel()->getDimensions().x;
  2486. if (!item->getValueLabel()->getText().empty())
  2487. {
  2488. itemWidth += item->getValueLabel()->getDimensions().x + settingsMenuValueMargin;
  2489. }
  2490. settingsMenuWidth = std::max<float>(settingsMenuWidth, itemWidth);
  2491. }
  2492. settingsMenuHeight -= settingsMenuSpacing;
  2493. settingsMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2494. settingsMenu->resize(settingsMenuWidth, settingsMenuHeight);
  2495. settingsMenu->getContainer()->setTranslation(Vector2(-settingsMenuPadding));
  2496. // Controls menu size
  2497. float controlsMenuWidth = 0.0f;
  2498. float controlsMenuHeight = 0.0f;
  2499. float controlsMenuSpacing = 0.5f * fontSizePX;
  2500. float controlsMenuPadding = fontSizePX * 4.0f;
  2501. float controlsMenuValueMargin = fontSizePX * 4.0f;
  2502. for (const MenuItem* item: *controlsMenu->getItems())
  2503. {
  2504. controlsMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2505. controlsMenuHeight += controlsMenuSpacing;
  2506. float itemWidth = item->getNameLabel()->getDimensions().x;
  2507. if (!item->getValueLabel()->getText().empty())
  2508. {
  2509. itemWidth += item->getValueLabel()->getDimensions().x + controlsMenuValueMargin;
  2510. }
  2511. controlsMenuWidth = std::max<float>(controlsMenuWidth, itemWidth);
  2512. }
  2513. controlsMenuWidth += controlsMenuValueMargin;
  2514. controlsMenuHeight -= controlsMenuSpacing;
  2515. controlsMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2516. controlsMenu->resize(controlsMenuWidth, controlsMenuHeight);
  2517. controlsMenu->getContainer()->setTranslation(Vector2(-controlsMenuPadding));
  2518. // Pause menu size
  2519. float pauseMenuWidth = 0.0f;
  2520. float pauseMenuHeight = 0.0f;
  2521. float pauseMenuSpacing = 0.5f * fontSizePX;
  2522. float pauseMenuPadding = fontSizePX * 4.0f;
  2523. for (const MenuItem* item: *pauseMenu->getItems())
  2524. {
  2525. pauseMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2526. pauseMenuHeight += pauseMenuSpacing;
  2527. pauseMenuWidth = std::max<float>(pauseMenuWidth, item->getNameLabel()->getDimensions().x);
  2528. }
  2529. pauseMenuHeight -= pauseMenuSpacing;
  2530. pauseMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2531. pauseMenu->resize(pauseMenuWidth, pauseMenuHeight);
  2532. pauseMenu->getContainer()->setTranslation(Vector2(-pauseMenuPadding));
  2533. // Language menu size
  2534. float languageMenuWidth = 0.0f;
  2535. float languageMenuHeight = 0.0f;
  2536. float languageMenuSpacing = 0.75f * fontSizePX;
  2537. for (const MenuItem* item: *languageMenu->getItems())
  2538. {
  2539. Font* font = item->getNameLabel()->getFont();
  2540. if (font)
  2541. {
  2542. float lineHeight = font->getMetrics().getAscender() - font->getMetrics().getDescender();
  2543. languageMenuHeight += lineHeight + languageMenuSpacing;
  2544. languageMenuWidth = std::max<float>(languageMenuWidth, item->getNameLabel()->getDimensions().x);
  2545. }
  2546. item->getNameLabel()->setAnchor(Vector2(0.5f, 0.0f));
  2547. }
  2548. languageMenuHeight -= languageMenuSpacing;
  2549. languageMenu->getContainer()->setAnchor(Anchor::CENTER);
  2550. languageMenu->resize(languageMenuWidth, languageMenuHeight);
  2551. }
  2552. void Game::restringUI()
  2553. {
  2554. // Reset fonts
  2555. mainMenu->setFonts(menuFont);
  2556. settingsMenu->setFonts(menuFont);
  2557. controlsMenu->setFonts(menuFont);
  2558. pauseMenu->setFonts(menuFont);
  2559. // Get common strings
  2560. std::string offString = getString("off");
  2561. std::string onString = getString("on");
  2562. std::string backString = getString("back");
  2563. // Main menu strings
  2564. mainMenuContinueItem->setName(getString("continue"));
  2565. mainMenuNewGameItem->setName(getString("new-game"));
  2566. mainMenuColoniesItem->setName(getString("colonies"));
  2567. mainMenuSettingsItem->setName(getString("settings"));
  2568. mainMenuQuitItem->setName(getString("quit"));
  2569. // Settings menu strings
  2570. settingsMenuControlsItem->setName(getString("controls"));
  2571. settingsMenuControlsItem->setValue(getString("ellipsis"));
  2572. settingsMenuFullscreenItem->setName(getString("fullscreen"));
  2573. settingsMenuFullscreenItem->setValue((*fullscreen) ? onString : offString);
  2574. settingsMenuVSyncItem->setName(getString("v-sync"));
  2575. settingsMenuVSyncItem->setValue((*vsync) ? onString : offString);
  2576. settingsMenuLanguageItem->setName(getString("language"));
  2577. settingsMenuLanguageItem->setValue(getString("language-name"));
  2578. settingsMenuBackItem->setName(backString);
  2579. // Controls menu strings
  2580. restringControlMenuItem(controlsMenuMoveForwardItem, "move-forward");
  2581. restringControlMenuItem(controlsMenuMoveLeftItem, "move-left");
  2582. restringControlMenuItem(controlsMenuMoveBackItem, "move-back");
  2583. restringControlMenuItem(controlsMenuMoveRightItem, "move-right");
  2584. restringControlMenuItem(controlsMenuChangeToolItem, "change-tool");
  2585. restringControlMenuItem(controlsMenuUseToolItem, "use-tool");
  2586. restringControlMenuItem(controlsMenuAdjustCameraItem, "adjust-camera");
  2587. restringControlMenuItem(controlsMenuPauseItem, "pause");
  2588. restringControlMenuItem(controlsMenuToggleFullscreenItem, "toggle-fullscreen");
  2589. restringControlMenuItem(controlsMenuTakeScreenshotItem, "take-screenshot");
  2590. controlsMenuResetToDefaultItem->setName(getString("reset-to-default"));
  2591. controlsMenuBackItem->setName(backString);
  2592. // Pause menu strings
  2593. pauseMenuResumeItem->setName(getString("resume"));
  2594. pauseMenuSettingsItem->setName(getString("settings"));
  2595. pauseMenuMainMenuItem->setName(getString("main-menu"));
  2596. pauseMenuQuitItem->setName(getString("quit"));
  2597. // Language menu strings
  2598. for (std::size_t i = 0; i < languageCount; ++i)
  2599. {
  2600. languageMenuItems[i]->setName(getString("language-name", i));
  2601. }
  2602. // Reset menu tweens
  2603. uiRootElement->update();
  2604. mainMenu->getContainer()->resetTweens();
  2605. settingsMenu->getContainer()->resetTweens();
  2606. controlsMenu->getContainer()->resetTweens();
  2607. pauseMenu->getContainer()->resetTweens();
  2608. languageMenu->getContainer()->resetTweens();
  2609. }
  2610. void Game::restringControlMenuItem(MenuItem* item, const std::string& name)
  2611. {
  2612. item->setName(getString(name));
  2613. Control* control = controlNameMap.find(name)->second;
  2614. std::string value;
  2615. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  2616. if (mappings != nullptr)
  2617. {
  2618. std::size_t i = 0;
  2619. for (const InputMapping* mapping: *mappings)
  2620. {
  2621. std::array<std::string, 3> mappingStrings = getInputMappingStrings(mapping);
  2622. // keyboard-key, mouse-button, gamepad-axis, etc.
  2623. std::string typeName = mappingStrings[0] + "-" + mappingStrings[1];
  2624. std::string type = getString(typeName);
  2625. if (mapping->getType() != InputMappingType::KEY)
  2626. {
  2627. value += type;
  2628. value += " ";
  2629. }
  2630. value += mappingStrings[2];
  2631. if (i < mappings->size() - 1)
  2632. {
  2633. value += ", ";
  2634. }
  2635. ++i;
  2636. }
  2637. }
  2638. item->setValue(value);
  2639. }
  2640. void Game::setTimeOfDay(float time)
  2641. {
  2642. Vector3 midnight = Vector3(0.0f, 1.0f, 0.0f);
  2643. Vector3 sunrise = Vector3(-1.0f, 0.0f, 0.0f);
  2644. Vector3 noon = Vector3(0, -1.0f, 0.0f);
  2645. Vector3 sunset = Vector3(1.0f, 0.0f, 0.0f);
  2646. float angles[4] =
  2647. {
  2648. glm::radians(270.0f), // 00:00
  2649. glm::radians(0.0f), // 06:00
  2650. glm::radians(90.0f), // 12:00
  2651. glm::radians(180.0f) // 18:00
  2652. };
  2653. int index0 = static_cast<int>(fmod(time, 24.0f) / 6.0f);
  2654. int index1 = (index0 + 1) % 4;
  2655. float t = (time - (static_cast<float>(index0) * 6.0f)) / 6.0f;
  2656. Quaternion rotation0 = glm::angleAxis(angles[index0], Vector3(1, 0, 0));
  2657. Quaternion rotation1 = glm::angleAxis(angles[index1], Vector3(1, 0, 0));
  2658. Quaternion rotation = glm::normalize(glm::slerp(rotation0, rotation1, t));
  2659. Vector3 direction = glm::normalize(rotation * Vector3(0, 0, 1));
  2660. sunlight.setDirection(direction);
  2661. Vector3 up = glm::normalize(rotation * Vector3(0, 1, 0));
  2662. sunlightCamera.lookAt(Vector3(0, 0, 0), sunlight.getDirection(), up);
  2663. }
  2664. void Game::queueScreenshot()
  2665. {
  2666. screenshotQueued = true;
  2667. cameraFlashImage->setVisible(false);
  2668. cameraGridContainer->setVisible(false);
  2669. fpsLabel->setVisible(false);
  2670. soundSystem->scrot();
  2671. }
  2672. void Game::screenshot()
  2673. {
  2674. screenshotQueued = false;
  2675. // Read pixel data from framebuffer
  2676. unsigned char* pixels = new unsigned char[w * h * 3];
  2677. glReadBuffer(GL_BACK);
  2678. glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixels);
  2679. // Get game title in current language
  2680. std::string title = getString("title");
  2681. // Convert title to lowercase
  2682. std::transform(title.begin(), title.end(), title.begin(), ::tolower);
  2683. // Create screenshot directory if it doesn't exist
  2684. std::string screenshotDirectory = configPath + std::string("screenshots/");
  2685. if (!pathExists(screenshotDirectory))
  2686. {
  2687. createDirectory(screenshotDirectory);
  2688. }
  2689. // Build screenshot file name
  2690. std::string filename = screenshotDirectory + title + "-" + timestamp() + ".png";
  2691. // Write screenshot to file in separate thread
  2692. std::thread screenshotThread(Game::saveScreenshot, filename, w, h, pixels);
  2693. screenshotThread.detach();
  2694. // Play camera flash animation
  2695. cameraFlashAnimation.stop();
  2696. cameraFlashAnimation.rewind();
  2697. cameraFlashAnimation.play();
  2698. // Play camera shutter sound
  2699. // Restore camera UI visibility
  2700. //cameraGridContainer->setVisible(true);
  2701. fpsLabel->setVisible(true);
  2702. // Whiteout screen immediately
  2703. glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
  2704. glClear(GL_COLOR_BUFFER_BIT);
  2705. }
  2706. void Game::inputMapped(const InputMapping& mapping)
  2707. {
  2708. // Skip mouse motion events
  2709. if (mapping.getType() == InputMappingType::MOUSE_MOTION)
  2710. {
  2711. return;
  2712. }
  2713. // Add input mapping to input router
  2714. if (mapping.control != nullptr)
  2715. {
  2716. inputRouter->addMapping(mapping);
  2717. }
  2718. // Disable input mapping generation
  2719. inputMapper->setControl(nullptr);
  2720. inputMapper->setEnabled(false);
  2721. // Restring UI
  2722. restringUI();
  2723. // Schedule callbacks to be enabled in 100ms
  2724. ScheduledFunctionEvent event;
  2725. event.caller = static_cast<void*>(this);
  2726. event.function = [this]()
  2727. {
  2728. // Re-enable UI callbacks
  2729. uiRootElement->setCallbacksEnabled(true);
  2730. // Re-enable menu controls
  2731. menuControls.setCallbacksEnabled(true);
  2732. };
  2733. eventDispatcher.schedule(event, time + 0.1f);
  2734. // Save control profile
  2735. saveControlProfile(*controlProfileName);
  2736. }
  2737. void Game::languageSelected()
  2738. {
  2739. // Disable non-system controls
  2740. disableNonSystemControls();
  2741. // Disable UI callbacks
  2742. uiRootElement->setCallbacksEnabled(false);
  2743. // Begin to fade out
  2744. fadeOut(0.5f, Vector3(0.0f), std::bind(&StateMachine::changeState, this, &titleState));
  2745. }
  2746. void Game::skipSplash()
  2747. {
  2748. if (StateMachine::getCurrentState() == &splashState)
  2749. {
  2750. StateMachine::changeState(&titleState);
  2751. }
  2752. }
  2753. void Game::togglePause()
  2754. {
  2755. paused = !paused;
  2756. if (paused)
  2757. {
  2758. openMenu(pauseMenu, 0);
  2759. // Enable menu controls and UI callbacks
  2760. uiRootElement->setCallbacksEnabled(true);
  2761. menuControls.setCallbacksEnabled(true);
  2762. }
  2763. else
  2764. {
  2765. closeCurrentMenu();
  2766. // Disable menu controls and UI callbacks
  2767. uiRootElement->setCallbacksEnabled(false);
  2768. menuControls.setCallbacksEnabled(false);
  2769. }
  2770. }
  2771. void Game::continueGame()
  2772. {
  2773. // Disable non-system controls
  2774. disableNonSystemControls();
  2775. // Disable UI callbacks
  2776. uiRootElement->setCallbacksEnabled(false);
  2777. // Start fading out main menu
  2778. menuFadeAnimation.setClip(&menuFadeOutClip);
  2779. menuFadeAnimation.setTimeFrame(menuFadeOutClip.getTimeFrame());
  2780. menuFadeAnimation.rewind();
  2781. menuFadeAnimation.play();
  2782. // Close menu and enter play state after it fades out
  2783. menuFadeAnimation.setEndCallback
  2784. (
  2785. [this]()
  2786. {
  2787. closeCurrentMenu();
  2788. StateMachine::changeState(&playState);
  2789. }
  2790. );
  2791. }
  2792. void Game::newGame()
  2793. {
  2794. // Disable non-system controls
  2795. disableNonSystemControls();
  2796. // Disable UI callbacks
  2797. uiRootElement->setCallbacksEnabled(false);
  2798. // Start fading out main menu
  2799. menuFadeAnimation.setClip(&menuFadeOutClip);
  2800. menuFadeAnimation.setTimeFrame(menuFadeOutClip.getTimeFrame());
  2801. menuFadeAnimation.rewind();
  2802. menuFadeAnimation.play();
  2803. // Close menu and enter play state after it fades out
  2804. menuFadeAnimation.setEndCallback
  2805. (
  2806. [this]()
  2807. {
  2808. closeCurrentMenu();
  2809. }
  2810. );
  2811. // Start to play state
  2812. fadeOut(3.0f, Vector3(0.0f), std::bind(&StateMachine::changeState, this, &playState));
  2813. }
  2814. void Game::returnToMainMenu()
  2815. {
  2816. // Disable non-system controls
  2817. disableNonSystemControls();
  2818. // Disable UI callbacks
  2819. uiRootElement->setCallbacksEnabled(false);
  2820. // Close pause menu
  2821. closeCurrentMenu();
  2822. // Fade to title state
  2823. fadeOut(3.0f, Vector3(0.0f), std::bind(&StateMachine::changeState, this, &titleState));
  2824. }
  2825. void Game::interpretCommands()
  2826. {
  2827. while (true)
  2828. {
  2829. std::cout << "> " << std::flush;
  2830. std::string line;
  2831. std::getline(std::cin, line);
  2832. try
  2833. {
  2834. auto [commandName, arguments, call] = cli->interpret(line);
  2835. if (call)
  2836. {
  2837. call();
  2838. }
  2839. else
  2840. {
  2841. if (!commandName.empty())
  2842. {
  2843. std::cout << "Unknown command " << commandName << std::endl;
  2844. }
  2845. }
  2846. }
  2847. catch (const std::invalid_argument& e)
  2848. {
  2849. std::string commandName = line.substr(0, line.find(' '));
  2850. auto& helpStrings = cli->help();
  2851. if (auto it = helpStrings.find(commandName); it != helpStrings.end())
  2852. {
  2853. std::cout << "Usage: " << it->second << std::endl;
  2854. }
  2855. else
  2856. {
  2857. std::cout << commandName << ": Invalid arguments" << std::endl;
  2858. }
  2859. }
  2860. }
  2861. }
  2862. void Game::boxSelect(float x, float y, float w, float h)
  2863. {
  2864. boxSelectionContainer->setTranslation(Vector2(x, y));
  2865. boxSelectionContainer->setDimensions(Vector2(w, h));
  2866. boxSelectionImageBackground->setDimensions(Vector2(w, h));
  2867. boxSelectionImageTop->setDimensions(Vector2(w, boxSelectionBorderWidth));
  2868. boxSelectionImageBottom->setDimensions(Vector2(w, boxSelectionBorderWidth));
  2869. boxSelectionImageLeft->setDimensions(Vector2(boxSelectionBorderWidth, h));
  2870. boxSelectionImageRight->setDimensions(Vector2(boxSelectionBorderWidth, h));
  2871. boxSelectionContainer->setVisible(true);
  2872. }
  2873. void Game::fadeIn(float duration, const Vector3& color, std::function<void()> callback)
  2874. {
  2875. if (fadeInAnimation.isPlaying())
  2876. {
  2877. return;
  2878. }
  2879. fadeOutAnimation.stop();
  2880. this->fadeInEndCallback = callback;
  2881. blackoutImage->setTintColor(Vector4(color, 1.0f));
  2882. blackoutImage->setVisible(true);
  2883. fadeInAnimation.setSpeed(1.0f / duration);
  2884. fadeInAnimation.setLoop(false);
  2885. fadeInAnimation.setClip(&fadeInClip);
  2886. fadeInAnimation.setTimeFrame(fadeInClip.getTimeFrame());
  2887. fadeInAnimation.rewind();
  2888. fadeInAnimation.play();
  2889. blackoutImage->resetTweens();
  2890. uiRootElement->update();
  2891. }
  2892. void Game::fadeOut(float duration, const Vector3& color, std::function<void()> callback)
  2893. {
  2894. if (fadeOutAnimation.isPlaying())
  2895. {
  2896. return;
  2897. }
  2898. fadeInAnimation.stop();
  2899. this->fadeOutEndCallback = callback;
  2900. blackoutImage->setVisible(true);
  2901. blackoutImage->setTintColor(Vector4(color, 0.0f));
  2902. fadeOutAnimation.setSpeed(1.0f / duration);
  2903. fadeOutAnimation.setLoop(false);
  2904. fadeOutAnimation.setClip(&fadeOutClip);
  2905. fadeOutAnimation.setTimeFrame(fadeOutClip.getTimeFrame());
  2906. fadeOutAnimation.rewind();
  2907. fadeOutAnimation.play();
  2908. blackoutImage->resetTweens();
  2909. uiRootElement->update();
  2910. }
  2911. void Game::stopFade()
  2912. {
  2913. fadeInAnimation.stop();
  2914. fadeOutAnimation.stop();
  2915. blackoutImage->setVisible(false);
  2916. uiRootElement->update();
  2917. }
  2918. void Game::selectTool(int toolIndex)
  2919. {
  2920. Tool* tools[] =
  2921. {
  2922. brush,
  2923. nullptr,
  2924. lens,
  2925. nullptr,
  2926. forceps,
  2927. nullptr,
  2928. nullptr,
  2929. nullptr
  2930. };
  2931. Tool* nextTool = tools[toolIndex];
  2932. if (nextTool != currentTool)
  2933. {
  2934. if (currentTool)
  2935. {
  2936. currentTool->setActive(false);
  2937. currentTool->update(0.0f);
  2938. }
  2939. currentTool = nextTool;
  2940. if (currentTool)
  2941. {
  2942. currentTool->setActive(true);
  2943. }
  2944. }
  2945. if (1)
  2946. {
  2947. toolIndicatorIconImage->setTextureBounds(toolIndicatorsBounds[toolIndex]);
  2948. toolIndicatorIconImage->setVisible(true);
  2949. }
  2950. else
  2951. {
  2952. toolIndicatorIconImage->setVisible(false);
  2953. }
  2954. }
  2955. void Game::nextControlProfile()
  2956. {
  2957. }
  2958. EntityID Game::createInstance()
  2959. {
  2960. return entityManager->createEntity();
  2961. }
  2962. EntityID Game::createNamedInstance(const std::string& instanceName)
  2963. {
  2964. EntityID entity = entityManager->createEntity();
  2965. cli->set(instanceName, std::to_string(entity));
  2966. return entity;
  2967. }
  2968. EntityID Game::createInstanceOf(const std::string& templateName)
  2969. {
  2970. EntityTemplate* entityTemplate = resourceManager->load<EntityTemplate>(templateName + ".ent");
  2971. EntityID entity = entityManager->createEntity();
  2972. entityTemplate->apply(entity, componentManager);
  2973. return entity;
  2974. }
  2975. EntityID Game::createNamedInstanceOf(const std::string& templateName, const std::string& instanceName)
  2976. {
  2977. EntityTemplate* entityTemplate = resourceManager->load<EntityTemplate>(templateName + ".ent");
  2978. EntityID entity = entityManager->createEntity();
  2979. entityTemplate->apply(entity, componentManager);
  2980. cli->set(instanceName, std::to_string(entity));
  2981. return entity;
  2982. }
  2983. void Game::destroyInstance(EntityID entity)
  2984. {
  2985. entityManager->destroyEntity(entity);
  2986. }
  2987. void Game::addComponent(EntityID entity, ComponentBase* component)
  2988. {
  2989. componentManager->addComponent(entity, component);
  2990. }
  2991. void Game::removeComponent(EntityID entity, ComponentType type)
  2992. {
  2993. ComponentBase* component = componentManager->removeComponent(entity, type);
  2994. delete component;
  2995. }
  2996. void Game::setTransform(EntityID entity, const Transform& transform)
  2997. {
  2998. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  2999. if (!component)
  3000. {
  3001. return;
  3002. }
  3003. component->transform = transform;
  3004. }
  3005. void Game::setTranslation(EntityID entity, const Vector3& translation)
  3006. {
  3007. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  3008. if (!component)
  3009. {
  3010. return;
  3011. }
  3012. component->transform.translation = translation;
  3013. }
  3014. void Game::setRotation(EntityID entity, const Quaternion& rotation)
  3015. {
  3016. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  3017. if (!component)
  3018. {
  3019. return;
  3020. }
  3021. component->transform.rotation = rotation;
  3022. }
  3023. void Game::setScale(EntityID entity, const Vector3& scale)
  3024. {
  3025. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  3026. if (!component)
  3027. {
  3028. return;
  3029. }
  3030. component->transform.scale = scale;
  3031. }
  3032. void Game::translate(EntityID entity, const Vector3& translation)
  3033. {
  3034. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  3035. if (!component)
  3036. {
  3037. return;
  3038. }
  3039. component->transform.translation += translation;
  3040. }
  3041. void Game::rotate(EntityID entity, const Quaternion& rotation)
  3042. {
  3043. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  3044. if (!component)
  3045. {
  3046. return;
  3047. }
  3048. component->transform.rotation = component->transform.rotation * rotation;
  3049. }
  3050. void Game::scale(EntityID entity, const Vector3& scale)
  3051. {
  3052. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  3053. if (!component)
  3054. {
  3055. return;
  3056. }
  3057. component->transform.scale *= scale;
  3058. }
  3059. void Game::setTerrainPatchPosition(EntityID entity, const std::tuple<int, int>& position)
  3060. {
  3061. TerrainPatchComponent* component = componentManager->getComponent<TerrainPatchComponent>(entity);
  3062. if (!component)
  3063. {
  3064. return;
  3065. }
  3066. component->position = position;
  3067. }
  3068. void Game::saveScreenshot(const std::string& filename, unsigned int width, unsigned int height, unsigned char* pixels)
  3069. {
  3070. stbi_flip_vertically_on_write(1);
  3071. stbi_write_png(filename.c_str(), width, height, 3, pixels, width * 3);
  3072. delete[] pixels;
  3073. }