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

1062 lines
39 KiB

  1. /*
  2. * Copyright (C) 2021 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 "animation/animation.hpp"
  20. #include "animation/animator.hpp"
  21. #include "animation/ease.hpp"
  22. #include "animation/screen-transition.hpp"
  23. #include "animation/timeline.hpp"
  24. #include "application.hpp"
  25. #include "debug/cli.hpp"
  26. #include "debug/console-commands.hpp"
  27. #include "debug/logger.hpp"
  28. #include "game/context.hpp"
  29. #include "gl/framebuffer.hpp"
  30. #include "gl/pixel-format.hpp"
  31. #include "gl/pixel-type.hpp"
  32. #include "gl/rasterizer.hpp"
  33. #include "gl/texture-2d.hpp"
  34. #include "gl/texture-filter.hpp"
  35. #include "gl/texture-wrapping.hpp"
  36. #include "gl/vertex-array.hpp"
  37. #include "gl/vertex-attribute-type.hpp"
  38. #include "gl/vertex-buffer.hpp"
  39. #include "renderer/material-flags.hpp"
  40. #include "renderer/material-property.hpp"
  41. #include "renderer/passes/bloom-pass.hpp"
  42. #include "renderer/passes/clear-pass.hpp"
  43. #include "renderer/passes/final-pass.hpp"
  44. #include "renderer/passes/material-pass.hpp"
  45. #include "renderer/passes/outline-pass.hpp"
  46. #include "renderer/passes/shadow-map-pass.hpp"
  47. #include "renderer/passes/sky-pass.hpp"
  48. #include "renderer/simple-render-pass.hpp"
  49. #include "renderer/vertex-attributes.hpp"
  50. #include "renderer/compositor.hpp"
  51. #include "renderer/renderer.hpp"
  52. #include "resources/resource-manager.hpp"
  53. #include "resources/resource-manager.hpp"
  54. #include "scene/scene.hpp"
  55. #include "game/states/loading.hpp"
  56. #include "entity/systems/behavior.hpp"
  57. #include "entity/systems/camera.hpp"
  58. #include "entity/systems/collision.hpp"
  59. #include "entity/systems/constraint.hpp"
  60. #include "entity/systems/locomotion.hpp"
  61. #include "entity/systems/snapping.hpp"
  62. #include "entity/systems/render.hpp"
  63. #include "entity/systems/samara.hpp"
  64. #include "entity/systems/subterrain.hpp"
  65. #include "entity/systems/terrain.hpp"
  66. #include "entity/systems/ui.hpp"
  67. #include "entity/systems/vegetation.hpp"
  68. #include "entity/systems/spatial.hpp"
  69. #include "entity/systems/tracking.hpp"
  70. #include "entity/systems/painting.hpp"
  71. #include "entity/systems/astronomy.hpp"
  72. #include "entity/systems/blackbody.hpp"
  73. #include "entity/systems/atmosphere.hpp"
  74. #include "entity/systems/orbit.hpp"
  75. #include "entity/systems/proteome.hpp"
  76. #include "entity/components/marker.hpp"
  77. #include "entity/commands.hpp"
  78. #include "utility/paths.hpp"
  79. #include "event/event-dispatcher.hpp"
  80. #include "input/event-router.hpp"
  81. #include "input/mapper.hpp"
  82. #include "input/listener.hpp"
  83. #include "input/gamepad.hpp"
  84. #include "input/mouse.hpp"
  85. #include "input/keyboard.hpp"
  86. #include "configuration.hpp"
  87. #include "input/scancode.hpp"
  88. #include <cxxopts.hpp>
  89. #include <dirent.h>
  90. #include <entt/entt.hpp>
  91. #include <filesystem>
  92. #include <functional>
  93. #include <string>
  94. #include <vector>
  95. #include <execution>
  96. #include <algorithm>
  97. static constexpr double seconds_per_day = 24.0 * 60.0 * 60.0;
  98. static void parse_options(game::context* ctx, int argc, char** argv);
  99. static void setup_resources(game::context* ctx);
  100. static void load_config(game::context* ctx);
  101. static void load_strings(game::context* ctx);
  102. static void setup_window(game::context* ctx);
  103. static void setup_rendering(game::context* ctx);
  104. static void setup_scenes(game::context* ctx);
  105. static void setup_animation(game::context* ctx);
  106. static void setup_entities(game::context* ctx);
  107. static void setup_systems(game::context* ctx);
  108. static void setup_controls(game::context* ctx);
  109. static void setup_cli(game::context* ctx);
  110. static void setup_callbacks(game::context* ctx);
  111. int bootloader(application* app, int argc, char** argv)
  112. {
  113. // Get application logger
  114. debug::logger* logger = app->get_logger();
  115. logger->push_task("Running application bootloader");
  116. // Allocate game context
  117. game::context* ctx = new game::context();
  118. ctx->app = app;
  119. ctx->logger = logger;
  120. // Init game context
  121. try
  122. {
  123. parse_options(ctx, argc, argv);
  124. setup_resources(ctx);
  125. load_config(ctx);
  126. load_strings(ctx);
  127. setup_window(ctx);
  128. setup_rendering(ctx);
  129. setup_scenes(ctx);
  130. setup_animation(ctx);
  131. setup_entities(ctx);
  132. setup_systems(ctx);
  133. setup_controls(ctx);
  134. setup_cli(ctx);
  135. setup_callbacks(ctx);
  136. }
  137. catch (const std::exception& e)
  138. {
  139. logger->error("Caught exception: \"" + std::string(e.what()) + "\"");
  140. logger->pop_task(EXIT_FAILURE);
  141. return EXIT_FAILURE;
  142. }
  143. logger->pop_task(EXIT_SUCCESS);
  144. // Set update rate
  145. if (ctx->config->contains("update_rate"))
  146. {
  147. app->set_update_rate((*ctx->config)["update_rate"].get<double>());
  148. }
  149. // Setup initial application state
  150. application::state initial_state;
  151. initial_state.name = "loading";
  152. initial_state.enter = std::bind(game::state::loading::enter, ctx);
  153. initial_state.exit = std::bind(game::state::loading::exit, ctx);
  154. // Enter initial application state
  155. app->change_state(initial_state);
  156. return EXIT_SUCCESS;
  157. }
  158. void parse_options(game::context* ctx, int argc, char** argv)
  159. {
  160. debug::logger* logger = ctx->logger;
  161. logger->push_task("Parsing command line options");
  162. try
  163. {
  164. cxxopts::Options options("Antkeeper", "Ant colony simulation game");
  165. options.add_options()
  166. ("c,continue", "Continues from the last save")
  167. ("d,data", "Sets the data package path", cxxopts::value<std::string>())
  168. ("f,fullscreen", "Starts in fullscreen mode")
  169. ("n,new-game", "Starts a new game")
  170. ("q,quick-start", "Skips to the main menu")
  171. ("r,reset", "Restores all settings to default")
  172. ("v,vsync", "Enables or disables v-sync", cxxopts::value<int>())
  173. ("w,windowed", "Starts in windowed mode");
  174. auto result = options.parse(argc, argv);
  175. // --continue
  176. if (result.count("continue"))
  177. ctx->option_continue = true;
  178. // --data
  179. if (result.count("data"))
  180. ctx->option_data = result["data"].as<std::string>();
  181. // --fullscreen
  182. if (result.count("fullscreen"))
  183. ctx->option_fullscreen = true;
  184. // --new-game
  185. if (result.count("new-game"))
  186. ctx->option_new_game = true;
  187. // --quick-start
  188. if (result.count("quick-start"))
  189. ctx->option_quick_start = true;
  190. // --reset
  191. if (result.count("reset"))
  192. ctx->option_reset = true;
  193. // --vsync
  194. if (result.count("vsync"))
  195. ctx->option_vsync = (result["vsync"].as<int>()) ? true : false;
  196. // --windowed
  197. if (result.count("windowed"))
  198. ctx->option_windowed = true;
  199. }
  200. catch (const std::exception& e)
  201. {
  202. logger->error("Exception caught: \"" + std::string(e.what()) + "\"");
  203. logger->pop_task(EXIT_FAILURE);
  204. return;
  205. }
  206. logger->pop_task(EXIT_SUCCESS);
  207. }
  208. void setup_resources(game::context* ctx)
  209. {
  210. debug::logger* logger = ctx->logger;
  211. // Setup resource manager
  212. ctx->resource_manager = new resource_manager(logger);
  213. // Determine application name
  214. std::string application_name;
  215. #if defined(_WIN32) || defined(__APPLE__)
  216. application_name = "Antkeeper";
  217. #else
  218. application_name = "antkeeper";
  219. #endif
  220. // Detect paths
  221. ctx->data_path = get_data_path(application_name);
  222. ctx->config_path = get_config_path(application_name);
  223. ctx->mods_path = ctx->config_path + "mods/";
  224. ctx->saves_path = ctx->config_path + "saves/";
  225. ctx->screenshots_path = ctx->config_path + "screenshots/";
  226. ctx->controls_path = ctx->config_path + "controls/";
  227. // Log resource paths
  228. logger->log("Detected data path as \"" + ctx->data_path + "\"");
  229. logger->log("Detected config path as \"" + ctx->config_path + "\"");
  230. // Create nonexistent config directories
  231. std::vector<std::string> config_paths;
  232. config_paths.push_back(ctx->config_path);
  233. config_paths.push_back(ctx->mods_path);
  234. config_paths.push_back(ctx->saves_path);
  235. config_paths.push_back(ctx->screenshots_path);
  236. config_paths.push_back(ctx->controls_path);
  237. for (const std::string& path: config_paths)
  238. {
  239. if (!path_exists(path))
  240. {
  241. logger->push_task("Creating directory \"" + path + "\"");
  242. if (create_directory(path))
  243. {
  244. logger->pop_task(EXIT_SUCCESS);
  245. }
  246. else
  247. {
  248. logger->pop_task(EXIT_FAILURE);
  249. }
  250. }
  251. }
  252. // Redirect logger output to log file on non-debug builds
  253. #if defined(NDEBUG)
  254. std::string log_filename = config_path + "log.txt";
  255. ctx->log_filestream.open(log_filename.c_str());
  256. ctx->log_filestream << logger->get_history();
  257. logger->redirect(&log_filestream);
  258. #endif
  259. // Scan for mods
  260. std::vector<std::string> mods;
  261. struct dirent** files = nullptr;
  262. if (int n = scandir(ctx->mods_path.c_str(), &files, NULL, alphasort); n >= 0)
  263. {
  264. for (int i = 0; i < n; ++i)
  265. {
  266. struct dirent* file = files[i];
  267. switch (file->d_type)
  268. {
  269. case DT_REG:
  270. case DT_DIR:
  271. {
  272. std::string mod_name = file->d_name;
  273. // Skip hidden files and directories
  274. if (mod_name.front() == '.')
  275. break;
  276. mods.push_back(mod_name);
  277. }
  278. default:
  279. break;
  280. }
  281. }
  282. }
  283. // Determine data package path
  284. if (ctx->option_data.has_value())
  285. {
  286. ctx->data_package_path = ctx->option_data.value();
  287. if (std::filesystem::path(ctx->data_package_path).is_relative())
  288. ctx->data_package_path = ctx->data_path + ctx->data_package_path;
  289. }
  290. else
  291. {
  292. ctx->data_package_path = ctx->data_path + "data.zip";
  293. }
  294. // Mount mods
  295. for (const std::string& mod_name: mods)
  296. ctx->resource_manager->mount(ctx->mods_path + mod_name);
  297. // Mount config path
  298. ctx->resource_manager->mount(ctx->config_path);
  299. // Mount data package
  300. ctx->resource_manager->mount(ctx->data_package_path);
  301. // Include resource search paths in order of priority
  302. ctx->resource_manager->include("/shaders/");
  303. ctx->resource_manager->include("/models/");
  304. ctx->resource_manager->include("/images/");
  305. ctx->resource_manager->include("/textures/");
  306. ctx->resource_manager->include("/materials/");
  307. ctx->resource_manager->include("/entities/");
  308. ctx->resource_manager->include("/behaviors/");
  309. ctx->resource_manager->include("/controls/");
  310. ctx->resource_manager->include("/localization/");
  311. ctx->resource_manager->include("/biomes/");
  312. ctx->resource_manager->include("/traits/");
  313. ctx->resource_manager->include("/");
  314. }
  315. void load_config(game::context* ctx)
  316. {
  317. debug::logger* logger = ctx->logger;
  318. logger->push_task("Loading config");
  319. // Load config file
  320. ctx->config = ctx->resource_manager->load<json>("config.json");
  321. if (!ctx->config)
  322. {
  323. logger->pop_task(EXIT_FAILURE);
  324. return;
  325. }
  326. logger->pop_task(EXIT_SUCCESS);
  327. }
  328. void load_strings(game::context* ctx)
  329. {
  330. debug::logger* logger = ctx->logger;
  331. logger->push_task("Loading strings");
  332. ctx->string_table = ctx->resource_manager->load<string_table>("strings.csv");
  333. build_string_table_map(&ctx->string_table_map, *ctx->string_table);
  334. ctx->language_code = (*ctx->config)["language"].get<std::string>();
  335. ctx->language_index = -1;
  336. for (int i = 2; i < (*ctx->string_table)[0].size(); ++i)
  337. {
  338. if ((*ctx->string_table)[0][i] == ctx->language_code)
  339. ctx->language_index = i;
  340. }
  341. logger->log("lang index: " + std::to_string(ctx->language_index));
  342. ctx->strings = &ctx->string_table_map[ctx->language_code];
  343. logger->pop_task(EXIT_SUCCESS);
  344. }
  345. void setup_window(game::context* ctx)
  346. {
  347. debug::logger* logger = ctx->logger;
  348. logger->push_task("Setting up window");
  349. application* app = ctx->app;
  350. json* config = ctx->config;
  351. // Set fullscreen or windowed mode
  352. bool fullscreen = true;
  353. if (ctx->option_fullscreen.has_value())
  354. fullscreen = true;
  355. else if (ctx->option_windowed.has_value())
  356. fullscreen = false;
  357. else if (config->contains("fullscreen"))
  358. fullscreen = (*config)["fullscreen"].get<bool>();
  359. app->set_fullscreen(fullscreen);
  360. // Set resolution
  361. const auto& display_dimensions = ctx->app->get_display_dimensions();
  362. int2 resolution = {display_dimensions[0], display_dimensions[1]};
  363. if (fullscreen)
  364. {
  365. if (config->contains("fullscreen_resolution"))
  366. {
  367. resolution.x = (*config)["fullscreen_resolution"][0].get<int>();
  368. resolution.y = (*config)["fullscreen_resolution"][1].get<int>();
  369. }
  370. }
  371. else
  372. {
  373. if (config->contains("windowed_resolution"))
  374. {
  375. resolution.x = (*config)["windowed_resolution"][0].get<int>();
  376. resolution.y = (*config)["windowed_resolution"][1].get<int>();
  377. }
  378. }
  379. app->resize_window(resolution.x, resolution.y);
  380. // Set v-sync
  381. bool vsync = true;
  382. if (ctx->option_vsync.has_value())
  383. vsync = (ctx->option_vsync.value() != 0);
  384. else if (config->contains("vsync"))
  385. vsync = (*config)["vsync"].get<bool>();
  386. app->set_vsync(vsync);
  387. // Set title
  388. app->set_title((*ctx->strings)["title"]);
  389. logger->pop_task(EXIT_SUCCESS);
  390. }
  391. void setup_rendering(game::context* ctx)
  392. {
  393. debug::logger* logger = ctx->logger;
  394. logger->push_task("Setting up rendering");
  395. // Get rasterizer from application
  396. ctx->rasterizer = ctx->app->get_rasterizer();
  397. // Get default framebuffer
  398. const gl::framebuffer& default_framebuffer = ctx->rasterizer->get_default_framebuffer();
  399. const auto& viewport_dimensions = default_framebuffer.get_dimensions();
  400. // Create HDR framebuffer (32F color, 32F depth)
  401. ctx->framebuffer_hdr_color = new gl::texture_2d(viewport_dimensions[0], viewport_dimensions[1], gl::pixel_type::float_32, gl::pixel_format::rgb);
  402. ctx->framebuffer_hdr_color->set_wrapping(gl::texture_wrapping::extend, gl::texture_wrapping::extend);
  403. ctx->framebuffer_hdr_color->set_filters(gl::texture_min_filter::linear, gl::texture_mag_filter::linear);
  404. ctx->framebuffer_hdr_color->set_max_anisotropy(0.0f);
  405. ctx->framebuffer_hdr_depth = new gl::texture_2d(viewport_dimensions[0], viewport_dimensions[1], gl::pixel_type::float_32, gl::pixel_format::ds);
  406. ctx->framebuffer_hdr_depth->set_wrapping(gl::texture_wrapping::extend, gl::texture_wrapping::extend);
  407. ctx->framebuffer_hdr_depth->set_filters(gl::texture_min_filter::linear, gl::texture_mag_filter::linear);
  408. ctx->framebuffer_hdr_depth->set_max_anisotropy(0.0f);
  409. ctx->framebuffer_hdr = new gl::framebuffer(viewport_dimensions[0], viewport_dimensions[1]);
  410. ctx->framebuffer_hdr->attach(gl::framebuffer_attachment_type::color, ctx->framebuffer_hdr_color);
  411. ctx->framebuffer_hdr->attach(gl::framebuffer_attachment_type::depth, ctx->framebuffer_hdr_depth);
  412. ctx->framebuffer_hdr->attach(gl::framebuffer_attachment_type::stencil, ctx->framebuffer_hdr_depth);
  413. // Create shadow map framebuffer
  414. int shadow_map_resolution = 4096;
  415. if (ctx->config->contains("shadow_map_resolution"))
  416. {
  417. shadow_map_resolution = (*ctx->config)["shadow_map_resolution"].get<int>();
  418. }
  419. ctx->shadow_map_depth_texture = new gl::texture_2d(shadow_map_resolution, shadow_map_resolution, gl::pixel_type::float_32, gl::pixel_format::d);
  420. ctx->shadow_map_depth_texture->set_wrapping(gl::texture_wrapping::extend, gl::texture_wrapping::extend);
  421. ctx->shadow_map_depth_texture->set_filters(gl::texture_min_filter::linear, gl::texture_mag_filter::linear);
  422. ctx->shadow_map_depth_texture->set_max_anisotropy(0.0f);
  423. ctx->shadow_map_framebuffer = new gl::framebuffer(shadow_map_resolution, shadow_map_resolution);
  424. ctx->shadow_map_framebuffer->attach(gl::framebuffer_attachment_type::depth, ctx->shadow_map_depth_texture);
  425. // Create bloom pingpong framebuffers (16F color, no depth)
  426. int bloom_width = viewport_dimensions[0] >> 1;
  427. int bloom_height = viewport_dimensions[1] >> 1;
  428. ctx->bloom_texture = new gl::texture_2d(bloom_width, bloom_height, gl::pixel_type::float_16, gl::pixel_format::rgb);
  429. ctx->bloom_texture->set_wrapping(gl::texture_wrapping::extend, gl::texture_wrapping::extend);
  430. ctx->bloom_texture->set_filters(gl::texture_min_filter::linear, gl::texture_mag_filter::linear);
  431. ctx->bloom_texture->set_max_anisotropy(0.0f);
  432. ctx->framebuffer_bloom = new gl::framebuffer(bloom_width, bloom_height);
  433. ctx->framebuffer_bloom->attach(gl::framebuffer_attachment_type::color, ctx->bloom_texture);
  434. // Load blue noise texture
  435. gl::texture_2d* blue_noise_map = ctx->resource_manager->load<gl::texture_2d>("blue-noise.tex");
  436. // Load fallback material
  437. ctx->fallback_material = ctx->resource_manager->load<material>("fallback.mtl");
  438. // Setup common render passes
  439. {
  440. ctx->common_bloom_pass = new bloom_pass(ctx->rasterizer, ctx->framebuffer_bloom, ctx->resource_manager);
  441. ctx->common_bloom_pass->set_source_texture(ctx->framebuffer_hdr_color);
  442. ctx->common_bloom_pass->set_brightness_threshold(1.0f);
  443. ctx->common_bloom_pass->set_blur_iterations(5);
  444. ctx->common_final_pass = new ::final_pass(ctx->rasterizer, &ctx->rasterizer->get_default_framebuffer(), ctx->resource_manager);
  445. ctx->common_final_pass->set_color_texture(ctx->framebuffer_hdr_color);
  446. ctx->common_final_pass->set_bloom_texture(ctx->bloom_texture);
  447. ctx->common_final_pass->set_blue_noise_texture(blue_noise_map);
  448. }
  449. // Setup UI compositor
  450. {
  451. ctx->ui_clear_pass = new clear_pass(ctx->rasterizer, &ctx->rasterizer->get_default_framebuffer());
  452. ctx->ui_clear_pass->set_cleared_buffers(false, true, false);
  453. ctx->ui_clear_pass->set_clear_depth(0.0f);
  454. ctx->ui_material_pass = new material_pass(ctx->rasterizer, &ctx->rasterizer->get_default_framebuffer(), ctx->resource_manager);
  455. ctx->ui_material_pass->set_fallback_material(ctx->fallback_material);
  456. ctx->ui_compositor = new compositor();
  457. ctx->ui_compositor->add_pass(ctx->ui_clear_pass);
  458. ctx->ui_compositor->add_pass(ctx->ui_material_pass);
  459. }
  460. // Setup underground compositor
  461. {
  462. ctx->underground_clear_pass = new clear_pass(ctx->rasterizer, ctx->framebuffer_hdr);
  463. ctx->underground_clear_pass->set_cleared_buffers(true, true, false);
  464. ctx->underground_clear_pass->set_clear_color({1, 0, 1, 0});
  465. ctx->underground_clear_pass->set_clear_depth(0.0f);
  466. ctx->underground_material_pass = new material_pass(ctx->rasterizer, ctx->framebuffer_hdr, ctx->resource_manager);
  467. ctx->underground_material_pass->set_fallback_material(ctx->fallback_material);
  468. ctx->app->get_event_dispatcher()->subscribe<mouse_moved_event>(ctx->underground_material_pass);
  469. ctx->underground_compositor = new compositor();
  470. ctx->underground_compositor->add_pass(ctx->underground_clear_pass);
  471. ctx->underground_compositor->add_pass(ctx->underground_material_pass);
  472. ctx->underground_compositor->add_pass(ctx->common_bloom_pass);
  473. ctx->underground_compositor->add_pass(ctx->common_final_pass);
  474. }
  475. // Setup surface compositor
  476. {
  477. ctx->surface_shadow_map_clear_pass = new clear_pass(ctx->rasterizer, ctx->shadow_map_framebuffer);
  478. ctx->surface_shadow_map_clear_pass->set_cleared_buffers(false, true, false);
  479. ctx->surface_shadow_map_clear_pass->set_clear_depth(1.0f);
  480. ctx->surface_shadow_map_pass = new shadow_map_pass(ctx->rasterizer, ctx->shadow_map_framebuffer, ctx->resource_manager);
  481. ctx->surface_shadow_map_pass->set_split_scheme_weight(0.75f);
  482. ctx->surface_clear_pass = new clear_pass(ctx->rasterizer, ctx->framebuffer_hdr);
  483. ctx->surface_clear_pass->set_cleared_buffers(true, true, true);
  484. ctx->surface_clear_pass->set_clear_depth(0.0f);
  485. ctx->surface_sky_pass = new sky_pass(ctx->rasterizer, ctx->framebuffer_hdr, ctx->resource_manager);
  486. ctx->app->get_event_dispatcher()->subscribe<mouse_moved_event>(ctx->surface_sky_pass);
  487. ctx->surface_material_pass = new material_pass(ctx->rasterizer, ctx->framebuffer_hdr, ctx->resource_manager);
  488. ctx->surface_material_pass->set_fallback_material(ctx->fallback_material);
  489. ctx->surface_material_pass->shadow_map_pass = ctx->surface_shadow_map_pass;
  490. ctx->surface_material_pass->shadow_map = ctx->shadow_map_depth_texture;
  491. ctx->app->get_event_dispatcher()->subscribe<mouse_moved_event>(ctx->surface_material_pass);
  492. ctx->surface_outline_pass = new outline_pass(ctx->rasterizer, ctx->framebuffer_hdr, ctx->resource_manager);
  493. ctx->surface_outline_pass->set_outline_width(0.25f);
  494. ctx->surface_outline_pass->set_outline_color(float4{1.0f, 1.0f, 1.0f, 1.0f});
  495. ctx->surface_compositor = new compositor();
  496. ctx->surface_compositor->add_pass(ctx->surface_shadow_map_clear_pass);
  497. ctx->surface_compositor->add_pass(ctx->surface_shadow_map_pass);
  498. ctx->surface_compositor->add_pass(ctx->surface_clear_pass);
  499. ctx->surface_compositor->add_pass(ctx->surface_sky_pass);
  500. ctx->surface_compositor->add_pass(ctx->surface_material_pass);
  501. //ctx->surface_compositor->add_pass(ctx->surface_outline_pass);
  502. ctx->surface_compositor->add_pass(ctx->common_bloom_pass);
  503. ctx->surface_compositor->add_pass(ctx->common_final_pass);
  504. }
  505. // Create billboard VAO
  506. {
  507. const float billboard_vertex_data[] =
  508. {
  509. -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f,
  510. -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
  511. 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
  512. 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
  513. -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
  514. 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f
  515. };
  516. std::size_t billboard_vertex_size = 8;
  517. std::size_t billboard_vertex_stride = sizeof(float) * billboard_vertex_size;
  518. std::size_t billboard_vertex_count = 6;
  519. ctx->billboard_vbo = new gl::vertex_buffer(sizeof(float) * billboard_vertex_size * billboard_vertex_count, billboard_vertex_data);
  520. ctx->billboard_vao = new gl::vertex_array();
  521. ctx->billboard_vao->bind_attribute(VERTEX_POSITION_LOCATION, *ctx->billboard_vbo, 3, gl::vertex_attribute_type::float_32, billboard_vertex_stride, 0);
  522. ctx->billboard_vao->bind_attribute(VERTEX_TEXCOORD_LOCATION, *ctx->billboard_vbo, 2, gl::vertex_attribute_type::float_32, billboard_vertex_stride, sizeof(float) * 3);
  523. ctx->billboard_vao->bind_attribute(VERTEX_BARYCENTRIC_LOCATION, *ctx->billboard_vbo, 3, gl::vertex_attribute_type::float_32, billboard_vertex_stride, sizeof(float) * 5);
  524. }
  525. // Load marker albedo textures
  526. ctx->marker_albedo_textures = new gl::texture_2d*[8];
  527. ctx->marker_albedo_textures[0] = ctx->resource_manager->load<gl::texture_2d>("marker-clear-albedo.tex");
  528. ctx->marker_albedo_textures[1] = ctx->resource_manager->load<gl::texture_2d>("marker-yellow-albedo.tex");
  529. ctx->marker_albedo_textures[2] = ctx->resource_manager->load<gl::texture_2d>("marker-green-albedo.tex");
  530. ctx->marker_albedo_textures[3] = ctx->resource_manager->load<gl::texture_2d>("marker-blue-albedo.tex");
  531. ctx->marker_albedo_textures[4] = ctx->resource_manager->load<gl::texture_2d>("marker-purple-albedo.tex");
  532. ctx->marker_albedo_textures[5] = ctx->resource_manager->load<gl::texture_2d>("marker-pink-albedo.tex");
  533. ctx->marker_albedo_textures[6] = ctx->resource_manager->load<gl::texture_2d>("marker-red-albedo.tex");
  534. ctx->marker_albedo_textures[7] = ctx->resource_manager->load<gl::texture_2d>("marker-orange-albedo.tex");
  535. // Create renderer
  536. ctx->renderer = new renderer();
  537. ctx->renderer->set_billboard_vao(ctx->billboard_vao);
  538. logger->pop_task(EXIT_SUCCESS);
  539. }
  540. void setup_scenes(game::context* ctx)
  541. {
  542. debug::logger* logger = ctx->logger;
  543. logger->push_task("Setting up scenes");
  544. // Get default framebuffer
  545. const auto& viewport_dimensions = ctx->rasterizer->get_default_framebuffer().get_dimensions();
  546. const float viewport_aspect_ratio = static_cast<float>(viewport_dimensions[0]) / static_cast<float>(viewport_dimensions[1]);
  547. // Create infinite culling mask
  548. const float inf = std::numeric_limits<float>::infinity();
  549. ctx->no_cull = {{-inf, -inf, -inf}, {inf, inf, inf}};
  550. // Setup UI camera
  551. ctx->ui_camera = new scene::camera();
  552. ctx->ui_camera->set_compositor(ctx->ui_compositor);
  553. // Setup underground camera
  554. ctx->underground_camera = new scene::camera();
  555. ctx->underground_camera->set_perspective(math::radians<float>(45.0f), viewport_aspect_ratio, 0.1f, 1000.0f);
  556. ctx->underground_camera->set_compositor(ctx->underground_compositor);
  557. ctx->underground_camera->set_composite_index(0);
  558. ctx->underground_camera->set_active(false);
  559. // Setup surface camera
  560. ctx->surface_camera = new scene::camera();
  561. ctx->surface_camera->set_perspective(math::radians<float>(45.0f), viewport_aspect_ratio, 0.1f, 1000.0f);
  562. ctx->surface_camera->set_compositor(ctx->surface_compositor);
  563. ctx->surface_camera->set_composite_index(0);
  564. ctx->surface_camera->set_active(false);
  565. // Setup UI scene
  566. {
  567. ctx->ui_scene = new scene::collection();
  568. const gl::texture_2d* splash_texture = ctx->resource_manager->load<gl::texture_2d>("splash.tex");
  569. auto splash_dimensions = splash_texture->get_dimensions();
  570. ctx->splash_billboard_material = new material();
  571. ctx->splash_billboard_material->set_shader_program(ctx->resource_manager->load<gl::shader_program>("ui-element-textured.glsl"));
  572. ctx->splash_billboard_material->add_property<const gl::texture_2d*>("background")->set_value(splash_texture);
  573. ctx->splash_billboard_material->add_property<float4>("tint")->set_value(float4{1, 1, 1, 1});
  574. ctx->splash_billboard_material->update_tweens();
  575. ctx->splash_billboard = new scene::billboard();
  576. ctx->splash_billboard->set_material(ctx->splash_billboard_material);
  577. ctx->splash_billboard->set_scale({(float)std::get<0>(splash_dimensions) * 0.5f, (float)std::get<1>(splash_dimensions) * 0.5f, 1.0f});
  578. ctx->splash_billboard->set_translation({0.0f, 0.0f, 0.0f});
  579. ctx->splash_billboard->update_tweens();
  580. // Create depth debug billboard
  581. /*
  582. material* depth_debug_material = new material();
  583. depth_debug_material->set_shader_program(ctx->resource_manager->load<gl::shader_program>("ui-element-textured.glsl"));
  584. depth_debug_material->add_property<const gl::texture_2d*>("background")->set_value(shadow_map_depth_texture);
  585. depth_debug_material->add_property<float4>("tint")->set_value(float4{1, 1, 1, 1});
  586. billboard* depth_debug_billboard = new billboard();
  587. depth_debug_billboard->set_material(depth_debug_material);
  588. depth_debug_billboard->set_scale({128, 128, 1});
  589. depth_debug_billboard->set_translation({-960 + 128, 1080 * 0.5f - 128, 0});
  590. depth_debug_billboard->update_tweens();
  591. ui_system->get_scene()->add_object(depth_debug_billboard);
  592. */
  593. ctx->ui_scene->add_object(ctx->ui_camera);
  594. }
  595. // Setup underground scene
  596. {
  597. ctx->underground_scene = new scene::collection();
  598. ctx->underground_ambient_light = new scene::ambient_light();
  599. ctx->underground_ambient_light->set_color({1, 1, 1});
  600. ctx->underground_ambient_light->set_intensity(0.1f);
  601. ctx->underground_ambient_light->update_tweens();
  602. ctx->flashlight_spot_light = new scene::spot_light();
  603. ctx->flashlight_spot_light->set_color({1, 1, 1});
  604. ctx->flashlight_spot_light->set_intensity(1.0f);
  605. ctx->flashlight_spot_light->set_attenuation({1.0f, 0.0f, 0.0f});
  606. ctx->flashlight_spot_light->set_cutoff({math::radians(10.0f), math::radians(19.0f)});
  607. ctx->underground_scene->add_object(ctx->underground_camera);
  608. ctx->underground_scene->add_object(ctx->underground_ambient_light);
  609. //ctx->underground_scene->add_object(ctx->flashlight_spot_light);
  610. }
  611. // Setup surface scene
  612. {
  613. ctx->surface_scene = new scene::collection();
  614. ctx->surface_scene->add_object(ctx->surface_camera);
  615. }
  616. // Clear active scene
  617. ctx->active_scene = nullptr;
  618. logger->pop_task(EXIT_SUCCESS);
  619. }
  620. void setup_animation(game::context* ctx)
  621. {
  622. // Setup timeline system
  623. ctx->timeline = new timeline();
  624. ctx->timeline->set_autoremove(true);
  625. // Setup animator
  626. ctx->animator = new animator();
  627. // Initialize time tween
  628. ctx->time_tween = new tween<double>(0.0);
  629. ctx->time_tween->set_interpolator(math::lerp<double, double>);
  630. // Create fade transition
  631. ctx->fade_transition = new screen_transition();
  632. ctx->fade_transition->get_material()->set_shader_program(ctx->resource_manager->load<gl::shader_program>("fade-transition.glsl"));
  633. ctx->fade_transition_color = ctx->fade_transition->get_material()->add_property<float3>("color");
  634. ctx->fade_transition_color->set_value({0, 0, 0});
  635. ctx->ui_scene->add_object(ctx->fade_transition->get_billboard());
  636. ctx->animator->add_animation(ctx->fade_transition->get_animation());
  637. // Create inner radial transition
  638. ctx->radial_transition_inner = new screen_transition();
  639. ctx->radial_transition_inner->get_material()->set_shader_program(ctx->resource_manager->load<gl::shader_program>("radial-transition-inner.glsl"));
  640. ctx->ui_scene->add_object(ctx->radial_transition_inner->get_billboard());
  641. ctx->animator->add_animation(ctx->radial_transition_inner->get_animation());
  642. // Create outer radial transition
  643. ctx->radial_transition_outer = new screen_transition();
  644. ctx->radial_transition_outer->get_material()->set_shader_program(ctx->resource_manager->load<gl::shader_program>("radial-transition-outer.glsl"));
  645. ctx->ui_scene->add_object(ctx->radial_transition_outer->get_billboard());
  646. ctx->animator->add_animation(ctx->radial_transition_outer->get_animation());
  647. // Set material pass tweens
  648. ctx->common_final_pass->set_time_tween(ctx->time_tween);
  649. ctx->surface_sky_pass->set_time_tween(ctx->time_tween);
  650. ctx->surface_material_pass->set_time_tween(ctx->time_tween);
  651. ctx->underground_material_pass->set_time_tween(ctx->time_tween);
  652. ctx->ui_material_pass->set_time_tween(ctx->time_tween);
  653. }
  654. void setup_entities(game::context* ctx)
  655. {
  656. // Create entity registry
  657. ctx->entity_registry = new entt::registry();
  658. }
  659. void setup_systems(game::context* ctx)
  660. {
  661. event_dispatcher* event_dispatcher = ctx->app->get_event_dispatcher();
  662. const auto& viewport_dimensions = ctx->app->get_viewport_dimensions();
  663. float4 viewport = {0.0f, 0.0f, static_cast<float>(viewport_dimensions[0]), static_cast<float>(viewport_dimensions[1])};
  664. // RGB wavelengths determined by matching wavelengths to XYZ, transforming XYZ to ACEScg, then selecting the max wavelengths for R, G, and B.
  665. const double3 rgb_wavelengths_nm = {602.224, 541.069, 448.143};
  666. // Setup terrain system
  667. ctx->terrain_system = new entity::system::terrain(*ctx->entity_registry);
  668. ctx->terrain_system->set_patch_subdivisions(30);
  669. ctx->terrain_system->set_patch_scene_collection(ctx->surface_scene);
  670. ctx->terrain_system->set_max_error(200.0);
  671. // Setup vegetation system
  672. //ctx->vegetation_system = new entity::system::vegetation(*ctx->entity_registry);
  673. //ctx->vegetation_system->set_terrain_patch_size(TERRAIN_PATCH_SIZE);
  674. //ctx->vegetation_system->set_vegetation_patch_resolution(VEGETATION_PATCH_RESOLUTION);
  675. //ctx->vegetation_system->set_vegetation_density(1.0f);
  676. //ctx->vegetation_system->set_vegetation_model(ctx->resource_manager->load<model>("grass-tuft.mdl"));
  677. //ctx->vegetation_system->set_scene(ctx->surface_scene);
  678. // Setup camera system
  679. ctx->camera_system = new entity::system::camera(*ctx->entity_registry);
  680. ctx->camera_system->set_viewport(viewport);
  681. event_dispatcher->subscribe<window_resized_event>(ctx->camera_system);
  682. // Setup subterrain system
  683. ctx->subterrain_system = new entity::system::subterrain(*ctx->entity_registry, ctx->resource_manager);
  684. ctx->subterrain_system->set_scene(ctx->underground_scene);
  685. // Setup collision system
  686. ctx->collision_system = new entity::system::collision(*ctx->entity_registry);
  687. // Setup samara system
  688. ctx->samara_system = new entity::system::samara(*ctx->entity_registry);
  689. // Setup snapping system
  690. ctx->snapping_system = new entity::system::snapping(*ctx->entity_registry);
  691. // Setup behavior system
  692. ctx->behavior_system = new entity::system::behavior(*ctx->entity_registry);
  693. // Setup locomotion system
  694. ctx->locomotion_system = new entity::system::locomotion(*ctx->entity_registry);
  695. // Setup spatial system
  696. ctx->spatial_system = new entity::system::spatial(*ctx->entity_registry);
  697. // Setup constraint system
  698. ctx->constraint_system = new entity::system::constraint(*ctx->entity_registry);
  699. // Setup tracking system
  700. ctx->tracking_system = new entity::system::tracking(*ctx->entity_registry, event_dispatcher, ctx->resource_manager);
  701. ctx->tracking_system->set_scene(ctx->surface_scene);
  702. // Setup painting system
  703. ctx->painting_system = new entity::system::painting(*ctx->entity_registry, event_dispatcher, ctx->resource_manager);
  704. ctx->painting_system->set_scene(ctx->surface_scene);
  705. // Setup solar system
  706. ctx->orbit_system = new entity::system::orbit(*ctx->entity_registry);
  707. // Setup blackbody system
  708. ctx->blackbody_system = new entity::system::blackbody(*ctx->entity_registry);
  709. ctx->blackbody_system->set_rgb_wavelengths(rgb_wavelengths_nm);
  710. // Setup atmosphere system
  711. ctx->atmosphere_system = new entity::system::atmosphere(*ctx->entity_registry);
  712. ctx->atmosphere_system->set_rgb_wavelengths(rgb_wavelengths_nm);
  713. // Setup astronomy system
  714. ctx->astronomy_system = new entity::system::astronomy(*ctx->entity_registry);
  715. ctx->astronomy_system->set_sky_pass(ctx->surface_sky_pass);
  716. // Setup proteome system
  717. ctx->proteome_system = new entity::system::proteome(*ctx->entity_registry);
  718. // Set time scale
  719. double time_scale = 60.0;
  720. if (ctx->config->contains("time_scale"))
  721. {
  722. time_scale = (*ctx->config)["time_scale"].get<double>();
  723. }
  724. ctx->orbit_system->set_time_scale(time_scale / seconds_per_day);
  725. ctx->astronomy_system->set_time_scale(time_scale / seconds_per_day);
  726. // Setup render system
  727. ctx->render_system = new entity::system::render(*ctx->entity_registry);
  728. ctx->render_system->add_layer(ctx->underground_scene);
  729. ctx->render_system->add_layer(ctx->surface_scene);
  730. ctx->render_system->add_layer(ctx->ui_scene);
  731. ctx->render_system->set_renderer(ctx->renderer);
  732. // Setup UI system
  733. ctx->ui_system = new entity::system::ui(ctx->resource_manager);
  734. ctx->ui_system->set_camera(ctx->ui_camera);
  735. ctx->ui_system->set_scene(ctx->ui_scene);
  736. ctx->ui_system->set_viewport(viewport);
  737. event_dispatcher->subscribe<mouse_moved_event>(ctx->ui_system);
  738. event_dispatcher->subscribe<window_resized_event>(ctx->ui_system);
  739. }
  740. void setup_controls(game::context* ctx)
  741. {
  742. event_dispatcher* event_dispatcher = ctx->app->get_event_dispatcher();
  743. // Setup input event routing
  744. ctx->input_event_router = new input::event_router();
  745. ctx->input_event_router->set_event_dispatcher(event_dispatcher);
  746. // Setup input mapper
  747. ctx->input_mapper = new input::mapper();
  748. ctx->input_mapper->set_event_dispatcher(event_dispatcher);
  749. // Setup input listener
  750. ctx->input_listener = new input::listener();
  751. ctx->input_listener->set_event_dispatcher(event_dispatcher);
  752. /*
  753. // Add menu control mappings
  754. ctx->input_event_router->add_mapping(input::gamepad_button_mapping(ctx->menu_back_control, nullptr, input::gamepad_button::b));
  755. //ctx->input_event_router->add_mapping(input::key_mapping(ctx->control_system->get_tool_menu_control(), nullptr, input::scancode::left_shift));
  756. ctx->input_event_router->add_mapping(input::gamepad_button_mapping(ctx->control_system->get_tool_menu_control(), nullptr, input::gamepad_button::x));
  757. ctx->input_event_router->add_mapping(input::key_mapping(ctx->menu_select_control, nullptr, input::scancode::enter));
  758. ctx->input_event_router->add_mapping(input::key_mapping(ctx->menu_select_control, nullptr, input::scancode::space));
  759. ctx->input_event_router->add_mapping(input::key_mapping(ctx->control_system->get_toggle_view_control(), nullptr, input::scancode::tab));
  760. ctx->control_system->get_toggle_view_control()->set_activated_callback(
  761. [ctx]()
  762. {
  763. if (ctx->active_scene == ctx->surface_scene)
  764. {
  765. ctx->active_scene = ctx->underground_scene;
  766. ctx->radial_transition_inner->transition(0.5f, false, ease<float, double>::in_quad);
  767. auto switch_cameras = [ctx]()
  768. {
  769. ctx->surface_camera->set_active(false);
  770. ctx->underground_camera->set_active(true);
  771. ctx->fade_transition->transition(0.25f, true, ease<float, double>::out_quad);
  772. };
  773. float t = ctx->timeline->get_position();
  774. ctx->timeline->add_cue({t + 0.5f, switch_cameras});
  775. }
  776. else
  777. {
  778. ctx->active_scene = ctx->surface_scene;
  779. ctx->fade_transition->transition(0.25f, false, ease<float, double>::out_quad);
  780. auto switch_cameras = [ctx]()
  781. {
  782. ctx->surface_camera->set_active(true);
  783. ctx->underground_camera->set_active(false);
  784. ctx->radial_transition_inner->transition(0.5f, true, ease<float, double>::out_quad);
  785. };
  786. float t = ctx->timeline->get_position();
  787. ctx->timeline->add_cue({t + 0.25f, switch_cameras});
  788. }
  789. });
  790. float time_scale = ctx->config->get<float>("time_scale");
  791. ctx->control_system->get_fast_forward_control()->set_activated_callback
  792. (
  793. [ctx, time_scale]()
  794. {
  795. ctx->orbit_system->set_time_scale(time_scale * 100.0f / seconds_per_day);
  796. ctx->astronomy_system->set_time_scale(time_scale * 100.0f / seconds_per_day);
  797. }
  798. );
  799. ctx->control_system->get_fast_forward_control()->set_deactivated_callback
  800. (
  801. [ctx, time_scale]()
  802. {
  803. ctx->orbit_system->set_time_scale(time_scale / seconds_per_day);
  804. ctx->astronomy_system->set_time_scale(time_scale / seconds_per_day);
  805. }
  806. );
  807. ctx->control_system->get_rewind_control()->set_activated_callback
  808. (
  809. [ctx, time_scale]()
  810. {
  811. ctx->orbit_system->set_time_scale(time_scale * -100.0f / seconds_per_day);
  812. ctx->astronomy_system->set_time_scale(time_scale * -100.0f / seconds_per_day);
  813. }
  814. );
  815. ctx->control_system->get_rewind_control()->set_deactivated_callback
  816. (
  817. [ctx, time_scale]()
  818. {
  819. ctx->orbit_system->set_time_scale(time_scale / seconds_per_day);
  820. ctx->astronomy_system->set_time_scale(time_scale / seconds_per_day);
  821. }
  822. );
  823. */
  824. }
  825. void setup_cli(game::context* ctx)
  826. {
  827. ctx->cli = new debug::cli();
  828. ctx->cli->register_command("echo", debug::cc::echo);
  829. ctx->cli->register_command("exit", std::function<std::string()>(std::bind(&debug::cc::exit, ctx)));
  830. ctx->cli->register_command("scrot", std::function<std::string()>(std::bind(&debug::cc::scrot, ctx)));
  831. ctx->cli->register_command("cue", std::function<std::string(float, std::string)>(std::bind(&debug::cc::cue, ctx, std::placeholders::_1, std::placeholders::_2)));
  832. //std::string cmd = "cue 20 exit";
  833. //logger->log(cmd);
  834. //logger->log(cli.interpret(cmd));
  835. }
  836. void setup_callbacks(game::context* ctx)
  837. {
  838. // Set update callback
  839. ctx->app->set_update_callback
  840. (
  841. [ctx](double t, double dt)
  842. {
  843. // Update controls
  844. for (const auto& control: ctx->controls)
  845. control.second->update();
  846. // Update processes
  847. std::for_each
  848. (
  849. std::execution::par,
  850. ctx->processes.begin(),
  851. ctx->processes.end(),
  852. [t, dt](const auto& process)
  853. {
  854. process.second(t, dt);
  855. }
  856. );
  857. // Update tweens
  858. ctx->time_tween->update();
  859. ctx->surface_sky_pass->update_tweens();
  860. ctx->surface_scene->update_tweens();
  861. ctx->underground_scene->update_tweens();
  862. ctx->ui_scene->update_tweens();
  863. // Set time tween time
  864. (*ctx->time_tween)[1] = t;
  865. ctx->timeline->advance(dt);
  866. ctx->terrain_system->update(t, dt);
  867. //ctx->vegetation_system->update(t, dt);
  868. ctx->snapping_system->update(t, dt);
  869. ctx->subterrain_system->update(t, dt);
  870. ctx->collision_system->update(t, dt);
  871. ctx->samara_system->update(t, dt);
  872. ctx->behavior_system->update(t, dt);
  873. ctx->locomotion_system->update(t, dt);
  874. ctx->camera_system->update(t, dt);
  875. ctx->orbit_system->update(t, dt);
  876. ctx->blackbody_system->update(t, dt);
  877. ctx->atmosphere_system->update(t, dt);
  878. ctx->astronomy_system->update(t, dt);
  879. ctx->spatial_system->update(t, dt);
  880. ctx->constraint_system->update(t, dt);
  881. ctx->tracking_system->update(t, dt);
  882. ctx->painting_system->update(t, dt);
  883. ctx->proteome_system->update(t, dt);
  884. ctx->ui_system->update(dt);
  885. ctx->render_system->update(t, dt);
  886. ctx->animator->animate(dt);
  887. }
  888. );
  889. // Set render callback
  890. ctx->app->set_render_callback
  891. (
  892. [ctx](double alpha)
  893. {
  894. ctx->render_system->draw(alpha);
  895. }
  896. );
  897. }