shader.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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 "log.h"
  35. #include "gamedef.h"
  36. #include "client/tile.h"
  37. #include "config.h"
  38. #include <mt_opengl.h>
  39. /*
  40. A cache from shader name to shader path
  41. */
  42. MutexedMap<std::string, std::string> g_shadername_to_path_cache;
  43. /*
  44. Gets the path to a shader by first checking if the file
  45. name_of_shader/filename
  46. exists in shader_path and if not, using the data path.
  47. If not found, returns "".
  48. Utilizes a thread-safe cache.
  49. */
  50. std::string getShaderPath(const std::string &name_of_shader,
  51. const std::string &filename)
  52. {
  53. std::string combined = name_of_shader + DIR_DELIM + filename;
  54. std::string fullpath;
  55. /*
  56. Check from cache
  57. */
  58. bool incache = g_shadername_to_path_cache.get(combined, &fullpath);
  59. if(incache)
  60. return fullpath;
  61. /*
  62. Check from shader_path
  63. */
  64. std::string shader_path = g_settings->get("shader_path");
  65. if (!shader_path.empty()) {
  66. std::string testpath = shader_path + DIR_DELIM + combined;
  67. if(fs::PathExists(testpath))
  68. fullpath = testpath;
  69. }
  70. /*
  71. Check from default data directory
  72. */
  73. if (fullpath.empty()) {
  74. std::string rel_path = std::string("client") + DIR_DELIM
  75. + "shaders" + DIR_DELIM
  76. + name_of_shader + DIR_DELIM
  77. + filename;
  78. std::string testpath = porting::path_share + DIR_DELIM + rel_path;
  79. if(fs::PathExists(testpath))
  80. fullpath = testpath;
  81. }
  82. // Add to cache (also an empty result is cached)
  83. g_shadername_to_path_cache.set(combined, fullpath);
  84. // Finally return it
  85. return fullpath;
  86. }
  87. /*
  88. SourceShaderCache: A cache used for storing source shaders.
  89. */
  90. class SourceShaderCache
  91. {
  92. public:
  93. void insert(const std::string &name_of_shader, const std::string &filename,
  94. const std::string &program, bool prefer_local)
  95. {
  96. std::string combined = name_of_shader + DIR_DELIM + filename;
  97. // Try to use local shader instead if asked to
  98. if(prefer_local){
  99. std::string path = getShaderPath(name_of_shader, filename);
  100. if(!path.empty()){
  101. std::string p = readFile(path);
  102. if (!p.empty()) {
  103. m_programs[combined] = p;
  104. return;
  105. }
  106. }
  107. }
  108. m_programs[combined] = program;
  109. }
  110. std::string get(const std::string &name_of_shader,
  111. const std::string &filename)
  112. {
  113. std::string combined = name_of_shader + DIR_DELIM + filename;
  114. StringMap::iterator n = m_programs.find(combined);
  115. if (n != m_programs.end())
  116. return n->second;
  117. return "";
  118. }
  119. // Primarily fetches from cache, secondarily tries to read from filesystem
  120. std::string getOrLoad(const std::string &name_of_shader,
  121. const std::string &filename)
  122. {
  123. std::string combined = name_of_shader + DIR_DELIM + filename;
  124. StringMap::iterator n = m_programs.find(combined);
  125. if (n != m_programs.end())
  126. return n->second;
  127. std::string path = getShaderPath(name_of_shader, filename);
  128. if (path.empty()) {
  129. infostream << "SourceShaderCache::getOrLoad(): No path found for \""
  130. << combined << "\"" << std::endl;
  131. return "";
  132. }
  133. infostream << "SourceShaderCache::getOrLoad(): Loading path \""
  134. << path << "\"" << std::endl;
  135. std::string p = readFile(path);
  136. if (!p.empty()) {
  137. m_programs[combined] = p;
  138. return p;
  139. }
  140. return "";
  141. }
  142. private:
  143. StringMap m_programs;
  144. std::string readFile(const std::string &path)
  145. {
  146. std::ifstream is(path.c_str(), std::ios::binary);
  147. if(!is.is_open())
  148. return "";
  149. std::ostringstream tmp_os;
  150. tmp_os << is.rdbuf();
  151. return tmp_os.str();
  152. }
  153. };
  154. /*
  155. ShaderCallback: Sets constants that can be used in shaders
  156. */
  157. class ShaderCallback : public video::IShaderConstantSetCallBack
  158. {
  159. std::vector<std::unique_ptr<IShaderConstantSetter>> m_setters;
  160. public:
  161. template <typename Factories>
  162. ShaderCallback(const Factories &factories)
  163. {
  164. for (auto &&factory : factories)
  165. m_setters.push_back(std::unique_ptr<IShaderConstantSetter>(factory->create()));
  166. }
  167. virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData) override
  168. {
  169. video::IVideoDriver *driver = services->getVideoDriver();
  170. sanity_check(driver != NULL);
  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;
  186. CachedVertexShaderSetting<f32, 16> m_world;
  187. // Shadow-related
  188. CachedPixelShaderSetting<f32, 16> m_shadow_view_proj;
  189. CachedPixelShaderSetting<f32, 3> m_light_direction;
  190. CachedPixelShaderSetting<f32> m_texture_res;
  191. CachedPixelShaderSetting<f32> m_shadow_strength;
  192. CachedPixelShaderSetting<f32> m_time_of_day;
  193. CachedPixelShaderSetting<f32> m_shadowfar;
  194. CachedPixelShaderSetting<f32, 4> m_camera_pos;
  195. CachedPixelShaderSetting<s32> m_shadow_texture;
  196. CachedVertexShaderSetting<f32> m_perspective_bias0_vertex;
  197. CachedPixelShaderSetting<f32> m_perspective_bias0_pixel;
  198. CachedVertexShaderSetting<f32> m_perspective_bias1_vertex;
  199. CachedPixelShaderSetting<f32> m_perspective_bias1_pixel;
  200. CachedVertexShaderSetting<f32> m_perspective_zbias_vertex;
  201. CachedPixelShaderSetting<f32> m_perspective_zbias_pixel;
  202. #if ENABLE_GLES
  203. // Modelview matrix
  204. CachedVertexShaderSetting<float, 16> m_world_view;
  205. // Texture matrix
  206. CachedVertexShaderSetting<float, 16> m_texture;
  207. // Normal matrix
  208. CachedVertexShaderSetting<float, 9> m_normal;
  209. #endif
  210. public:
  211. MainShaderConstantSetter() :
  212. m_world_view_proj("mWorldViewProj")
  213. , m_world("mWorld")
  214. , m_shadow_view_proj("m_ShadowViewProj")
  215. , m_light_direction("v_LightDirection")
  216. , m_texture_res("f_textureresolution")
  217. , m_shadow_strength("f_shadow_strength")
  218. , m_time_of_day("f_timeofday")
  219. , m_shadowfar("f_shadowfar")
  220. , m_camera_pos("CameraPos")
  221. , m_shadow_texture("ShadowMapSampler")
  222. , m_perspective_bias0_vertex("xyPerspectiveBias0")
  223. , m_perspective_bias0_pixel("xyPerspectiveBias0")
  224. , m_perspective_bias1_vertex("xyPerspectiveBias1")
  225. , m_perspective_bias1_pixel("xyPerspectiveBias1")
  226. , m_perspective_zbias_vertex("zPerspectiveBias")
  227. , m_perspective_zbias_pixel("zPerspectiveBias")
  228. #if ENABLE_GLES
  229. , m_world_view("mWorldView")
  230. , m_texture("mTexture")
  231. , m_normal("mNormal")
  232. #endif
  233. {}
  234. ~MainShaderConstantSetter() = default;
  235. virtual void onSetConstants(video::IMaterialRendererServices *services) override
  236. {
  237. video::IVideoDriver *driver = services->getVideoDriver();
  238. sanity_check(driver);
  239. // Set world matrix
  240. core::matrix4 world = driver->getTransform(video::ETS_WORLD);
  241. m_world.set(*reinterpret_cast<float(*)[16]>(world.pointer()), services);
  242. // Set clip matrix
  243. core::matrix4 worldView;
  244. worldView = driver->getTransform(video::ETS_VIEW);
  245. worldView *= world;
  246. core::matrix4 worldViewProj;
  247. worldViewProj = driver->getTransform(video::ETS_PROJECTION);
  248. worldViewProj *= worldView;
  249. m_world_view_proj.set(*reinterpret_cast<float(*)[16]>(worldViewProj.pointer()), services);
  250. #if ENABLE_GLES
  251. core::matrix4 texture = driver->getTransform(video::ETS_TEXTURE_0);
  252. m_world_view.set(*reinterpret_cast<float(*)[16]>(worldView.pointer()), services);
  253. m_texture.set(*reinterpret_cast<float(*)[16]>(texture.pointer()), services);
  254. core::matrix4 normal;
  255. worldView.getTransposed(normal);
  256. sanity_check(normal.makeInverse());
  257. float m[9] = {
  258. normal[0], normal[1], normal[2],
  259. normal[4], normal[5], normal[6],
  260. normal[8], normal[9], normal[10],
  261. };
  262. m_normal.set(m, services);
  263. #endif
  264. // Set uniforms for Shadow shader
  265. if (ShadowRenderer *shadow = RenderingEngine::get_shadow_renderer()) {
  266. const auto &light = shadow->getDirectionalLight();
  267. core::matrix4 shadowViewProj = light.getProjectionMatrix();
  268. shadowViewProj *= light.getViewMatrix();
  269. m_shadow_view_proj.set(shadowViewProj.pointer(), services);
  270. f32 v_LightDirection[3];
  271. light.getDirection().getAs3Values(v_LightDirection);
  272. m_light_direction.set(v_LightDirection, services);
  273. f32 TextureResolution = light.getMapResolution();
  274. m_texture_res.set(&TextureResolution, services);
  275. f32 ShadowStrength = shadow->getShadowStrength();
  276. m_shadow_strength.set(&ShadowStrength, services);
  277. f32 timeOfDay = shadow->getTimeOfDay();
  278. m_time_of_day.set(&timeOfDay, services);
  279. f32 shadowFar = shadow->getMaxShadowFar();
  280. m_shadowfar.set(&shadowFar, services);
  281. f32 cam_pos[4];
  282. shadowViewProj.transformVect(cam_pos, light.getPlayerPos());
  283. m_camera_pos.set(cam_pos, services);
  284. // I dont like using this hardcoded value. maybe something like
  285. // MAX_TEXTURE - 1 or somthing like that??
  286. s32 TextureLayerID = 3;
  287. m_shadow_texture.set(&TextureLayerID, services);
  288. f32 bias0 = shadow->getPerspectiveBiasXY();
  289. m_perspective_bias0_vertex.set(&bias0, services);
  290. m_perspective_bias0_pixel.set(&bias0, services);
  291. f32 bias1 = 1.0f - bias0 + 1e-5f;
  292. m_perspective_bias1_vertex.set(&bias1, services);
  293. m_perspective_bias1_pixel.set(&bias1, services);
  294. f32 zbias = shadow->getPerspectiveBiasZ();
  295. m_perspective_zbias_vertex.set(&zbias, services);
  296. m_perspective_zbias_pixel.set(&zbias, services);
  297. }
  298. }
  299. };
  300. class MainShaderConstantSetterFactory : public IShaderConstantSetterFactory
  301. {
  302. public:
  303. virtual IShaderConstantSetter* create()
  304. { return new MainShaderConstantSetter(); }
  305. };
  306. /*
  307. ShaderSource
  308. */
  309. class ShaderSource : public IWritableShaderSource
  310. {
  311. public:
  312. ShaderSource();
  313. /*
  314. - If shader material specified by name is found from cache,
  315. return the cached id.
  316. - Otherwise generate the shader material, add to cache and return id.
  317. The id 0 points to a null shader. Its material is EMT_SOLID.
  318. */
  319. u32 getShaderIdDirect(const std::string &name,
  320. MaterialType material_type, NodeDrawType drawtype) override;
  321. /*
  322. If shader specified by the name pointed by the id doesn't
  323. exist, create it, then return id.
  324. Can be called from any thread. If called from some other thread
  325. and not found in cache, the call is queued to the main thread
  326. for processing.
  327. */
  328. u32 getShader(const std::string &name,
  329. MaterialType material_type, NodeDrawType drawtype) override;
  330. ShaderInfo getShaderInfo(u32 id) override;
  331. // Processes queued shader requests from other threads.
  332. // Shall be called from the main thread.
  333. void processQueue() override;
  334. // Insert a shader program into the cache without touching the
  335. // filesystem. Shall be called from the main thread.
  336. void insertSourceShader(const std::string &name_of_shader,
  337. const std::string &filename, const std::string &program) override;
  338. // Rebuild shaders from the current set of source shaders
  339. // Shall be called from the main thread.
  340. void rebuildShaders() override;
  341. void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) override
  342. {
  343. m_setter_factories.push_back(std::unique_ptr<IShaderConstantSetterFactory>(setter));
  344. }
  345. private:
  346. // The id of the thread that is allowed to use irrlicht directly
  347. std::thread::id m_main_thread;
  348. // Cache of source shaders
  349. // This should be only accessed from the main thread
  350. SourceShaderCache m_sourcecache;
  351. // A shader id is index in this array.
  352. // The first position contains a dummy shader.
  353. std::vector<ShaderInfo> m_shaderinfo_cache;
  354. // The former container is behind this mutex
  355. std::mutex m_shaderinfo_cache_mutex;
  356. // Queued shader fetches (to be processed by the main thread)
  357. RequestQueue<std::string, u32, u8, u8> m_get_shader_queue;
  358. // Global constant setter factories
  359. std::vector<std::unique_ptr<IShaderConstantSetterFactory>> m_setter_factories;
  360. // Generate shader given the shader name.
  361. ShaderInfo generateShader(const std::string &name,
  362. MaterialType material_type, NodeDrawType drawtype);
  363. };
  364. IWritableShaderSource *createShaderSource()
  365. {
  366. return new ShaderSource();
  367. }
  368. ShaderSource::ShaderSource()
  369. {
  370. m_main_thread = std::this_thread::get_id();
  371. // Add a dummy ShaderInfo as the first index, named ""
  372. m_shaderinfo_cache.emplace_back();
  373. // Add main global constant setter
  374. addShaderConstantSetterFactory(new MainShaderConstantSetterFactory());
  375. }
  376. u32 ShaderSource::getShader(const std::string &name,
  377. MaterialType material_type, NodeDrawType drawtype)
  378. {
  379. /*
  380. Get shader
  381. */
  382. if (std::this_thread::get_id() == m_main_thread) {
  383. return getShaderIdDirect(name, material_type, drawtype);
  384. }
  385. /*errorstream<<"getShader(): Queued: name=\""<<name<<"\""<<std::endl;*/
  386. // We're gonna ask the result to be put into here
  387. static ResultQueue<std::string, u32, u8, u8> result_queue;
  388. // Throw a request in
  389. m_get_shader_queue.add(name, 0, 0, &result_queue);
  390. /* infostream<<"Waiting for shader from main thread, name=\""
  391. <<name<<"\""<<std::endl;*/
  392. while(true) {
  393. GetResult<std::string, u32, u8, u8>
  394. result = result_queue.pop_frontNoEx();
  395. if (result.key == name) {
  396. return result.item;
  397. }
  398. errorstream << "Got shader with invalid name: " << result.key << std::endl;
  399. }
  400. infostream << "getShader(): Failed" << std::endl;
  401. return 0;
  402. }
  403. /*
  404. This method generates all the shaders
  405. */
  406. u32 ShaderSource::getShaderIdDirect(const std::string &name,
  407. MaterialType material_type, NodeDrawType drawtype)
  408. {
  409. //infostream<<"getShaderIdDirect(): name=\""<<name<<"\""<<std::endl;
  410. // Empty name means shader 0
  411. if (name.empty()) {
  412. infostream<<"getShaderIdDirect(): name is empty"<<std::endl;
  413. return 0;
  414. }
  415. // Check if already have such instance
  416. for(u32 i=0; i<m_shaderinfo_cache.size(); i++){
  417. ShaderInfo *info = &m_shaderinfo_cache[i];
  418. if(info->name == name && info->material_type == material_type &&
  419. info->drawtype == drawtype)
  420. return i;
  421. }
  422. /*
  423. Calling only allowed from main thread
  424. */
  425. if (std::this_thread::get_id() != m_main_thread) {
  426. errorstream<<"ShaderSource::getShaderIdDirect() "
  427. "called not from main thread"<<std::endl;
  428. return 0;
  429. }
  430. ShaderInfo info = generateShader(name, material_type, drawtype);
  431. /*
  432. Add shader to caches (add dummy shaders too)
  433. */
  434. MutexAutoLock lock(m_shaderinfo_cache_mutex);
  435. u32 id = m_shaderinfo_cache.size();
  436. m_shaderinfo_cache.push_back(info);
  437. infostream<<"getShaderIdDirect(): "
  438. <<"Returning id="<<id<<" for name \""<<name<<"\""<<std::endl;
  439. return id;
  440. }
  441. ShaderInfo ShaderSource::getShaderInfo(u32 id)
  442. {
  443. MutexAutoLock lock(m_shaderinfo_cache_mutex);
  444. if(id >= m_shaderinfo_cache.size())
  445. return ShaderInfo();
  446. return m_shaderinfo_cache[id];
  447. }
  448. void ShaderSource::processQueue()
  449. {
  450. }
  451. void ShaderSource::insertSourceShader(const std::string &name_of_shader,
  452. const std::string &filename, const std::string &program)
  453. {
  454. /*infostream<<"ShaderSource::insertSourceShader(): "
  455. "name_of_shader=\""<<name_of_shader<<"\", "
  456. "filename=\""<<filename<<"\""<<std::endl;*/
  457. sanity_check(std::this_thread::get_id() == m_main_thread);
  458. m_sourcecache.insert(name_of_shader, filename, program, true);
  459. }
  460. void ShaderSource::rebuildShaders()
  461. {
  462. MutexAutoLock lock(m_shaderinfo_cache_mutex);
  463. /*// Oh well... just clear everything, they'll load sometime.
  464. m_shaderinfo_cache.clear();
  465. m_name_to_id.clear();*/
  466. /*
  467. FIXME: Old shader materials can't be deleted in Irrlicht,
  468. or can they?
  469. (This would be nice to do in the destructor too)
  470. */
  471. // Recreate shaders
  472. for (ShaderInfo &i : m_shaderinfo_cache) {
  473. ShaderInfo *info = &i;
  474. if (!info->name.empty()) {
  475. *info = generateShader(info->name, info->material_type, info->drawtype);
  476. }
  477. }
  478. }
  479. ShaderInfo ShaderSource::generateShader(const std::string &name,
  480. MaterialType material_type, NodeDrawType drawtype)
  481. {
  482. ShaderInfo shaderinfo;
  483. shaderinfo.name = name;
  484. shaderinfo.material_type = material_type;
  485. shaderinfo.drawtype = drawtype;
  486. switch (material_type) {
  487. case TILE_MATERIAL_OPAQUE:
  488. case TILE_MATERIAL_LIQUID_OPAQUE:
  489. case TILE_MATERIAL_WAVING_LIQUID_OPAQUE:
  490. shaderinfo.base_material = video::EMT_SOLID;
  491. break;
  492. case TILE_MATERIAL_ALPHA:
  493. case TILE_MATERIAL_PLAIN_ALPHA:
  494. case TILE_MATERIAL_LIQUID_TRANSPARENT:
  495. case TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT:
  496. shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
  497. break;
  498. case TILE_MATERIAL_BASIC:
  499. case TILE_MATERIAL_PLAIN:
  500. case TILE_MATERIAL_WAVING_LEAVES:
  501. case TILE_MATERIAL_WAVING_PLANTS:
  502. case TILE_MATERIAL_WAVING_LIQUID_BASIC:
  503. shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
  504. break;
  505. }
  506. shaderinfo.material = shaderinfo.base_material;
  507. bool enable_shaders = g_settings->getBool("enable_shaders");
  508. if (!enable_shaders)
  509. return shaderinfo;
  510. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  511. if (!driver->queryFeature(video::EVDF_ARB_GLSL)) {
  512. errorstream << "Shaders are enabled but GLSL is not supported by the driver\n";
  513. return shaderinfo;
  514. }
  515. video::IGPUProgrammingServices *gpu = driver->getGPUProgrammingServices();
  516. // Create shaders header
  517. bool use_gles = false;
  518. #if ENABLE_GLES
  519. use_gles = driver->getDriverType() == video::EDT_OGLES2;
  520. #endif
  521. std::stringstream shaders_header;
  522. shaders_header
  523. << std::noboolalpha
  524. << std::showpoint // for GLSL ES
  525. ;
  526. std::string vertex_header, fragment_header, geometry_header;
  527. if (use_gles) {
  528. shaders_header << R"(
  529. #version 100
  530. )";
  531. vertex_header = R"(
  532. precision mediump float;
  533. uniform highp mat4 mWorldView;
  534. uniform highp mat4 mWorldViewProj;
  535. uniform mediump mat4 mTexture;
  536. uniform mediump mat3 mNormal;
  537. attribute highp vec4 inVertexPosition;
  538. attribute lowp vec4 inVertexColor;
  539. attribute mediump vec4 inTexCoord0;
  540. attribute mediump vec3 inVertexNormal;
  541. attribute mediump vec4 inVertexTangent;
  542. attribute mediump vec4 inVertexBinormal;
  543. )";
  544. fragment_header = R"(
  545. precision mediump float;
  546. )";
  547. } else {
  548. shaders_header << R"(
  549. #version 120
  550. #define lowp
  551. #define mediump
  552. #define highp
  553. )";
  554. vertex_header = R"(
  555. #define mWorldView gl_ModelViewMatrix
  556. #define mWorldViewProj gl_ModelViewProjectionMatrix
  557. #define mTexture (gl_TextureMatrix[0])
  558. #define mNormal gl_NormalMatrix
  559. #define inVertexPosition gl_Vertex
  560. #define inVertexColor gl_Color
  561. #define inTexCoord0 gl_MultiTexCoord0
  562. #define inVertexNormal gl_Normal
  563. #define inVertexTangent gl_MultiTexCoord1
  564. #define inVertexBinormal gl_MultiTexCoord2
  565. )";
  566. }
  567. // Since this is the first time we're using the GL bindings be extra careful.
  568. // This should be removed before 5.6.0 or similar.
  569. if (!GL.GetString) {
  570. errorstream << "OpenGL procedures were not loaded correctly, "
  571. "please open a bug report with details about your platform/OS." << std::endl;
  572. abort();
  573. }
  574. bool use_discard = use_gles;
  575. // For renderers that should use discard instead of GL_ALPHA_TEST
  576. const char *renderer = reinterpret_cast<const char*>(GL.GetString(GL.RENDERER));
  577. if (strstr(renderer, "GC7000"))
  578. use_discard = true;
  579. if (use_discard) {
  580. if (shaderinfo.base_material == video::EMT_TRANSPARENT_ALPHA_CHANNEL)
  581. shaders_header << "#define USE_DISCARD 1\n";
  582. else if (shaderinfo.base_material == video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF)
  583. shaders_header << "#define USE_DISCARD_REF 1\n";
  584. }
  585. #define PROVIDE(constant) shaders_header << "#define " #constant " " << (int)constant << "\n"
  586. PROVIDE(NDT_NORMAL);
  587. PROVIDE(NDT_AIRLIKE);
  588. PROVIDE(NDT_LIQUID);
  589. PROVIDE(NDT_FLOWINGLIQUID);
  590. PROVIDE(NDT_GLASSLIKE);
  591. PROVIDE(NDT_ALLFACES);
  592. PROVIDE(NDT_ALLFACES_OPTIONAL);
  593. PROVIDE(NDT_TORCHLIKE);
  594. PROVIDE(NDT_SIGNLIKE);
  595. PROVIDE(NDT_PLANTLIKE);
  596. PROVIDE(NDT_FENCELIKE);
  597. PROVIDE(NDT_RAILLIKE);
  598. PROVIDE(NDT_NODEBOX);
  599. PROVIDE(NDT_GLASSLIKE_FRAMED);
  600. PROVIDE(NDT_FIRELIKE);
  601. PROVIDE(NDT_GLASSLIKE_FRAMED_OPTIONAL);
  602. PROVIDE(NDT_PLANTLIKE_ROOTED);
  603. PROVIDE(TILE_MATERIAL_BASIC);
  604. PROVIDE(TILE_MATERIAL_ALPHA);
  605. PROVIDE(TILE_MATERIAL_LIQUID_TRANSPARENT);
  606. PROVIDE(TILE_MATERIAL_LIQUID_OPAQUE);
  607. PROVIDE(TILE_MATERIAL_WAVING_LEAVES);
  608. PROVIDE(TILE_MATERIAL_WAVING_PLANTS);
  609. PROVIDE(TILE_MATERIAL_OPAQUE);
  610. PROVIDE(TILE_MATERIAL_WAVING_LIQUID_BASIC);
  611. PROVIDE(TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT);
  612. PROVIDE(TILE_MATERIAL_WAVING_LIQUID_OPAQUE);
  613. PROVIDE(TILE_MATERIAL_PLAIN);
  614. PROVIDE(TILE_MATERIAL_PLAIN_ALPHA);
  615. #undef PROVIDE
  616. shaders_header << "#define MATERIAL_TYPE " << (int)material_type << "\n";
  617. shaders_header << "#define DRAW_TYPE " << (int)drawtype << "\n";
  618. bool enable_waving_water = g_settings->getBool("enable_waving_water");
  619. shaders_header << "#define ENABLE_WAVING_WATER " << enable_waving_water << "\n";
  620. if (enable_waving_water) {
  621. shaders_header << "#define WATER_WAVE_HEIGHT " << g_settings->getFloat("water_wave_height") << "\n";
  622. shaders_header << "#define WATER_WAVE_LENGTH " << g_settings->getFloat("water_wave_length") << "\n";
  623. shaders_header << "#define WATER_WAVE_SPEED " << g_settings->getFloat("water_wave_speed") << "\n";
  624. }
  625. shaders_header << "#define ENABLE_WAVING_LEAVES " << g_settings->getBool("enable_waving_leaves") << "\n";
  626. shaders_header << "#define ENABLE_WAVING_PLANTS " << g_settings->getBool("enable_waving_plants") << "\n";
  627. shaders_header << "#define ENABLE_TONE_MAPPING " << g_settings->getBool("tone_mapping") << "\n";
  628. shaders_header << "#define FOG_START " << core::clamp(g_settings->getFloat("fog_start"), 0.0f, 0.99f) << "\n";
  629. if (g_settings->getBool("enable_dynamic_shadows")) {
  630. shaders_header << "#define ENABLE_DYNAMIC_SHADOWS 1\n";
  631. if (g_settings->getBool("shadow_map_color"))
  632. shaders_header << "#define COLORED_SHADOWS 1\n";
  633. if (g_settings->getBool("shadow_poisson_filter"))
  634. shaders_header << "#define POISSON_FILTER 1\n";
  635. s32 shadow_filter = g_settings->getS32("shadow_filters");
  636. shaders_header << "#define SHADOW_FILTER " << shadow_filter << "\n";
  637. float shadow_soft_radius = g_settings->getFloat("shadow_soft_radius");
  638. if (shadow_soft_radius < 1.0f)
  639. shadow_soft_radius = 1.0f;
  640. shaders_header << "#define SOFTSHADOWRADIUS " << shadow_soft_radius << "\n";
  641. }
  642. shaders_header << "#line 0\n"; // reset the line counter for meaningful diagnostics
  643. std::string common_header = shaders_header.str();
  644. std::string vertex_shader = m_sourcecache.getOrLoad(name, "opengl_vertex.glsl");
  645. std::string fragment_shader = m_sourcecache.getOrLoad(name, "opengl_fragment.glsl");
  646. std::string geometry_shader = m_sourcecache.getOrLoad(name, "opengl_geometry.glsl");
  647. vertex_shader = common_header + vertex_header + vertex_shader;
  648. fragment_shader = common_header + fragment_header + fragment_shader;
  649. const char *geometry_shader_ptr = nullptr; // optional
  650. if (!geometry_shader.empty()) {
  651. geometry_shader = common_header + geometry_header + geometry_shader;
  652. geometry_shader_ptr = geometry_shader.c_str();
  653. }
  654. irr_ptr<ShaderCallback> cb{new ShaderCallback(m_setter_factories)};
  655. infostream<<"Compiling high level shaders for "<<name<<std::endl;
  656. s32 shadermat = gpu->addHighLevelShaderMaterial(
  657. vertex_shader.c_str(), nullptr, video::EVST_VS_1_1,
  658. fragment_shader.c_str(), nullptr, video::EPST_PS_1_1,
  659. geometry_shader_ptr, nullptr, video::EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLES, 0,
  660. cb.get(), shaderinfo.base_material, 1);
  661. if (shadermat == -1) {
  662. errorstream<<"generate_shader(): "
  663. "failed to generate \""<<name<<"\", "
  664. "addHighLevelShaderMaterial failed."
  665. <<std::endl;
  666. dumpShaderProgram(warningstream, "Vertex", vertex_shader);
  667. dumpShaderProgram(warningstream, "Fragment", fragment_shader);
  668. dumpShaderProgram(warningstream, "Geometry", geometry_shader);
  669. return shaderinfo;
  670. }
  671. // Apply the newly created material type
  672. shaderinfo.material = (video::E_MATERIAL_TYPE) shadermat;
  673. return shaderinfo;
  674. }
  675. void dumpShaderProgram(std::ostream &output_stream,
  676. const std::string &program_type, const std::string &program)
  677. {
  678. output_stream << program_type << " shader program:" << std::endl <<
  679. "----------------------------------" << std::endl;
  680. size_t pos = 0;
  681. size_t prev = 0;
  682. s16 line = 1;
  683. while ((pos = program.find('\n', prev)) != std::string::npos) {
  684. output_stream << line++ << ": "<< program.substr(prev, pos - prev) <<
  685. std::endl;
  686. prev = pos + 1;
  687. }
  688. output_stream << line << ": " << program.substr(prev) << std::endl <<
  689. "End of " << program_type << " shader program." << std::endl <<
  690. " " << std::endl;
  691. }