shader.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. Copyright (C) 2013 Kahrl <kahrl@gmx.net>
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU Lesser General Public License as published by
  7. the Free Software Foundation; either version 2.1 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public License along
  14. with this program; if not, write to the Free Software Foundation, Inc.,
  15. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. */
  17. #include <fstream>
  18. #include <iterator>
  19. #include "shader.h"
  20. #include "irrlichttypes_extrabloated.h"
  21. #include "irr_ptr.h"
  22. #include "debug.h"
  23. #include "filesys.h"
  24. #include "util/container.h"
  25. #include "util/thread.h"
  26. #include "settings.h"
  27. #include <ICameraSceneNode.h>
  28. #include <IGPUProgrammingServices.h>
  29. #include <IMaterialRenderer.h>
  30. #include <IMaterialRendererServices.h>
  31. #include <IShaderConstantSetCallBack.h>
  32. #include "client/renderingengine.h"
  33. #include <EShaderTypes.h>
  34. #include "gettext.h"
  35. #include "log.h"
  36. #include "gamedef.h"
  37. #include "client/tile.h"
  38. #include "config.h"
  39. #include <mt_opengl.h>
  40. /*
  41. A cache from shader name to shader path
  42. */
  43. MutexedMap<std::string, std::string> g_shadername_to_path_cache;
  44. /*
  45. Gets the path to a shader by first checking if the file
  46. name_of_shader/filename
  47. exists in shader_path and if not, using the data path.
  48. If not found, returns "".
  49. Utilizes a thread-safe cache.
  50. */
  51. std::string getShaderPath(const std::string &name_of_shader,
  52. const std::string &filename)
  53. {
  54. std::string combined = name_of_shader + DIR_DELIM + filename;
  55. std::string fullpath;
  56. /*
  57. Check from cache
  58. */
  59. bool incache = g_shadername_to_path_cache.get(combined, &fullpath);
  60. if(incache)
  61. return fullpath;
  62. /*
  63. Check from shader_path
  64. */
  65. std::string shader_path = g_settings->get("shader_path");
  66. if (!shader_path.empty()) {
  67. std::string testpath = shader_path + DIR_DELIM + combined;
  68. if(fs::PathExists(testpath))
  69. fullpath = testpath;
  70. }
  71. /*
  72. Check from default data directory
  73. */
  74. if (fullpath.empty()) {
  75. std::string rel_path = std::string("client") + DIR_DELIM
  76. + "shaders" + DIR_DELIM
  77. + name_of_shader + DIR_DELIM
  78. + filename;
  79. std::string testpath = porting::path_share + DIR_DELIM + rel_path;
  80. if(fs::PathExists(testpath))
  81. fullpath = testpath;
  82. }
  83. // Add to cache (also an empty result is cached)
  84. g_shadername_to_path_cache.set(combined, fullpath);
  85. // Finally return it
  86. return fullpath;
  87. }
  88. /*
  89. SourceShaderCache: A cache used for storing source shaders.
  90. */
  91. class SourceShaderCache
  92. {
  93. public:
  94. void insert(const std::string &name_of_shader, const std::string &filename,
  95. const std::string &program, bool prefer_local)
  96. {
  97. std::string combined = name_of_shader + DIR_DELIM + filename;
  98. // Try to use local shader instead if asked to
  99. if(prefer_local){
  100. std::string path = getShaderPath(name_of_shader, filename);
  101. if(!path.empty()){
  102. std::string p = readFile(path);
  103. if (!p.empty()) {
  104. m_programs[combined] = p;
  105. return;
  106. }
  107. }
  108. }
  109. m_programs[combined] = program;
  110. }
  111. std::string get(const std::string &name_of_shader,
  112. const std::string &filename)
  113. {
  114. std::string combined = name_of_shader + DIR_DELIM + filename;
  115. StringMap::iterator n = m_programs.find(combined);
  116. if (n != m_programs.end())
  117. return n->second;
  118. return "";
  119. }
  120. // Primarily fetches from cache, secondarily tries to read from filesystem
  121. std::string getOrLoad(const std::string &name_of_shader,
  122. const std::string &filename)
  123. {
  124. std::string combined = name_of_shader + DIR_DELIM + filename;
  125. StringMap::iterator n = m_programs.find(combined);
  126. if (n != m_programs.end())
  127. return n->second;
  128. std::string path = getShaderPath(name_of_shader, filename);
  129. if (path.empty()) {
  130. infostream << "SourceShaderCache::getOrLoad(): No path found for \""
  131. << combined << "\"" << std::endl;
  132. return "";
  133. }
  134. infostream << "SourceShaderCache::getOrLoad(): Loading path \""
  135. << path << "\"" << std::endl;
  136. std::string p = readFile(path);
  137. if (!p.empty()) {
  138. m_programs[combined] = p;
  139. return p;
  140. }
  141. return "";
  142. }
  143. private:
  144. StringMap m_programs;
  145. std::string readFile(const std::string &path)
  146. {
  147. std::string ret;
  148. if (!fs::ReadFile(path, ret))
  149. ret.clear();
  150. return ret;
  151. }
  152. };
  153. /*
  154. ShaderCallback: Sets constants that can be used in shaders
  155. */
  156. class ShaderCallback : public video::IShaderConstantSetCallBack
  157. {
  158. std::vector<std::unique_ptr<IShaderConstantSetter>> m_setters;
  159. public:
  160. template <typename Factories>
  161. ShaderCallback(const Factories &factories)
  162. {
  163. for (auto &&factory : factories) {
  164. auto *setter = factory->create();
  165. if (setter)
  166. m_setters.emplace_back(setter);
  167. }
  168. }
  169. virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData) override
  170. {
  171. for (auto &&setter : m_setters)
  172. setter->onSetConstants(services);
  173. }
  174. virtual void OnSetMaterial(const video::SMaterial& material) override
  175. {
  176. for (auto &&setter : m_setters)
  177. setter->onSetMaterial(material);
  178. }
  179. };
  180. /*
  181. MainShaderConstantSetter: Set basic constants required for almost everything
  182. */
  183. class MainShaderConstantSetter : public IShaderConstantSetter
  184. {
  185. CachedVertexShaderSetting<f32, 16> m_world_view_proj{"mWorldViewProj"};
  186. CachedVertexShaderSetting<f32, 16> m_world{"mWorld"};
  187. // Modelview matrix
  188. CachedVertexShaderSetting<float, 16> m_world_view{"mWorldView"};
  189. // Texture matrix
  190. CachedVertexShaderSetting<float, 16> m_texture{"mTexture"};
  191. // commonly used way to pass material color to shader
  192. video::SColor m_emissive_color;
  193. CachedPixelShaderSetting<float, 4> m_emissive_color_setting{"emissiveColor"};
  194. public:
  195. ~MainShaderConstantSetter() = default;
  196. virtual void onSetMaterial(const video::SMaterial& material) override
  197. {
  198. m_emissive_color = material.EmissiveColor;
  199. }
  200. virtual void onSetConstants(video::IMaterialRendererServices *services) override
  201. {
  202. video::IVideoDriver *driver = services->getVideoDriver();
  203. assert(driver);
  204. // Set world matrix
  205. core::matrix4 world = driver->getTransform(video::ETS_WORLD);
  206. m_world.set(world, services);
  207. // Set clip matrix
  208. core::matrix4 worldView;
  209. worldView = driver->getTransform(video::ETS_VIEW);
  210. worldView *= world;
  211. core::matrix4 worldViewProj;
  212. worldViewProj = driver->getTransform(video::ETS_PROJECTION);
  213. worldViewProj *= worldView;
  214. m_world_view_proj.set(worldViewProj, services);
  215. if (driver->getDriverType() == video::EDT_OGLES2 || driver->getDriverType() == video::EDT_OPENGL3) {
  216. core::matrix4 texture = driver->getTransform(video::ETS_TEXTURE_0);
  217. m_world_view.set(worldView, services);
  218. m_texture.set(texture, services);
  219. }
  220. video::SColorf emissive_color(m_emissive_color);
  221. m_emissive_color_setting.set(emissive_color, services);
  222. }
  223. };
  224. class MainShaderConstantSetterFactory : public IShaderConstantSetterFactory
  225. {
  226. public:
  227. virtual IShaderConstantSetter* create()
  228. { return new MainShaderConstantSetter(); }
  229. };
  230. /*
  231. ShaderSource
  232. */
  233. class ShaderSource : public IWritableShaderSource
  234. {
  235. public:
  236. ShaderSource();
  237. ~ShaderSource() override;
  238. /*
  239. - If shader material specified by name is found from cache,
  240. return the cached id.
  241. - Otherwise generate the shader material, add to cache and return id.
  242. The id 0 points to a null shader. Its material is EMT_SOLID.
  243. */
  244. u32 getShaderIdDirect(const std::string &name,
  245. MaterialType material_type, NodeDrawType drawtype) override;
  246. /*
  247. If shader specified by the name pointed by the id doesn't
  248. exist, create it, then return id.
  249. Can be called from any thread. If called from some other thread
  250. and not found in cache, the call is queued to the main thread
  251. for processing.
  252. */
  253. u32 getShader(const std::string &name,
  254. MaterialType material_type, NodeDrawType drawtype) override;
  255. ShaderInfo getShaderInfo(u32 id) override;
  256. // Processes queued shader requests from other threads.
  257. // Shall be called from the main thread.
  258. void processQueue() override;
  259. // Insert a shader program into the cache without touching the
  260. // filesystem. Shall be called from the main thread.
  261. void insertSourceShader(const std::string &name_of_shader,
  262. const std::string &filename, const std::string &program) override;
  263. // Rebuild shaders from the current set of source shaders
  264. // Shall be called from the main thread.
  265. void rebuildShaders() override;
  266. void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) override
  267. {
  268. m_setter_factories.emplace_back(setter);
  269. }
  270. private:
  271. // The id of the thread that is allowed to use irrlicht directly
  272. std::thread::id m_main_thread;
  273. // Cache of source shaders
  274. // This should be only accessed from the main thread
  275. SourceShaderCache m_sourcecache;
  276. // A shader id is index in this array.
  277. // The first position contains a dummy shader.
  278. std::vector<ShaderInfo> m_shaderinfo_cache;
  279. // The former container is behind this mutex
  280. std::mutex m_shaderinfo_cache_mutex;
  281. #if 0
  282. // Queued shader fetches (to be processed by the main thread)
  283. RequestQueue<std::string, u32, u8, u8> m_get_shader_queue;
  284. #endif
  285. // Global constant setter factories
  286. std::vector<std::unique_ptr<IShaderConstantSetterFactory>> m_setter_factories;
  287. // Generate shader given the shader name.
  288. ShaderInfo generateShader(const std::string &name,
  289. MaterialType material_type, NodeDrawType drawtype);
  290. };
  291. IWritableShaderSource *createShaderSource()
  292. {
  293. return new ShaderSource();
  294. }
  295. ShaderSource::ShaderSource()
  296. {
  297. m_main_thread = std::this_thread::get_id();
  298. // Add a dummy ShaderInfo as the first index, named ""
  299. m_shaderinfo_cache.emplace_back();
  300. // Add main global constant setter
  301. addShaderConstantSetterFactory(new MainShaderConstantSetterFactory());
  302. }
  303. ShaderSource::~ShaderSource()
  304. {
  305. MutexAutoLock lock(m_shaderinfo_cache_mutex);
  306. #if IRRLICHT_VERSION_MT_REVISION >= 15
  307. // Delete materials
  308. video::IGPUProgrammingServices *gpu = RenderingEngine::get_video_driver()->
  309. getGPUProgrammingServices();
  310. for (ShaderInfo &i : m_shaderinfo_cache) {
  311. if (!i.name.empty())
  312. gpu->deleteShaderMaterial(i.material);
  313. }
  314. m_shaderinfo_cache.clear();
  315. #endif
  316. }
  317. u32 ShaderSource::getShader(const std::string &name,
  318. MaterialType material_type, NodeDrawType drawtype)
  319. {
  320. /*
  321. Get shader
  322. */
  323. if (std::this_thread::get_id() == m_main_thread) {
  324. return getShaderIdDirect(name, material_type, drawtype);
  325. }
  326. errorstream << "ShaderSource::getShader(): getting from "
  327. "other thread not implemented" << std::endl;
  328. #if 0
  329. // We're gonna ask the result to be put into here
  330. static ResultQueue<std::string, u32, u8, u8> result_queue;
  331. // Throw a request in
  332. m_get_shader_queue.add(name, 0, 0, &result_queue);
  333. /* infostream<<"Waiting for shader from main thread, name=\""
  334. <<name<<"\""<<std::endl;*/
  335. while(true) {
  336. GetResult<std::string, u32, u8, u8>
  337. result = result_queue.pop_frontNoEx();
  338. if (result.key == name) {
  339. return result.item;
  340. }
  341. errorstream << "Got shader with invalid name: " << result.key << std::endl;
  342. }
  343. infostream << "getShader(): Failed" << std::endl;
  344. #endif
  345. return 0;
  346. }
  347. /*
  348. This method generates all the shaders
  349. */
  350. u32 ShaderSource::getShaderIdDirect(const std::string &name,
  351. MaterialType material_type, NodeDrawType drawtype)
  352. {
  353. // Empty name means shader 0
  354. if (name.empty()) {
  355. infostream<<"getShaderIdDirect(): name is empty"<<std::endl;
  356. return 0;
  357. }
  358. // Check if already have such instance
  359. for(u32 i=0; i<m_shaderinfo_cache.size(); i++){
  360. ShaderInfo *info = &m_shaderinfo_cache[i];
  361. if(info->name == name && info->material_type == material_type &&
  362. info->drawtype == drawtype)
  363. return i;
  364. }
  365. /*
  366. Calling only allowed from main thread
  367. */
  368. if (std::this_thread::get_id() != m_main_thread) {
  369. errorstream<<"ShaderSource::getShaderIdDirect() "
  370. "called not from main thread"<<std::endl;
  371. return 0;
  372. }
  373. ShaderInfo info = generateShader(name, material_type, drawtype);
  374. /*
  375. Add shader to caches (add dummy shaders too)
  376. */
  377. MutexAutoLock lock(m_shaderinfo_cache_mutex);
  378. u32 id = m_shaderinfo_cache.size();
  379. m_shaderinfo_cache.push_back(info);
  380. infostream<<"getShaderIdDirect(): "
  381. <<"Returning id="<<id<<" for name \""<<name<<"\""<<std::endl;
  382. return id;
  383. }
  384. ShaderInfo ShaderSource::getShaderInfo(u32 id)
  385. {
  386. MutexAutoLock lock(m_shaderinfo_cache_mutex);
  387. if(id >= m_shaderinfo_cache.size())
  388. return ShaderInfo();
  389. return m_shaderinfo_cache[id];
  390. }
  391. void ShaderSource::processQueue()
  392. {
  393. }
  394. void ShaderSource::insertSourceShader(const std::string &name_of_shader,
  395. const std::string &filename, const std::string &program)
  396. {
  397. /*infostream<<"ShaderSource::insertSourceShader(): "
  398. "name_of_shader=\""<<name_of_shader<<"\", "
  399. "filename=\""<<filename<<"\""<<std::endl;*/
  400. sanity_check(std::this_thread::get_id() == m_main_thread);
  401. m_sourcecache.insert(name_of_shader, filename, program, true);
  402. }
  403. void ShaderSource::rebuildShaders()
  404. {
  405. MutexAutoLock lock(m_shaderinfo_cache_mutex);
  406. #if IRRLICHT_VERSION_MT_REVISION >= 15
  407. // Delete materials
  408. video::IGPUProgrammingServices *gpu = RenderingEngine::get_video_driver()->
  409. getGPUProgrammingServices();
  410. for (ShaderInfo &i : m_shaderinfo_cache) {
  411. if (!i.name.empty()) {
  412. gpu->deleteShaderMaterial(i.material);
  413. i.material = video::EMT_SOLID; // invalidate
  414. }
  415. }
  416. #endif
  417. // Recreate shaders
  418. for (ShaderInfo &i : m_shaderinfo_cache) {
  419. ShaderInfo *info = &i;
  420. if (!info->name.empty()) {
  421. *info = generateShader(info->name, info->material_type, info->drawtype);
  422. }
  423. }
  424. }
  425. ShaderInfo ShaderSource::generateShader(const std::string &name,
  426. MaterialType material_type, NodeDrawType drawtype)
  427. {
  428. ShaderInfo shaderinfo;
  429. shaderinfo.name = name;
  430. shaderinfo.material_type = material_type;
  431. shaderinfo.drawtype = drawtype;
  432. switch (material_type) {
  433. case TILE_MATERIAL_OPAQUE:
  434. case TILE_MATERIAL_LIQUID_OPAQUE:
  435. case TILE_MATERIAL_WAVING_LIQUID_OPAQUE:
  436. shaderinfo.base_material = video::EMT_SOLID;
  437. break;
  438. case TILE_MATERIAL_ALPHA:
  439. case TILE_MATERIAL_PLAIN_ALPHA:
  440. case TILE_MATERIAL_LIQUID_TRANSPARENT:
  441. case TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT:
  442. shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
  443. break;
  444. case TILE_MATERIAL_BASIC:
  445. case TILE_MATERIAL_PLAIN:
  446. case TILE_MATERIAL_WAVING_LEAVES:
  447. case TILE_MATERIAL_WAVING_PLANTS:
  448. case TILE_MATERIAL_WAVING_LIQUID_BASIC:
  449. shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
  450. break;
  451. }
  452. shaderinfo.material = shaderinfo.base_material;
  453. bool enable_shaders = g_settings->getBool("enable_shaders");
  454. if (!enable_shaders)
  455. return shaderinfo;
  456. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  457. video::IGPUProgrammingServices *gpu = driver->getGPUProgrammingServices();
  458. if (!driver->queryFeature(video::EVDF_ARB_GLSL) || !gpu) {
  459. throw ShaderException(gettext("Shaders are enabled but GLSL is not "
  460. "supported by the driver."));
  461. }
  462. // Create shaders header
  463. bool fully_programmable = driver->getDriverType() == video::EDT_OGLES2 || driver->getDriverType() == video::EDT_OPENGL3;
  464. std::stringstream shaders_header;
  465. shaders_header
  466. << std::noboolalpha
  467. << std::showpoint // for GLSL ES
  468. ;
  469. std::string vertex_header, fragment_header, geometry_header;
  470. if (fully_programmable) {
  471. if (driver->getDriverType() == video::EDT_OPENGL3) {
  472. shaders_header << "#version 150\n";
  473. } else {
  474. shaders_header << "#version 100\n";
  475. }
  476. vertex_header = R"(
  477. precision mediump float;
  478. uniform highp mat4 mWorldView;
  479. uniform highp mat4 mWorldViewProj;
  480. uniform mediump mat4 mTexture;
  481. attribute highp vec4 inVertexPosition;
  482. attribute lowp vec4 inVertexColor;
  483. attribute mediump vec4 inTexCoord0;
  484. attribute mediump vec3 inVertexNormal;
  485. attribute mediump vec4 inVertexTangent;
  486. attribute mediump vec4 inVertexBinormal;
  487. )";
  488. fragment_header = R"(
  489. precision mediump float;
  490. )";
  491. } else {
  492. shaders_header << R"(
  493. #version 120
  494. #define lowp
  495. #define mediump
  496. #define highp
  497. )";
  498. vertex_header = R"(
  499. #define mWorldView gl_ModelViewMatrix
  500. #define mWorldViewProj gl_ModelViewProjectionMatrix
  501. #define mTexture (gl_TextureMatrix[0])
  502. #define inVertexPosition gl_Vertex
  503. #define inVertexColor gl_Color
  504. #define inTexCoord0 gl_MultiTexCoord0
  505. #define inVertexNormal gl_Normal
  506. #define inVertexTangent gl_MultiTexCoord1
  507. #define inVertexBinormal gl_MultiTexCoord2
  508. )";
  509. }
  510. // map legacy semantic texture names to texture identifiers
  511. fragment_header += R"(
  512. #define baseTexture texture0
  513. #define normalTexture texture1
  514. #define textureFlags texture2
  515. )";
  516. bool use_discard = fully_programmable;
  517. // For renderers that should use discard instead of GL_ALPHA_TEST
  518. const char *renderer = reinterpret_cast<const char*>(GL.GetString(GL.RENDERER));
  519. if (strstr(renderer, "GC7000"))
  520. use_discard = true;
  521. if (use_discard) {
  522. if (shaderinfo.base_material == video::EMT_TRANSPARENT_ALPHA_CHANNEL)
  523. shaders_header << "#define USE_DISCARD 1\n";
  524. else if (shaderinfo.base_material == video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF)
  525. shaders_header << "#define USE_DISCARD_REF 1\n";
  526. }
  527. #define PROVIDE(constant) shaders_header << "#define " #constant " " << (int)constant << "\n"
  528. PROVIDE(NDT_NORMAL);
  529. PROVIDE(NDT_AIRLIKE);
  530. PROVIDE(NDT_LIQUID);
  531. PROVIDE(NDT_FLOWINGLIQUID);
  532. PROVIDE(NDT_GLASSLIKE);
  533. PROVIDE(NDT_ALLFACES);
  534. PROVIDE(NDT_ALLFACES_OPTIONAL);
  535. PROVIDE(NDT_TORCHLIKE);
  536. PROVIDE(NDT_SIGNLIKE);
  537. PROVIDE(NDT_PLANTLIKE);
  538. PROVIDE(NDT_FENCELIKE);
  539. PROVIDE(NDT_RAILLIKE);
  540. PROVIDE(NDT_NODEBOX);
  541. PROVIDE(NDT_GLASSLIKE_FRAMED);
  542. PROVIDE(NDT_FIRELIKE);
  543. PROVIDE(NDT_GLASSLIKE_FRAMED_OPTIONAL);
  544. PROVIDE(NDT_PLANTLIKE_ROOTED);
  545. PROVIDE(TILE_MATERIAL_BASIC);
  546. PROVIDE(TILE_MATERIAL_ALPHA);
  547. PROVIDE(TILE_MATERIAL_LIQUID_TRANSPARENT);
  548. PROVIDE(TILE_MATERIAL_LIQUID_OPAQUE);
  549. PROVIDE(TILE_MATERIAL_WAVING_LEAVES);
  550. PROVIDE(TILE_MATERIAL_WAVING_PLANTS);
  551. PROVIDE(TILE_MATERIAL_OPAQUE);
  552. PROVIDE(TILE_MATERIAL_WAVING_LIQUID_BASIC);
  553. PROVIDE(TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT);
  554. PROVIDE(TILE_MATERIAL_WAVING_LIQUID_OPAQUE);
  555. PROVIDE(TILE_MATERIAL_PLAIN);
  556. PROVIDE(TILE_MATERIAL_PLAIN_ALPHA);
  557. #undef PROVIDE
  558. shaders_header << "#define MATERIAL_TYPE " << (int)material_type << "\n";
  559. shaders_header << "#define DRAW_TYPE " << (int)drawtype << "\n";
  560. bool enable_waving_water = g_settings->getBool("enable_waving_water");
  561. shaders_header << "#define ENABLE_WAVING_WATER " << enable_waving_water << "\n";
  562. if (enable_waving_water) {
  563. shaders_header << "#define WATER_WAVE_HEIGHT " << g_settings->getFloat("water_wave_height") << "\n";
  564. shaders_header << "#define WATER_WAVE_LENGTH " << g_settings->getFloat("water_wave_length") << "\n";
  565. shaders_header << "#define WATER_WAVE_SPEED " << g_settings->getFloat("water_wave_speed") << "\n";
  566. }
  567. shaders_header << "#define ENABLE_WAVING_LEAVES " << g_settings->getBool("enable_waving_leaves") << "\n";
  568. shaders_header << "#define ENABLE_WAVING_PLANTS " << g_settings->getBool("enable_waving_plants") << "\n";
  569. shaders_header << "#define ENABLE_TONE_MAPPING " << g_settings->getBool("tone_mapping") << "\n";
  570. if (g_settings->getBool("enable_dynamic_shadows")) {
  571. shaders_header << "#define ENABLE_DYNAMIC_SHADOWS 1\n";
  572. if (g_settings->getBool("shadow_map_color"))
  573. shaders_header << "#define COLORED_SHADOWS 1\n";
  574. if (g_settings->getBool("shadow_poisson_filter"))
  575. shaders_header << "#define POISSON_FILTER 1\n";
  576. s32 shadow_filter = g_settings->getS32("shadow_filters");
  577. shaders_header << "#define SHADOW_FILTER " << shadow_filter << "\n";
  578. float shadow_soft_radius = g_settings->getFloat("shadow_soft_radius");
  579. if (shadow_soft_radius < 1.0f)
  580. shadow_soft_radius = 1.0f;
  581. shaders_header << "#define SOFTSHADOWRADIUS " << shadow_soft_radius << "\n";
  582. }
  583. if (g_settings->getBool("enable_bloom")) {
  584. shaders_header << "#define ENABLE_BLOOM 1\n";
  585. if (g_settings->getBool("enable_bloom_debug"))
  586. shaders_header << "#define ENABLE_BLOOM_DEBUG 1\n";
  587. }
  588. if (g_settings->getBool("enable_auto_exposure"))
  589. shaders_header << "#define ENABLE_AUTO_EXPOSURE 1\n";
  590. if (g_settings->get("antialiasing") == "ssaa") {
  591. shaders_header << "#define ENABLE_SSAA 1\n";
  592. u16 ssaa_scale = MYMAX(2, g_settings->getU16("fsaa"));
  593. shaders_header << "#define SSAA_SCALE " << ssaa_scale << ".\n";
  594. }
  595. if (g_settings->getBool("debanding"))
  596. shaders_header << "#define ENABLE_DITHERING 1\n";
  597. if (g_settings->getBool("enable_volumetric_lighting")) {
  598. shaders_header << "#define VOLUMETRIC_LIGHT 1\n";
  599. }
  600. shaders_header << "#line 0\n"; // reset the line counter for meaningful diagnostics
  601. std::string common_header = shaders_header.str();
  602. std::string vertex_shader = m_sourcecache.getOrLoad(name, "opengl_vertex.glsl");
  603. std::string fragment_shader = m_sourcecache.getOrLoad(name, "opengl_fragment.glsl");
  604. std::string geometry_shader = m_sourcecache.getOrLoad(name, "opengl_geometry.glsl");
  605. vertex_shader = common_header + vertex_header + vertex_shader;
  606. fragment_shader = common_header + fragment_header + fragment_shader;
  607. const char *geometry_shader_ptr = nullptr; // optional
  608. if (!geometry_shader.empty()) {
  609. geometry_shader = common_header + geometry_header + geometry_shader;
  610. geometry_shader_ptr = geometry_shader.c_str();
  611. }
  612. irr_ptr<ShaderCallback> cb{new ShaderCallback(m_setter_factories)};
  613. infostream<<"Compiling high level shaders for "<<name<<std::endl;
  614. s32 shadermat = gpu->addHighLevelShaderMaterial(
  615. vertex_shader.c_str(), nullptr, video::EVST_VS_1_1,
  616. fragment_shader.c_str(), nullptr, video::EPST_PS_1_1,
  617. geometry_shader_ptr, nullptr, video::EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLES, 0,
  618. cb.get(), shaderinfo.base_material, 1);
  619. if (shadermat == -1) {
  620. errorstream<<"generate_shader(): "
  621. "failed to generate \""<<name<<"\", "
  622. "addHighLevelShaderMaterial failed."
  623. <<std::endl;
  624. dumpShaderProgram(warningstream, "Vertex", vertex_shader);
  625. dumpShaderProgram(warningstream, "Fragment", fragment_shader);
  626. dumpShaderProgram(warningstream, "Geometry", geometry_shader);
  627. throw ShaderException(
  628. fmtgettext("Failed to compile the \"%s\" shader.", name.c_str()) +
  629. strgettext("\nCheck debug.txt for details."));
  630. }
  631. // Apply the newly created material type
  632. shaderinfo.material = (video::E_MATERIAL_TYPE) shadermat;
  633. return shaderinfo;
  634. }
  635. void dumpShaderProgram(std::ostream &output_stream,
  636. const std::string &program_type, std::string_view program)
  637. {
  638. output_stream << program_type << " shader program:" << std::endl <<
  639. "----------------------------------" << std::endl;
  640. size_t pos = 0;
  641. size_t prev = 0;
  642. s16 line = 1;
  643. while ((pos = program.find('\n', prev)) != std::string::npos) {
  644. output_stream << line++ << ": "<< program.substr(prev, pos - prev) <<
  645. std::endl;
  646. prev = pos + 1;
  647. }
  648. output_stream << line << ": " << program.substr(prev) << std::endl <<
  649. "End of " << program_type << " shader program." << std::endl <<
  650. " " << std::endl;
  651. }