sky.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. /*
  2. * Copyright 2017 Stanislav Pidhorskyi. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. /*
  6. * This example demonstrates:
  7. * - Usage of Perez sky model [1] to render a dynamic sky.
  8. * - Rendering a mesh with a lightmap, shading of which is driven by the same parameters as the sky.
  9. *
  10. * Typically, the sky is rendered using cubemaps or other environment maps.
  11. * This approach can provide a high-quality sky, but the downside is that the
  12. * image is static. To achieve daytime changes in sky appearance, there is a need
  13. * in a dynamic model.
  14. *
  15. * Perez "An All-Weather Model for Sky Luminance Distribution" is a simple,
  16. * but good enough model which is, in essence, a function that
  17. * interpolates a sky color. As input, it requires several turbidity
  18. * coefficients, a color at zenith and direction to the sun.
  19. * Turbidity coefficients are taken from [2], which are computed using more
  20. * complex physically based models. Color at zenith depends on daytime and can
  21. * vary depending on many factors.
  22. *
  23. * In the code below, there are two tables that contain sky and sun luminance
  24. * which were computed using code from [3]. Luminance in those tables
  25. * represents actual scale of light energy that comes from sun compared to
  26. * the sky.
  27. *
  28. * The sky is driven by luminance of the sky, while the material of the
  29. * landscape is driven by both, the luminance of the sky and the sun. The
  30. * lightening model is very simple and consists of two parts: directional
  31. * light and hemisphere light. The first is used for the sun while the second
  32. * is used for the sky. Additionally, the second part is modulated by a
  33. * lightmap to achieve ambient occlusion effect.
  34. *
  35. * References
  36. * ==========
  37. *
  38. * [1] R. Perez, R. Seals, and J. Michalsky."An All-Weather Model for Sky Luminance Distribution".
  39. * Solar Energy, Volume 50, Number 3 (March 1993), pp. 235-245.
  40. *
  41. * [2] A. J. Preetham, Peter Shirley, and Brian Smits. "A Practical Analytic Model for Daylight",
  42. * Proceedings of the 26th Annual Conference on Computer Graphics and Interactive Techniques,
  43. * 1999, pp. 91-100.
  44. * https://www.cs.utah.edu/~shirley/papers/sunsky/sunsky.pdf
  45. *
  46. * [3] E. Lengyel, Game Engine Gems, Volume One. Jones & Bartlett Learning, 2010. pp. 219 - 234
  47. *
  48. */
  49. #include "common.h"
  50. #include "bgfx_utils.h"
  51. #include "imgui/imgui.h"
  52. #include "camera.h"
  53. #include "bounds.h"
  54. #include <map>
  55. namespace
  56. {
  57. // Represents color. Color-space depends on context.
  58. // In the code below, used to represent color in XYZ, and RGB color-space
  59. typedef bx::Vec3 Color;
  60. // HDTV rec. 709 matrix.
  61. static constexpr float M_XYZ2RGB[] =
  62. {
  63. 3.240479f, -0.969256f, 0.055648f,
  64. -1.53715f, 1.875991f, -0.204043f,
  65. -0.49853f, 0.041556f, 1.057311f,
  66. };
  67. // Converts color repesentation from CIE XYZ to RGB color-space.
  68. Color xyzToRgb(const Color& xyz)
  69. {
  70. Color rgb(bx::init::None);
  71. rgb.x = M_XYZ2RGB[0] * xyz.x + M_XYZ2RGB[3] * xyz.y + M_XYZ2RGB[6] * xyz.z;
  72. rgb.y = M_XYZ2RGB[1] * xyz.x + M_XYZ2RGB[4] * xyz.y + M_XYZ2RGB[7] * xyz.z;
  73. rgb.z = M_XYZ2RGB[2] * xyz.x + M_XYZ2RGB[5] * xyz.y + M_XYZ2RGB[8] * xyz.z;
  74. return rgb;
  75. };
  76. // Precomputed luminance of sunlight in XYZ colorspace.
  77. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model.
  78. // This table is used for piecewise linear interpolation. Transitions from and to 0.0 at sunset and sunrise are highly inaccurate
  79. static std::map<float, Color> sunLuminanceXYZTable =
  80. {
  81. { 5.0f, { 0.000000f, 0.000000f, 0.000000f } },
  82. { 7.0f, { 12.703322f, 12.989393f, 9.100411f } },
  83. { 8.0f, { 13.202644f, 13.597814f, 11.524929f } },
  84. { 9.0f, { 13.192974f, 13.597458f, 12.264488f } },
  85. { 10.0f, { 13.132943f, 13.535914f, 12.560032f } },
  86. { 11.0f, { 13.088722f, 13.489535f, 12.692996f } },
  87. { 12.0f, { 13.067827f, 13.467483f, 12.745179f } },
  88. { 13.0f, { 13.069653f, 13.469413f, 12.740822f } },
  89. { 14.0f, { 13.094319f, 13.495428f, 12.678066f } },
  90. { 15.0f, { 13.142133f, 13.545483f, 12.526785f } },
  91. { 16.0f, { 13.201734f, 13.606017f, 12.188001f } },
  92. { 17.0f, { 13.182774f, 13.572725f, 11.311157f } },
  93. { 18.0f, { 12.448635f, 12.672520f, 8.267771f } },
  94. { 20.0f, { 0.000000f, 0.000000f, 0.000000f } },
  95. };
  96. // Precomputed luminance of sky in the zenith point in XYZ colorspace.
  97. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model.
  98. // This table is used for piecewise linear interpolation. Day/night transitions are highly inaccurate.
  99. // The scale of luminance change in Day/night transitions is not preserved.
  100. // Luminance at night was increased to eliminate need the of HDR render.
  101. static std::map<float, Color> skyLuminanceXYZTable =
  102. {
  103. { 0.0f, { 0.308f, 0.308f, 0.411f } },
  104. { 1.0f, { 0.308f, 0.308f, 0.410f } },
  105. { 2.0f, { 0.301f, 0.301f, 0.402f } },
  106. { 3.0f, { 0.287f, 0.287f, 0.382f } },
  107. { 4.0f, { 0.258f, 0.258f, 0.344f } },
  108. { 5.0f, { 0.258f, 0.258f, 0.344f } },
  109. { 7.0f, { 0.962851f, 1.000000f, 1.747835f } },
  110. { 8.0f, { 0.967787f, 1.000000f, 1.776762f } },
  111. { 9.0f, { 0.970173f, 1.000000f, 1.788413f } },
  112. { 10.0f, { 0.971431f, 1.000000f, 1.794102f } },
  113. { 11.0f, { 0.972099f, 1.000000f, 1.797096f } },
  114. { 12.0f, { 0.972385f, 1.000000f, 1.798389f } },
  115. { 13.0f, { 0.972361f, 1.000000f, 1.798278f } },
  116. { 14.0f, { 0.972020f, 1.000000f, 1.796740f } },
  117. { 15.0f, { 0.971275f, 1.000000f, 1.793407f } },
  118. { 16.0f, { 0.969885f, 1.000000f, 1.787078f } },
  119. { 17.0f, { 0.967216f, 1.000000f, 1.773758f } },
  120. { 18.0f, { 0.961668f, 1.000000f, 1.739891f } },
  121. { 20.0f, { 0.264f, 0.264f, 0.352f } },
  122. { 21.0f, { 0.264f, 0.264f, 0.352f } },
  123. { 22.0f, { 0.290f, 0.290f, 0.386f } },
  124. { 23.0f, { 0.303f, 0.303f, 0.404f } },
  125. };
  126. // Turbidity tables. Taken from:
  127. // A. J. Preetham, P. Shirley, and B. Smits. A Practical Analytic Model for Daylight. SIGGRAPH '99
  128. // Coefficients correspond to xyY colorspace.
  129. static constexpr Color ABCDE[] =
  130. {
  131. { -0.2592f, -0.2608f, -1.4630f },
  132. { 0.0008f, 0.0092f, 0.4275f },
  133. { 0.2125f, 0.2102f, 5.3251f },
  134. { -0.8989f, -1.6537f, -2.5771f },
  135. { 0.0452f, 0.0529f, 0.3703f },
  136. };
  137. static constexpr Color ABCDE_t[] =
  138. {
  139. { -0.0193f, -0.0167f, 0.1787f },
  140. { -0.0665f, -0.0950f, -0.3554f },
  141. { -0.0004f, -0.0079f, -0.0227f },
  142. { -0.0641f, -0.0441f, 0.1206f },
  143. { -0.0033f, -0.0109f, -0.0670f },
  144. };
  145. // Performs piecewise linear interpolation of a Color parameter.
  146. class DynamicValueController
  147. {
  148. typedef Color ValueType;
  149. typedef std::map<float, ValueType> KeyMap;
  150. public:
  151. DynamicValueController()
  152. {
  153. }
  154. ~DynamicValueController()
  155. {
  156. }
  157. void SetMap(const KeyMap& keymap)
  158. {
  159. m_keyMap = keymap;
  160. }
  161. ValueType GetValue(float time) const
  162. {
  163. typename KeyMap::const_iterator itUpper = m_keyMap.upper_bound(time + 1e-6f);
  164. typename KeyMap::const_iterator itLower = itUpper;
  165. --itLower;
  166. if (itLower == m_keyMap.end())
  167. {
  168. return itUpper->second;
  169. }
  170. if (itUpper == m_keyMap.end())
  171. {
  172. return itLower->second;
  173. }
  174. float lowerTime = itLower->first;
  175. const ValueType& lowerVal = itLower->second;
  176. float upperTime = itUpper->first;
  177. const ValueType& upperVal = itUpper->second;
  178. if (lowerTime == upperTime)
  179. {
  180. return lowerVal;
  181. }
  182. return interpolate(lowerTime, lowerVal, upperTime, upperVal, time);
  183. };
  184. void Clear()
  185. {
  186. m_keyMap.clear();
  187. };
  188. private:
  189. ValueType interpolate(float lowerTime, const ValueType& lowerVal, float upperTime, const ValueType& upperVal, float time) const
  190. {
  191. const float tt = (time - lowerTime) / (upperTime - lowerTime);
  192. const ValueType result = bx::lerp(lowerVal, upperVal, tt);
  193. return result;
  194. };
  195. KeyMap m_keyMap;
  196. };
  197. // Controls sun position according to time, month, and observer's latitude.
  198. // Sun position computation based on Earth's orbital elements: https://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html
  199. class SunController
  200. {
  201. public:
  202. enum Month : int
  203. {
  204. January = 0,
  205. February,
  206. March,
  207. April,
  208. May,
  209. June,
  210. July,
  211. August,
  212. September,
  213. October,
  214. November,
  215. December
  216. };
  217. SunController()
  218. : m_northDir(1.0f, 0.0f, 0.0f)
  219. , m_sunDir(0.0f, -1.0f, 0.0f)
  220. , m_upDir(0.0f, 1.0f, 0.0f)
  221. , m_latitude(50.0f)
  222. , m_month(June)
  223. , m_eclipticObliquity(bx::toRad(23.4f) )
  224. , m_delta(0.0f)
  225. {
  226. }
  227. void Update(float _time)
  228. {
  229. CalculateSunOrbit();
  230. UpdateSunPosition(_time - 12.0f);
  231. }
  232. bx::Vec3 m_northDir;
  233. bx::Vec3 m_sunDir;
  234. bx::Vec3 m_upDir;
  235. float m_latitude;
  236. Month m_month;
  237. private:
  238. void CalculateSunOrbit()
  239. {
  240. float day = 30.0f * m_month + 15.0f;
  241. float lambda = 280.46f + 0.9856474f * day;
  242. lambda = bx::toRad(lambda);
  243. m_delta = bx::asin(bx::sin(m_eclipticObliquity) * bx::sin(lambda) );
  244. }
  245. void UpdateSunPosition(float _hour)
  246. {
  247. const float latitude = bx::toRad(m_latitude);
  248. const float hh = _hour * bx::kPi / 12.0f;
  249. const float azimuth = bx::atan2(
  250. bx::sin(hh)
  251. , bx::cos(hh) * bx::sin(latitude) - bx::tan(m_delta) * bx::cos(latitude)
  252. );
  253. const float altitude = bx::asin(
  254. bx::sin(latitude) * bx::sin(m_delta) + bx::cos(latitude) * bx::cos(m_delta) * bx::cos(hh)
  255. );
  256. const bx::Quaternion rot0 = bx::rotateAxis(m_upDir, -azimuth);
  257. const bx::Vec3 dir = bx::mul(m_northDir, rot0);
  258. const bx::Vec3 uxd = bx::cross(m_upDir, dir);
  259. const bx::Quaternion rot1 = bx::rotateAxis(uxd, altitude);
  260. m_sunDir = bx::mul(dir, rot1);
  261. }
  262. float m_eclipticObliquity;
  263. float m_delta;
  264. };
  265. struct ScreenPosVertex
  266. {
  267. float m_x;
  268. float m_y;
  269. static void init()
  270. {
  271. ms_layout
  272. .begin()
  273. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  274. .end();
  275. }
  276. static bgfx::VertexLayout ms_layout;
  277. };
  278. bgfx::VertexLayout ScreenPosVertex::ms_layout;
  279. // Renders a screen-space grid of triangles.
  280. // Because of performance reasons, and because sky color is smooth, sky color is computed in vertex shader.
  281. // 32x32 is a reasonable size for the grid to have smooth enough colors.
  282. struct ProceduralSky
  283. {
  284. void init(int verticalCount, int horizontalCount)
  285. {
  286. // Create vertex stream declaration.
  287. ScreenPosVertex::init();
  288. m_skyProgram = loadProgram("vs_sky", "fs_sky");
  289. m_skyProgram_colorBandingFix = loadProgram("vs_sky", "fs_sky_color_banding_fix");
  290. m_preventBanding = true;
  291. bx::AllocatorI* allocator = entry::getAllocator();
  292. ScreenPosVertex* vertices = (ScreenPosVertex*)BX_ALLOC(allocator
  293. , verticalCount * horizontalCount * sizeof(ScreenPosVertex)
  294. );
  295. for (int i = 0; i < verticalCount; i++)
  296. {
  297. for (int j = 0; j < horizontalCount; j++)
  298. {
  299. ScreenPosVertex& v = vertices[i * verticalCount + j];
  300. v.m_x = float(j) / (horizontalCount - 1) * 2.0f - 1.0f;
  301. v.m_y = float(i) / (verticalCount - 1) * 2.0f - 1.0f;
  302. }
  303. }
  304. uint16_t* indices = (uint16_t*)BX_ALLOC(allocator
  305. , (verticalCount - 1) * (horizontalCount - 1) * 6 * sizeof(uint16_t)
  306. );
  307. int k = 0;
  308. for (int i = 0; i < verticalCount - 1; i++)
  309. {
  310. for (int j = 0; j < horizontalCount - 1; j++)
  311. {
  312. indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 0));
  313. indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0));
  314. indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1));
  315. indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0));
  316. indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 1));
  317. indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1));
  318. }
  319. }
  320. m_vbh = bgfx::createVertexBuffer(bgfx::copy(vertices, sizeof(ScreenPosVertex) * verticalCount * horizontalCount), ScreenPosVertex::ms_layout);
  321. m_ibh = bgfx::createIndexBuffer(bgfx::copy(indices, sizeof(uint16_t) * k));
  322. BX_FREE(allocator, indices);
  323. BX_FREE(allocator, vertices);
  324. }
  325. void shutdown()
  326. {
  327. bgfx::destroy(m_ibh);
  328. bgfx::destroy(m_vbh);
  329. bgfx::destroy(m_skyProgram);
  330. bgfx::destroy(m_skyProgram_colorBandingFix);
  331. }
  332. void draw()
  333. {
  334. bgfx::setState(BGFX_STATE_WRITE_RGB | BGFX_STATE_DEPTH_TEST_EQUAL);
  335. bgfx::setIndexBuffer(m_ibh);
  336. bgfx::setVertexBuffer(0, m_vbh);
  337. bgfx::submit(0, m_preventBanding ? m_skyProgram_colorBandingFix : m_skyProgram);
  338. }
  339. bgfx::VertexBufferHandle m_vbh;
  340. bgfx::IndexBufferHandle m_ibh;
  341. bgfx::ProgramHandle m_skyProgram;
  342. bgfx::ProgramHandle m_skyProgram_colorBandingFix;
  343. bool m_preventBanding;
  344. };
  345. class ExampleProceduralSky : public entry::AppI
  346. {
  347. public:
  348. ExampleProceduralSky(const char* _name, const char* _description, const char* _url)
  349. : entry::AppI(_name, _description, _url)
  350. {
  351. }
  352. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  353. {
  354. Args args(_argc, _argv);
  355. m_width = _width;
  356. m_height = _height;
  357. m_debug = BGFX_DEBUG_NONE;
  358. m_reset = BGFX_RESET_VSYNC;
  359. bgfx::Init init;
  360. init.type = args.m_type;
  361. init.vendorId = args.m_pciId;
  362. init.resolution.width = m_width;
  363. init.resolution.height = m_height;
  364. init.resolution.reset = m_reset;
  365. bgfx::init(init);
  366. // Enable m_debug text.
  367. bgfx::setDebug(m_debug);
  368. // Set view 0 clear state.
  369. bgfx::setViewClear(0
  370. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  371. , 0x000000ff
  372. , 1.0f
  373. , 0
  374. );
  375. m_sunLuminanceXYZ.SetMap(sunLuminanceXYZTable);
  376. m_skyLuminanceXYZ.SetMap(skyLuminanceXYZTable);
  377. m_mesh = meshLoad("meshes/test_scene.bin");
  378. m_lightmapTexture = loadTexture("textures/lightmap.ktx");
  379. // Imgui.
  380. imguiCreate();
  381. m_timeOffset = bx::getHPCounter();
  382. m_time = 0.0f;
  383. m_timeScale = 1.0f;
  384. s_texLightmap = bgfx::createUniform("s_texLightmap", bgfx::UniformType::Sampler);
  385. u_sunLuminance = bgfx::createUniform("u_sunLuminance", bgfx::UniformType::Vec4);
  386. u_skyLuminanceXYZ = bgfx::createUniform("u_skyLuminanceXYZ", bgfx::UniformType::Vec4);
  387. u_skyLuminance = bgfx::createUniform("u_skyLuminance", bgfx::UniformType::Vec4);
  388. u_sunDirection = bgfx::createUniform("u_sunDirection", bgfx::UniformType::Vec4);
  389. u_parameters = bgfx::createUniform("u_parameters", bgfx::UniformType::Vec4);
  390. u_perezCoeff = bgfx::createUniform("u_perezCoeff", bgfx::UniformType::Vec4, 5);
  391. m_landscapeProgram = loadProgram("vs_sky_landscape", "fs_sky_landscape");
  392. m_sky.init(32, 32);
  393. m_sun.Update(0);
  394. cameraCreate();
  395. cameraSetPosition({ 5.0f, 3.0, 0.0f });
  396. cameraSetVerticalAngle(bx::kPi / 8.0f);
  397. cameraSetHorizontalAngle(-bx::kPi / 3.0f);
  398. m_turbidity = 2.15f;
  399. }
  400. virtual int shutdown() override
  401. {
  402. // Cleanup.
  403. cameraDestroy();
  404. imguiDestroy();
  405. meshUnload(m_mesh);
  406. m_sky.shutdown();
  407. bgfx::destroy(s_texLightmap);
  408. bgfx::destroy(u_sunLuminance);
  409. bgfx::destroy(u_skyLuminanceXYZ);
  410. bgfx::destroy(u_skyLuminance);
  411. bgfx::destroy(u_sunDirection);
  412. bgfx::destroy(u_parameters);
  413. bgfx::destroy(u_perezCoeff);
  414. bgfx::destroy(m_lightmapTexture);
  415. bgfx::destroy(m_landscapeProgram);
  416. bgfx::frame();
  417. // Shutdown bgfx.
  418. bgfx::shutdown();
  419. return 0;
  420. }
  421. void imgui(float _width)
  422. {
  423. ImGui::Begin("ProceduralSky");
  424. ImGui::SetWindowSize(ImVec2(_width, 200.0f) );
  425. ImGui::SliderFloat("Time scale", &m_timeScale, 0.0f, 1.0f);
  426. ImGui::SliderFloat("Time", &m_time, 0.0f, 24.0f);
  427. ImGui::SliderFloat("Latitude", &m_sun.m_latitude, -90.0f, 90.0f);
  428. ImGui::SliderFloat("Turbidity", &m_turbidity, 1.9f, 10.0f);
  429. ImGui::Checkbox("Prevent color banding", &m_sky.m_preventBanding);
  430. const char* items[] =
  431. {
  432. "January",
  433. "February",
  434. "March",
  435. "April",
  436. "May",
  437. "June",
  438. "July",
  439. "August",
  440. "September",
  441. "October",
  442. "November",
  443. "December"
  444. };
  445. ImGui::Combo("Month", (int*)&m_sun.m_month, items, 12);
  446. ImGui::End();
  447. }
  448. bool update() override
  449. {
  450. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  451. {
  452. int64_t now = bx::getHPCounter();
  453. static int64_t last = now;
  454. const int64_t frameTime = now - last;
  455. last = now;
  456. const double freq = double(bx::getHPFrequency());
  457. const float deltaTime = float(frameTime / freq);
  458. m_time += m_timeScale * deltaTime;
  459. m_time = bx::mod(m_time, 24.0f);
  460. m_sun.Update(m_time);
  461. imguiBeginFrame(m_mouseState.m_mx
  462. , m_mouseState.m_my
  463. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  464. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  465. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  466. , m_mouseState.m_mz
  467. , uint16_t(m_width)
  468. , uint16_t(m_height)
  469. );
  470. showExampleDialog(this);
  471. ImGui::SetNextWindowPos(
  472. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  473. , ImGuiCond_FirstUseEver
  474. );
  475. imgui(m_width / 5.0f - 10.0f);
  476. imguiEndFrame();
  477. // Update camera.
  478. cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
  479. // Set view 0 default viewport.
  480. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height));
  481. float view[16];
  482. cameraGetViewMtx(view);
  483. float proj[16];
  484. bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 2000.0f, bgfx::getCaps()->homogeneousDepth);
  485. bgfx::setViewTransform(0, view, proj);
  486. Color sunLuminanceXYZ = m_sunLuminanceXYZ.GetValue(m_time);
  487. Color sunLuminanceRGB = xyzToRgb(sunLuminanceXYZ);
  488. Color skyLuminanceXYZ = m_skyLuminanceXYZ.GetValue(m_time);
  489. Color skyLuminanceRGB = xyzToRgb(skyLuminanceXYZ);
  490. bgfx::setUniform(u_sunLuminance, &sunLuminanceRGB.x);
  491. bgfx::setUniform(u_skyLuminanceXYZ, &skyLuminanceXYZ.x);
  492. bgfx::setUniform(u_skyLuminance, &skyLuminanceRGB.x);
  493. bgfx::setUniform(u_sunDirection, &m_sun.m_sunDir.x);
  494. float exposition[4] = { 0.02f, 3.0f, 0.1f, m_time };
  495. bgfx::setUniform(u_parameters, exposition);
  496. float perezCoeff[4 * 5];
  497. computePerezCoeff(m_turbidity, perezCoeff);
  498. bgfx::setUniform(u_perezCoeff, perezCoeff, 5);
  499. bgfx::setTexture(0, s_texLightmap, m_lightmapTexture);
  500. meshSubmit(m_mesh, 0, m_landscapeProgram, NULL);
  501. m_sky.draw();
  502. bgfx::frame();
  503. return true;
  504. }
  505. return false;
  506. }
  507. void computePerezCoeff(float _turbidity, float* _outPerezCoeff)
  508. {
  509. const bx::Vec3 turbidity = { _turbidity, _turbidity, _turbidity };
  510. for (uint32_t ii = 0; ii < 5; ++ii)
  511. {
  512. const bx::Vec3 tmp = bx::mad(ABCDE_t[ii], turbidity, ABCDE[ii]);
  513. float* out = _outPerezCoeff + 4 * ii;
  514. bx::store(out, tmp);
  515. out[3] = 0.0f;
  516. }
  517. }
  518. bgfx::ProgramHandle m_landscapeProgram;
  519. bgfx::UniformHandle s_texLightmap;
  520. bgfx::TextureHandle m_lightmapTexture;
  521. bgfx::UniformHandle u_sunLuminance;
  522. bgfx::UniformHandle u_skyLuminanceXYZ;
  523. bgfx::UniformHandle u_skyLuminance;
  524. bgfx::UniformHandle u_sunDirection;
  525. bgfx::UniformHandle u_parameters;
  526. bgfx::UniformHandle u_perezCoeff;
  527. ProceduralSky m_sky;
  528. SunController m_sun;
  529. DynamicValueController m_sunLuminanceXYZ;
  530. DynamicValueController m_skyLuminanceXYZ;
  531. uint32_t m_width;
  532. uint32_t m_height;
  533. uint32_t m_debug;
  534. uint32_t m_reset;
  535. Mesh* m_mesh;
  536. entry::MouseState m_mouseState;
  537. float m_time;
  538. float m_timeScale;
  539. int64_t m_timeOffset;
  540. float m_turbidity;
  541. };
  542. } // namespace
  543. ENTRY_IMPLEMENT_MAIN(
  544. ExampleProceduralSky
  545. , "36-sky"
  546. , "Perez dynamic sky model."
  547. , "https://bkaradzic.github.io/bgfx/examples.html#sky"
  548. );