💿🐜 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.

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