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

496 lines
15 KiB

  1. /*
  2. * Copyright (C) 2023 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/world.hpp"
  20. #include <engine/color/color.hpp>
  21. #include <engine/config.hpp>
  22. #include <engine/debug/log.hpp>
  23. #include <engine/entity/archetype.hpp>
  24. #include "game/commands/commands.hpp"
  25. #include "game/components/atmosphere-component.hpp"
  26. #include "game/components/blackbody-component.hpp"
  27. #include "game/components/celestial-body-component.hpp"
  28. #include "game/components/observer-component.hpp"
  29. #include "game/components/orbit-component.hpp"
  30. #include "game/components/terrain-component.hpp"
  31. #include "game/components/transform-component.hpp"
  32. #include "game/systems/astronomy-system.hpp"
  33. #include "game/systems/atmosphere-system.hpp"
  34. #include "game/systems/orbit-system.hpp"
  35. #include "game/systems/terrain-system.hpp"
  36. #include <engine/geom/solid-angle.hpp>
  37. #include <engine/gl/drawing-mode.hpp>
  38. #include <engine/gl/texture-filter.hpp>
  39. #include <engine/gl/texture-wrapping.hpp>
  40. #include <engine/gl/vertex-array.hpp>
  41. #include <engine/gl/vertex-attribute.hpp>
  42. #include <engine/gl/vertex-buffer.hpp>
  43. #include <engine/i18n/string-table.hpp>
  44. #include <engine/math/hash/hash.hpp>
  45. #include <engine/math/noise/noise.hpp>
  46. #include <engine/math/angles.hpp>
  47. #include <engine/physics/light/photometry.hpp>
  48. #include <engine/physics/light/vmag.hpp>
  49. #include <engine/physics/orbit/ephemeris.hpp>
  50. #include <engine/physics/orbit/orbit.hpp>
  51. #include <engine/physics/time/constants.hpp>
  52. #include <engine/physics/time/gregorian.hpp>
  53. #include <engine/physics/time/utc.hpp>
  54. #include <engine/render/material-flags.hpp>
  55. #include <engine/render/material.hpp>
  56. #include <engine/render/model.hpp>
  57. #include <engine/render/passes/shadow-map-pass.hpp>
  58. #include <engine/render/passes/sky-pass.hpp>
  59. #include <engine/render/vertex-attribute.hpp>
  60. #include <engine/utility/image.hpp>
  61. #include <engine/utility/json.hpp>
  62. #include <engine/resources/resource-manager.hpp>
  63. #include <engine/scene/directional-light.hpp>
  64. #include <engine/scene/text.hpp>
  65. #include <algorithm>
  66. #include <execution>
  67. #include <fstream>
  68. #include <stb/stb_image_write.h>
  69. #include <engine/animation/screen-transition.hpp>
  70. #include <engine/animation/ease.hpp>
  71. namespace world {
  72. /// Loads an ephemeris.
  73. static void load_ephemeris(::game& ctx);
  74. /// Creates the fixed stars.
  75. static void create_stars(::game& ctx);
  76. /// Creates the Sun.
  77. static void create_sun(::game& ctx);
  78. /// Creates the Earth-Moon system.
  79. static void create_earth_moon_system(::game& ctx);
  80. /// Creates the Earth.
  81. static void create_earth(::game& ctx);
  82. /// Creates the Moon.
  83. static void create_moon(::game& ctx);
  84. void cosmogenesis(::game& ctx)
  85. {
  86. debug::log::trace("Generating cosmos...");
  87. load_ephemeris(ctx);
  88. create_stars(ctx);
  89. create_sun(ctx);
  90. create_earth_moon_system(ctx);
  91. debug::log::trace("Generated cosmos");
  92. }
  93. void create_observer(::game& ctx)
  94. {
  95. debug::log::trace("Creating observer...");
  96. {
  97. // Create observer entity
  98. entity::id observer_eid = ctx.entity_registry->create();
  99. ctx.entities["observer"] = observer_eid;
  100. // Construct observer component
  101. ::observer_component observer;
  102. // Set observer reference body
  103. if (auto it = ctx.entities.find("earth"); it != ctx.entities.end())
  104. observer.reference_body_eid = it->second;
  105. else
  106. observer.reference_body_eid = entt::null;
  107. // Set observer location
  108. observer.elevation = 0.0;
  109. observer.latitude = 0.0;
  110. observer.longitude = 0.0;
  111. // Assign observer component to observer entity
  112. ctx.entity_registry->emplace<::observer_component>(observer_eid, observer);
  113. // Set atmosphere system active atmosphere
  114. ctx.atmosphere_system->set_active_atmosphere(observer.reference_body_eid);
  115. // Set astronomy system observer
  116. ctx.astronomy_system->set_observer(observer_eid);
  117. }
  118. debug::log::trace("Created observer");
  119. }
  120. void set_location(::game& ctx, double elevation, double latitude, double longitude)
  121. {
  122. if (auto it = ctx.entities.find("observer"); it != ctx.entities.end())
  123. {
  124. entity::id observer_eid = it->second;
  125. if (ctx.entity_registry->valid(observer_eid) && ctx.entity_registry->all_of<::observer_component>(observer_eid))
  126. {
  127. // Update observer location
  128. ctx.entity_registry->patch<::observer_component>
  129. (
  130. observer_eid,
  131. [&](auto& component)
  132. {
  133. component.elevation = elevation;
  134. component.latitude = latitude;
  135. component.longitude = longitude;
  136. }
  137. );
  138. }
  139. }
  140. }
  141. void set_time(::game& ctx, double t)
  142. {
  143. try
  144. {
  145. ctx.astronomy_system->set_time(t);
  146. ctx.orbit_system->set_time(t);
  147. // debug::log::info("Set time to UT1 {}", t);
  148. }
  149. catch (const std::exception& e)
  150. {
  151. debug::log::error("Failed to set time to UT1 {}: {}", t, e.what());
  152. }
  153. }
  154. void set_time(::game& ctx, int year, int month, int day, int hour, int minute, double second)
  155. {
  156. double longitude = 0.0;
  157. // Get longitude of observer
  158. if (auto it = ctx.entities.find("observer"); it != ctx.entities.end())
  159. {
  160. entity::id observer_eid = it->second;
  161. if (ctx.entity_registry->valid(observer_eid))
  162. {
  163. const auto observer = ctx.entity_registry->try_get<::observer_component>(observer_eid);
  164. if (observer)
  165. longitude = observer->longitude;
  166. }
  167. }
  168. // Calculate UTC offset at longitude
  169. const double utc_offset = physics::time::utc::offset<double>(longitude);
  170. // Convert time from Gregorian to UT1
  171. const double t = physics::time::gregorian::to_ut1<double>(year, month, day, hour, minute, second, utc_offset);
  172. set_time(ctx, t);
  173. }
  174. void set_time_scale(::game& ctx, double scale)
  175. {
  176. // Convert time scale from seconds to days
  177. const double astronomical_scale = scale / physics::time::seconds_per_day<double>;
  178. ctx.orbit_system->set_time_scale(astronomical_scale);
  179. ctx.astronomy_system->set_time_scale(astronomical_scale);
  180. }
  181. void load_ephemeris(::game& ctx)
  182. {
  183. ctx.orbit_system->set_ephemeris(ctx.resource_manager->load<physics::orbit::ephemeris<double>>("de421.eph"));
  184. }
  185. void create_stars(::game& ctx)
  186. {
  187. debug::log::trace("Generating fixed stars...");
  188. // Load star catalog
  189. auto star_catalog = ctx.resource_manager->load<i18n::string_table>("hipparcos-7.tsv");
  190. // Allocate star catalog vertex data
  191. std::size_t star_count = 0;
  192. if (star_catalog->rows.size() > 0)
  193. star_count = star_catalog->rows.size() - 1;
  194. std::size_t star_vertex_size = 7;
  195. std::size_t star_vertex_stride = star_vertex_size * sizeof(float);
  196. std::vector<float> star_vertex_data(star_count * star_vertex_size);
  197. float* star_vertex = star_vertex_data.data();
  198. // Init starlight illuminance
  199. math::dvec3 starlight_illuminance = {0, 0, 0};
  200. // Build star catalog vertex data
  201. for (std::size_t i = 1; i < star_catalog->rows.size(); ++i)
  202. {
  203. const auto& row = star_catalog->rows[i];
  204. // Parse star catalog item
  205. float ra = 0.0;
  206. float dec = 0.0;
  207. float vmag = 0.0;
  208. float bv = 0.0;
  209. try
  210. {
  211. ra = std::stof(row[1]);
  212. dec = std::stof(row[2]);
  213. vmag = std::stof(row[3]);
  214. bv = std::stof(row[4]);
  215. }
  216. catch (const std::exception&)
  217. {
  218. debug::log::warning("Invalid star catalog item on row {}", i);
  219. continue;
  220. }
  221. // Convert right ascension and declination from degrees to radians
  222. ra = math::wrap_radians(math::radians(ra));
  223. dec = math::wrap_radians(math::radians(dec));
  224. // Convert ICRF coordinates from spherical to Cartesian
  225. math::fvec3 position = physics::orbit::frame::bci::cartesian(math::fvec3{1.0f, dec, ra});
  226. // Convert color index to color temperature
  227. float cct = color::index::bv_to_cct(bv);
  228. // Calculate XYZ color from color temperature
  229. math::fvec3 color_xyz = color::cct::to_xyz(cct);
  230. // Transform XYZ color to ACEScg colorspace
  231. math::fvec3 color_acescg = color::aces::ap1<float>.from_xyz * color_xyz;
  232. // Convert apparent magnitude to brightness factor relative to a 0th magnitude star
  233. float brightness = physics::light::vmag::to_brightness(vmag);
  234. // Build vertex
  235. *(star_vertex++) = position.x();
  236. *(star_vertex++) = position.y();
  237. *(star_vertex++) = position.z();
  238. *(star_vertex++) = color_acescg.x();
  239. *(star_vertex++) = color_acescg.y();
  240. *(star_vertex++) = color_acescg.z();
  241. *(star_vertex++) = brightness;
  242. // Calculate spectral illuminance
  243. math::dvec3 illuminance = math::dvec3(color_acescg * physics::light::vmag::to_illuminance(vmag));
  244. // Add spectral illuminance to total starlight illuminance
  245. starlight_illuminance += illuminance;
  246. }
  247. // Allocate stars model
  248. std::shared_ptr<render::model> stars_model = std::make_shared<render::model>();
  249. // Get model VBO and VAO
  250. auto& vbo = stars_model->get_vertex_buffer();
  251. auto& vao = stars_model->get_vertex_array();
  252. // Resize model VBO and upload vertex data
  253. vbo->resize(star_vertex_data.size(), std::as_bytes(std::span{star_vertex_data}));
  254. std::size_t attribute_offset = 0;
  255. // Define position vertex attribute
  256. gl::vertex_attribute position_attribute;
  257. position_attribute.buffer = vbo.get();
  258. position_attribute.offset = attribute_offset;
  259. position_attribute.stride = star_vertex_stride;
  260. position_attribute.type = gl::vertex_attribute_type::float_32;
  261. position_attribute.components = 3;
  262. attribute_offset += position_attribute.components * sizeof(float);
  263. // Define color vertex attribute
  264. gl::vertex_attribute color_attribute;
  265. color_attribute.buffer = vbo.get();
  266. color_attribute.offset = attribute_offset;
  267. color_attribute.stride = star_vertex_stride;
  268. color_attribute.type = gl::vertex_attribute_type::float_32;
  269. color_attribute.components = 4;
  270. //attribute_offset += color_attribute.components * sizeof(float);
  271. // Bind vertex attributes to VAO
  272. vao->bind(render::vertex_attribute::position, position_attribute);
  273. vao->bind(render::vertex_attribute::color, color_attribute);
  274. // Load star material
  275. std::shared_ptr<render::material> star_material = ctx.resource_manager->load<render::material>("fixed-star.mtl");
  276. // Create model group
  277. stars_model->get_groups().resize(1);
  278. render::model_group& stars_model_group = stars_model->get_groups().back();
  279. stars_model_group.id = "stars";
  280. stars_model_group.material = star_material;
  281. stars_model_group.drawing_mode = gl::drawing_mode::points;
  282. stars_model_group.start_index = 0;
  283. stars_model_group.index_count = static_cast<std::uint32_t>(star_count);
  284. // Pass stars model to sky pass
  285. ctx.sky_pass->set_stars_model(stars_model);
  286. // Pass starlight illuminance to astronomy system
  287. ctx.astronomy_system->set_starlight_illuminance(starlight_illuminance);
  288. debug::log::trace("Generated fixed stars");
  289. }
  290. void create_sun(::game& ctx)
  291. {
  292. debug::log::trace("Generating Sun...");
  293. {
  294. // Create sun entity
  295. auto sun_archetype = ctx.resource_manager->load<entity::archetype>("sun.ent");
  296. entity::id sun_eid = sun_archetype->create(*ctx.entity_registry);
  297. ctx.entities["sun"] = sun_eid;
  298. // Create sun directional light scene object
  299. ctx.sun_light = std::make_unique<scene::directional_light>();
  300. ctx.sun_light->set_shadow_caster(true);
  301. ctx.sun_light->set_shadow_framebuffer(ctx.shadow_map_framebuffer);
  302. ctx.sun_light->set_shadow_bias(0.0025f);
  303. ctx.sun_light->set_shadow_cascade_count(4);
  304. ctx.sun_light->set_shadow_cascade_coverage(0.05f);
  305. ctx.sun_light->set_shadow_cascade_distribution(0.8f);
  306. // Add sun light scene objects to surface scene
  307. ctx.surface_scene->add_object(*ctx.sun_light);
  308. // Pass direct sun light scene object to shadow map pass and astronomy system
  309. ctx.astronomy_system->set_sun_light(ctx.sun_light.get());
  310. }
  311. debug::log::trace("Generated Sun");
  312. }
  313. void create_earth_moon_system(::game& ctx)
  314. {
  315. debug::log::trace("Generating Earth-Moon system...");
  316. {
  317. // Create Earth-Moon barycenter entity
  318. auto em_bary_archetype = ctx.resource_manager->load<entity::archetype>("em-bary.ent");
  319. entity::id em_bary_eid = em_bary_archetype->create(*ctx.entity_registry);
  320. ctx.entities["em_bary"] = em_bary_eid;
  321. // Create Earth
  322. create_earth(ctx);
  323. // Create Moon
  324. create_moon(ctx);
  325. }
  326. debug::log::trace("Generated Earth-Moon system");
  327. }
  328. void create_earth(::game& ctx)
  329. {
  330. debug::log::trace("Generating Earth...");
  331. {
  332. // Create earth entity
  333. auto earth_archetype = ctx.resource_manager->load<entity::archetype>("earth.ent");
  334. entity::id earth_eid = earth_archetype->create(*ctx.entity_registry);
  335. ctx.entities["earth"] = earth_eid;
  336. // Assign orbital parent
  337. ctx.entity_registry->get<::orbit_component>(earth_eid).parent = ctx.entities["em_bary"];
  338. }
  339. debug::log::trace("Generated Earth");
  340. }
  341. void create_moon(::game& ctx)
  342. {
  343. debug::log::trace("Generating Moon...");
  344. {
  345. // Create lunar entity
  346. auto moon_archetype = ctx.resource_manager->load<entity::archetype>("moon.ent");
  347. entity::id moon_eid = moon_archetype->create(*ctx.entity_registry);
  348. ctx.entities["moon"] = moon_eid;
  349. // Assign orbital parent
  350. ctx.entity_registry->get<::orbit_component>(moon_eid).parent = ctx.entities["em_bary"];
  351. // Pass moon model to sky pass
  352. ctx.sky_pass->set_moon_model(ctx.resource_manager->load<render::model>("moon.mdl"));
  353. // Create moon directional light scene object
  354. ctx.moon_light = std::make_unique<scene::directional_light>();
  355. // Add moon light scene objects to surface scene
  356. ctx.surface_scene->add_object(*ctx.moon_light);
  357. // Pass moon light scene object to astronomy system
  358. ctx.astronomy_system->set_moon_light(ctx.moon_light.get());
  359. }
  360. debug::log::trace("Generated Moon");
  361. }
  362. void enter_ecoregion(::game& ctx, const ecoregion& ecoregion)
  363. {
  364. debug::log::trace("Entering ecoregion {}...", ecoregion.name);
  365. {
  366. // Set active ecoregion
  367. //ctx.active_ecoregion = &ecoregion;
  368. // Set location
  369. ::world::set_location(ctx, ecoregion.elevation, ecoregion.latitude, ecoregion.longitude);
  370. // Setup sky
  371. ctx.sky_pass->set_sky_model(ctx.resource_manager->load<render::model>("celestial-hemisphere.mdl"));
  372. ctx.sky_pass->set_ground_albedo(ecoregion.terrain_albedo);
  373. // Setup terrain
  374. // ctx.terrain_system->set_patch_material(ecoregion.terrain_material);
  375. // ctx.terrain_system->set_elevation_function
  376. // (
  377. // [](float x, float z) -> float
  378. // {
  379. // const math::fvec2 position = math::fvec2{x, z};
  380. // const std::size_t octaves = 3;
  381. // const float lacunarity = 1.5f;
  382. // const float gain = 0.5f;
  383. // const float fbm = math::noise::fbm
  384. // (
  385. // position * 0.005f,
  386. // octaves,
  387. // lacunarity,
  388. // gain
  389. // );
  390. // float y = fbm * 4.0f;
  391. // return y;
  392. // }
  393. // );
  394. }
  395. debug::log::trace("Entered ecoregion {}", ecoregion.name);
  396. }
  397. void switch_scene(::game& ctx)
  398. {
  399. ctx.fade_transition_color->set({0, 0, 0});
  400. ctx.fade_transition->transition(1.0f, false, ease<float>::out_cubic, false, [](){});
  401. }
  402. } // namespace world