mapblock_mesh.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "mapblock_mesh.h"
  17. #include "client.h"
  18. #include "mapblock.h"
  19. #include "map.h"
  20. #include "profiler.h"
  21. #include "shader.h"
  22. #include "mesh.h"
  23. #include "minimap.h"
  24. #include "content_mapblock.h"
  25. #include "util/directiontables.h"
  26. #include "client/meshgen/collector.h"
  27. #include "client/renderingengine.h"
  28. #include <array>
  29. #include <algorithm>
  30. /*
  31. MeshMakeData
  32. */
  33. MeshMakeData::MeshMakeData(Client *client, bool use_shaders):
  34. m_client(client),
  35. m_use_shaders(use_shaders)
  36. {}
  37. void MeshMakeData::fillBlockDataBegin(const v3s16 &blockpos)
  38. {
  39. m_blockpos = blockpos;
  40. v3s16 blockpos_nodes = m_blockpos*MAP_BLOCKSIZE;
  41. m_vmanip.clear();
  42. VoxelArea voxel_area(blockpos_nodes - v3s16(1,1,1) * MAP_BLOCKSIZE,
  43. blockpos_nodes + v3s16(1,1,1) * MAP_BLOCKSIZE*2-v3s16(1,1,1));
  44. m_vmanip.addArea(voxel_area);
  45. }
  46. void MeshMakeData::fillBlockData(const v3s16 &block_offset, MapNode *data)
  47. {
  48. v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
  49. VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1));
  50. v3s16 bp = m_blockpos + block_offset;
  51. v3s16 blockpos_nodes = bp * MAP_BLOCKSIZE;
  52. m_vmanip.copyFrom(data, data_area, v3s16(0,0,0), blockpos_nodes, data_size);
  53. }
  54. void MeshMakeData::fill(MapBlock *block)
  55. {
  56. fillBlockDataBegin(block->getPos());
  57. fillBlockData(v3s16(0,0,0), block->getData());
  58. // Get map for reading neighbor blocks
  59. Map *map = block->getParent();
  60. for (const v3s16 &dir : g_26dirs) {
  61. v3s16 bp = m_blockpos + dir;
  62. MapBlock *b = map->getBlockNoCreateNoEx(bp);
  63. if(b)
  64. fillBlockData(dir, b->getData());
  65. }
  66. }
  67. void MeshMakeData::setCrack(int crack_level, v3s16 crack_pos)
  68. {
  69. if (crack_level >= 0)
  70. m_crack_pos_relative = crack_pos - m_blockpos*MAP_BLOCKSIZE;
  71. }
  72. void MeshMakeData::setSmoothLighting(bool smooth_lighting)
  73. {
  74. m_smooth_lighting = smooth_lighting;
  75. }
  76. /*
  77. Light and vertex color functions
  78. */
  79. /*
  80. Calculate non-smooth lighting at interior of node.
  81. Single light bank.
  82. */
  83. static u8 getInteriorLight(enum LightBank bank, MapNode n, s32 increment,
  84. const NodeDefManager *ndef)
  85. {
  86. u8 light = n.getLight(bank, ndef);
  87. if (light > 0)
  88. light = rangelim(light + increment, 0, LIGHT_SUN);
  89. return decode_light(light);
  90. }
  91. /*
  92. Calculate non-smooth lighting at interior of node.
  93. Both light banks.
  94. */
  95. u16 getInteriorLight(MapNode n, s32 increment, const NodeDefManager *ndef)
  96. {
  97. u16 day = getInteriorLight(LIGHTBANK_DAY, n, increment, ndef);
  98. u16 night = getInteriorLight(LIGHTBANK_NIGHT, n, increment, ndef);
  99. return day | (night << 8);
  100. }
  101. /*
  102. Calculate non-smooth lighting at face of node.
  103. Single light bank.
  104. */
  105. static u8 getFaceLight(enum LightBank bank, MapNode n, MapNode n2,
  106. v3s16 face_dir, const NodeDefManager *ndef)
  107. {
  108. u8 light;
  109. u8 l1 = n.getLight(bank, ndef);
  110. u8 l2 = n2.getLight(bank, ndef);
  111. if(l1 > l2)
  112. light = l1;
  113. else
  114. light = l2;
  115. // Boost light level for light sources
  116. u8 light_source = MYMAX(ndef->get(n).light_source,
  117. ndef->get(n2).light_source);
  118. if(light_source > light)
  119. light = light_source;
  120. return decode_light(light);
  121. }
  122. /*
  123. Calculate non-smooth lighting at face of node.
  124. Both light banks.
  125. */
  126. u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir,
  127. const NodeDefManager *ndef)
  128. {
  129. u16 day = getFaceLight(LIGHTBANK_DAY, n, n2, face_dir, ndef);
  130. u16 night = getFaceLight(LIGHTBANK_NIGHT, n, n2, face_dir, ndef);
  131. return day | (night << 8);
  132. }
  133. /*
  134. Calculate smooth lighting at the XYZ- corner of p.
  135. Both light banks
  136. */
  137. static u16 getSmoothLightCombined(const v3s16 &p,
  138. const std::array<v3s16,8> &dirs, MeshMakeData *data)
  139. {
  140. const NodeDefManager *ndef = data->m_client->ndef();
  141. u16 ambient_occlusion = 0;
  142. u16 light_count = 0;
  143. u8 light_source_max = 0;
  144. u16 light_day = 0;
  145. u16 light_night = 0;
  146. bool direct_sunlight = false;
  147. auto add_node = [&] (u8 i, bool obstructed = false) -> bool {
  148. if (obstructed) {
  149. ambient_occlusion++;
  150. return false;
  151. }
  152. MapNode n = data->m_vmanip.getNodeNoExNoEmerge(p + dirs[i]);
  153. if (n.getContent() == CONTENT_IGNORE)
  154. return true;
  155. const ContentFeatures &f = ndef->get(n);
  156. if (f.light_source > light_source_max)
  157. light_source_max = f.light_source;
  158. // Check f.solidness because fast-style leaves look better this way
  159. if (f.param_type == CPT_LIGHT && f.solidness != 2) {
  160. u8 light_level_day = n.getLightNoChecks(LIGHTBANK_DAY, &f);
  161. u8 light_level_night = n.getLightNoChecks(LIGHTBANK_NIGHT, &f);
  162. if (light_level_day == LIGHT_SUN)
  163. direct_sunlight = true;
  164. light_day += decode_light(light_level_day);
  165. light_night += decode_light(light_level_night);
  166. light_count++;
  167. } else {
  168. ambient_occlusion++;
  169. }
  170. return f.light_propagates;
  171. };
  172. bool obstructed[4] = { true, true, true, true };
  173. add_node(0);
  174. bool opaque1 = !add_node(1);
  175. bool opaque2 = !add_node(2);
  176. bool opaque3 = !add_node(3);
  177. obstructed[0] = opaque1 && opaque2;
  178. obstructed[1] = opaque1 && opaque3;
  179. obstructed[2] = opaque2 && opaque3;
  180. for (u8 k = 0; k < 3; ++k)
  181. if (add_node(k + 4, obstructed[k]))
  182. obstructed[3] = false;
  183. if (add_node(7, obstructed[3])) { // wrap light around nodes
  184. ambient_occlusion -= 3;
  185. for (u8 k = 0; k < 3; ++k)
  186. add_node(k + 4, !obstructed[k]);
  187. }
  188. if (light_count == 0) {
  189. light_day = light_night = 0;
  190. } else {
  191. light_day /= light_count;
  192. light_night /= light_count;
  193. }
  194. // boost direct sunlight, if any
  195. if (direct_sunlight)
  196. light_day = 0xFF;
  197. // Boost brightness around light sources
  198. bool skip_ambient_occlusion_day = false;
  199. if (decode_light(light_source_max) >= light_day) {
  200. light_day = decode_light(light_source_max);
  201. skip_ambient_occlusion_day = true;
  202. }
  203. bool skip_ambient_occlusion_night = false;
  204. if(decode_light(light_source_max) >= light_night) {
  205. light_night = decode_light(light_source_max);
  206. skip_ambient_occlusion_night = true;
  207. }
  208. if (ambient_occlusion > 4) {
  209. static thread_local const float ao_gamma = rangelim(
  210. g_settings->getFloat("ambient_occlusion_gamma"), 0.25, 4.0);
  211. // Table of gamma space multiply factors.
  212. static thread_local const float light_amount[3] = {
  213. powf(0.75, 1.0 / ao_gamma),
  214. powf(0.5, 1.0 / ao_gamma),
  215. powf(0.25, 1.0 / ao_gamma)
  216. };
  217. //calculate table index for gamma space multiplier
  218. ambient_occlusion -= 5;
  219. if (!skip_ambient_occlusion_day)
  220. light_day = rangelim(core::round32(
  221. light_day * light_amount[ambient_occlusion]), 0, 255);
  222. if (!skip_ambient_occlusion_night)
  223. light_night = rangelim(core::round32(
  224. light_night * light_amount[ambient_occlusion]), 0, 255);
  225. }
  226. return light_day | (light_night << 8);
  227. }
  228. /*
  229. Calculate smooth lighting at the given corner of p.
  230. Both light banks.
  231. Node at p is solid, and thus the lighting is face-dependent.
  232. */
  233. u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner, MeshMakeData *data)
  234. {
  235. return getSmoothLightTransparent(p + face_dir, corner - 2 * face_dir, data);
  236. }
  237. /*
  238. Calculate smooth lighting at the given corner of p.
  239. Both light banks.
  240. Node at p is not solid, and the lighting is not face-dependent.
  241. */
  242. u16 getSmoothLightTransparent(const v3s16 &p, const v3s16 &corner, MeshMakeData *data)
  243. {
  244. const std::array<v3s16,8> dirs = {{
  245. // Always shine light
  246. v3s16(0,0,0),
  247. v3s16(corner.X,0,0),
  248. v3s16(0,corner.Y,0),
  249. v3s16(0,0,corner.Z),
  250. // Can be obstructed
  251. v3s16(corner.X,corner.Y,0),
  252. v3s16(corner.X,0,corner.Z),
  253. v3s16(0,corner.Y,corner.Z),
  254. v3s16(corner.X,corner.Y,corner.Z)
  255. }};
  256. return getSmoothLightCombined(p, dirs, data);
  257. }
  258. void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio){
  259. f32 rg = daynight_ratio / 1000.0f - 0.04f;
  260. f32 b = (0.98f * daynight_ratio) / 1000.0f + 0.078f;
  261. sunlight->r = rg;
  262. sunlight->g = rg;
  263. sunlight->b = b;
  264. }
  265. void final_color_blend(video::SColor *result,
  266. u16 light, u32 daynight_ratio)
  267. {
  268. video::SColorf dayLight;
  269. get_sunlight_color(&dayLight, daynight_ratio);
  270. final_color_blend(result,
  271. encode_light(light, 0), dayLight);
  272. }
  273. void final_color_blend(video::SColor *result,
  274. const video::SColor &data, const video::SColorf &dayLight)
  275. {
  276. static const video::SColorf artificialColor(1.04f, 1.04f, 1.04f);
  277. video::SColorf c(data);
  278. f32 n = 1 - c.a;
  279. f32 r = c.r * (c.a * dayLight.r + n * artificialColor.r) * 2.0f;
  280. f32 g = c.g * (c.a * dayLight.g + n * artificialColor.g) * 2.0f;
  281. f32 b = c.b * (c.a * dayLight.b + n * artificialColor.b) * 2.0f;
  282. // Emphase blue a bit in darker places
  283. // Each entry of this array represents a range of 8 blue levels
  284. static const u8 emphase_blue_when_dark[32] = {
  285. 1, 4, 6, 6, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0,
  286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  287. };
  288. b += emphase_blue_when_dark[irr::core::clamp((s32) ((r + g + b) / 3 * 255),
  289. 0, 255) / 8] / 255.0f;
  290. result->setRed(core::clamp((s32) (r * 255.0f), 0, 255));
  291. result->setGreen(core::clamp((s32) (g * 255.0f), 0, 255));
  292. result->setBlue(core::clamp((s32) (b * 255.0f), 0, 255));
  293. }
  294. /*
  295. Mesh generation helpers
  296. */
  297. // This table is moved outside getNodeVertexDirs to avoid the compiler using
  298. // a mutex to initialize this table at runtime right in the hot path.
  299. // For details search the internet for "cxa_guard_acquire".
  300. static const v3s16 vertex_dirs_table[] = {
  301. // ( 1, 0, 0)
  302. v3s16( 1,-1, 1), v3s16( 1,-1,-1),
  303. v3s16( 1, 1,-1), v3s16( 1, 1, 1),
  304. // ( 0, 1, 0)
  305. v3s16( 1, 1,-1), v3s16(-1, 1,-1),
  306. v3s16(-1, 1, 1), v3s16( 1, 1, 1),
  307. // ( 0, 0, 1)
  308. v3s16(-1,-1, 1), v3s16( 1,-1, 1),
  309. v3s16( 1, 1, 1), v3s16(-1, 1, 1),
  310. // invalid
  311. v3s16(), v3s16(), v3s16(), v3s16(),
  312. // ( 0, 0,-1)
  313. v3s16( 1,-1,-1), v3s16(-1,-1,-1),
  314. v3s16(-1, 1,-1), v3s16( 1, 1,-1),
  315. // ( 0,-1, 0)
  316. v3s16( 1,-1, 1), v3s16(-1,-1, 1),
  317. v3s16(-1,-1,-1), v3s16( 1,-1,-1),
  318. // (-1, 0, 0)
  319. v3s16(-1,-1,-1), v3s16(-1,-1, 1),
  320. v3s16(-1, 1, 1), v3s16(-1, 1,-1)
  321. };
  322. /*
  323. vertex_dirs: v3s16[4]
  324. */
  325. static void getNodeVertexDirs(const v3s16 &dir, v3s16 *vertex_dirs)
  326. {
  327. /*
  328. If looked from outside the node towards the face, the corners are:
  329. 0: bottom-right
  330. 1: bottom-left
  331. 2: top-left
  332. 3: top-right
  333. */
  334. // Direction must be (1,0,0), (-1,0,0), (0,1,0), (0,-1,0),
  335. // (0,0,1), (0,0,-1)
  336. assert(dir.X * dir.X + dir.Y * dir.Y + dir.Z * dir.Z == 1);
  337. // Convert direction to single integer for table lookup
  338. u8 idx = (dir.X + 2 * dir.Y + 3 * dir.Z) & 7;
  339. idx = (idx - 1) * 4;
  340. #if defined(__GNUC__) && !defined(__clang__)
  341. #pragma GCC diagnostic push
  342. #if __GNUC__ > 7
  343. #pragma GCC diagnostic ignored "-Wclass-memaccess"
  344. #endif
  345. #endif
  346. memcpy(vertex_dirs, &vertex_dirs_table[idx], 4 * sizeof(v3s16));
  347. #if defined(__GNUC__) && !defined(__clang__)
  348. #pragma GCC diagnostic pop
  349. #endif
  350. }
  351. static void getNodeTextureCoords(v3f base, const v3f &scale, const v3s16 &dir, float *u, float *v)
  352. {
  353. if (dir.X > 0 || dir.Y != 0 || dir.Z < 0)
  354. base -= scale;
  355. if (dir == v3s16(0,0,1)) {
  356. *u = -base.X;
  357. *v = -base.Y;
  358. } else if (dir == v3s16(0,0,-1)) {
  359. *u = base.X + 1;
  360. *v = -base.Y - 1;
  361. } else if (dir == v3s16(1,0,0)) {
  362. *u = base.Z + 1;
  363. *v = -base.Y - 1;
  364. } else if (dir == v3s16(-1,0,0)) {
  365. *u = -base.Z;
  366. *v = -base.Y;
  367. } else if (dir == v3s16(0,1,0)) {
  368. *u = base.X + 1;
  369. *v = -base.Z - 1;
  370. } else if (dir == v3s16(0,-1,0)) {
  371. *u = base.X + 1;
  372. *v = base.Z + 1;
  373. }
  374. }
  375. struct FastFace
  376. {
  377. TileSpec tile;
  378. video::S3DVertex vertices[4]; // Precalculated vertices
  379. /*!
  380. * The face is divided into two triangles. If this is true,
  381. * vertices 0 and 2 are connected, othervise vertices 1 and 3
  382. * are connected.
  383. */
  384. bool vertex_0_2_connected;
  385. };
  386. static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li3,
  387. const v3f &tp, const v3f &p, const v3s16 &dir, const v3f &scale, std::vector<FastFace> &dest)
  388. {
  389. // Position is at the center of the cube.
  390. v3f pos = p * BS;
  391. float x0 = 0.0f;
  392. float y0 = 0.0f;
  393. float w = 1.0f;
  394. float h = 1.0f;
  395. v3f vertex_pos[4];
  396. v3s16 vertex_dirs[4];
  397. getNodeVertexDirs(dir, vertex_dirs);
  398. if (tile.world_aligned)
  399. getNodeTextureCoords(tp, scale, dir, &x0, &y0);
  400. v3s16 t;
  401. u16 t1;
  402. switch (tile.rotation) {
  403. case 0:
  404. break;
  405. case 1: //R90
  406. t = vertex_dirs[0];
  407. vertex_dirs[0] = vertex_dirs[3];
  408. vertex_dirs[3] = vertex_dirs[2];
  409. vertex_dirs[2] = vertex_dirs[1];
  410. vertex_dirs[1] = t;
  411. t1 = li0;
  412. li0 = li3;
  413. li3 = li2;
  414. li2 = li1;
  415. li1 = t1;
  416. break;
  417. case 2: //R180
  418. t = vertex_dirs[0];
  419. vertex_dirs[0] = vertex_dirs[2];
  420. vertex_dirs[2] = t;
  421. t = vertex_dirs[1];
  422. vertex_dirs[1] = vertex_dirs[3];
  423. vertex_dirs[3] = t;
  424. t1 = li0;
  425. li0 = li2;
  426. li2 = t1;
  427. t1 = li1;
  428. li1 = li3;
  429. li3 = t1;
  430. break;
  431. case 3: //R270
  432. t = vertex_dirs[0];
  433. vertex_dirs[0] = vertex_dirs[1];
  434. vertex_dirs[1] = vertex_dirs[2];
  435. vertex_dirs[2] = vertex_dirs[3];
  436. vertex_dirs[3] = t;
  437. t1 = li0;
  438. li0 = li1;
  439. li1 = li2;
  440. li2 = li3;
  441. li3 = t1;
  442. break;
  443. case 4: //FXR90
  444. t = vertex_dirs[0];
  445. vertex_dirs[0] = vertex_dirs[3];
  446. vertex_dirs[3] = vertex_dirs[2];
  447. vertex_dirs[2] = vertex_dirs[1];
  448. vertex_dirs[1] = t;
  449. t1 = li0;
  450. li0 = li3;
  451. li3 = li2;
  452. li2 = li1;
  453. li1 = t1;
  454. y0 += h;
  455. h *= -1;
  456. break;
  457. case 5: //FXR270
  458. t = vertex_dirs[0];
  459. vertex_dirs[0] = vertex_dirs[1];
  460. vertex_dirs[1] = vertex_dirs[2];
  461. vertex_dirs[2] = vertex_dirs[3];
  462. vertex_dirs[3] = t;
  463. t1 = li0;
  464. li0 = li1;
  465. li1 = li2;
  466. li2 = li3;
  467. li3 = t1;
  468. y0 += h;
  469. h *= -1;
  470. break;
  471. case 6: //FYR90
  472. t = vertex_dirs[0];
  473. vertex_dirs[0] = vertex_dirs[3];
  474. vertex_dirs[3] = vertex_dirs[2];
  475. vertex_dirs[2] = vertex_dirs[1];
  476. vertex_dirs[1] = t;
  477. t1 = li0;
  478. li0 = li3;
  479. li3 = li2;
  480. li2 = li1;
  481. li1 = t1;
  482. x0 += w;
  483. w *= -1;
  484. break;
  485. case 7: //FYR270
  486. t = vertex_dirs[0];
  487. vertex_dirs[0] = vertex_dirs[1];
  488. vertex_dirs[1] = vertex_dirs[2];
  489. vertex_dirs[2] = vertex_dirs[3];
  490. vertex_dirs[3] = t;
  491. t1 = li0;
  492. li0 = li1;
  493. li1 = li2;
  494. li2 = li3;
  495. li3 = t1;
  496. x0 += w;
  497. w *= -1;
  498. break;
  499. case 8: //FX
  500. y0 += h;
  501. h *= -1;
  502. break;
  503. case 9: //FY
  504. x0 += w;
  505. w *= -1;
  506. break;
  507. default:
  508. break;
  509. }
  510. for (u16 i = 0; i < 4; i++) {
  511. vertex_pos[i] = v3f(
  512. BS / 2 * vertex_dirs[i].X,
  513. BS / 2 * vertex_dirs[i].Y,
  514. BS / 2 * vertex_dirs[i].Z
  515. );
  516. }
  517. for (v3f &vpos : vertex_pos) {
  518. vpos.X *= scale.X;
  519. vpos.Y *= scale.Y;
  520. vpos.Z *= scale.Z;
  521. vpos += pos;
  522. }
  523. f32 abs_scale = 1.0f;
  524. if (scale.X < 0.999f || scale.X > 1.001f) abs_scale = scale.X;
  525. else if (scale.Y < 0.999f || scale.Y > 1.001f) abs_scale = scale.Y;
  526. else if (scale.Z < 0.999f || scale.Z > 1.001f) abs_scale = scale.Z;
  527. v3f normal(dir.X, dir.Y, dir.Z);
  528. u16 li[4] = { li0, li1, li2, li3 };
  529. u16 day[4];
  530. u16 night[4];
  531. for (u8 i = 0; i < 4; i++) {
  532. day[i] = li[i] >> 8;
  533. night[i] = li[i] & 0xFF;
  534. }
  535. bool vertex_0_2_connected = abs(day[0] - day[2]) + abs(night[0] - night[2])
  536. < abs(day[1] - day[3]) + abs(night[1] - night[3]);
  537. v2f32 f[4] = {
  538. core::vector2d<f32>(x0 + w * abs_scale, y0 + h),
  539. core::vector2d<f32>(x0, y0 + h),
  540. core::vector2d<f32>(x0, y0),
  541. core::vector2d<f32>(x0 + w * abs_scale, y0) };
  542. // equivalent to dest.push_back(FastFace()) but faster
  543. dest.emplace_back();
  544. FastFace& face = *dest.rbegin();
  545. for (u8 i = 0; i < 4; i++) {
  546. video::SColor c = encode_light(li[i], tile.emissive_light);
  547. if (!tile.emissive_light)
  548. applyFacesShading(c, normal);
  549. face.vertices[i] = video::S3DVertex(vertex_pos[i], normal, c, f[i]);
  550. }
  551. /*
  552. Revert triangles for nicer looking gradient if the
  553. brightness of vertices 1 and 3 differ less than
  554. the brightness of vertices 0 and 2.
  555. */
  556. face.vertex_0_2_connected = vertex_0_2_connected;
  557. face.tile = tile;
  558. }
  559. /*
  560. Nodes make a face if contents differ and solidness differs.
  561. Return value:
  562. 0: No face
  563. 1: Face uses m1's content
  564. 2: Face uses m2's content
  565. equivalent: Whether the blocks share the same face (eg. water and glass)
  566. TODO: Add 3: Both faces drawn with backface culling, remove equivalent
  567. */
  568. static u8 face_contents(content_t m1, content_t m2, bool *equivalent,
  569. const NodeDefManager *ndef)
  570. {
  571. *equivalent = false;
  572. if (m1 == m2 || m1 == CONTENT_IGNORE || m2 == CONTENT_IGNORE)
  573. return 0;
  574. const ContentFeatures &f1 = ndef->get(m1);
  575. const ContentFeatures &f2 = ndef->get(m2);
  576. // Contents don't differ for different forms of same liquid
  577. if (f1.sameLiquid(f2))
  578. return 0;
  579. u8 c1 = f1.solidness;
  580. u8 c2 = f2.solidness;
  581. if (c1 == c2)
  582. return 0;
  583. if (c1 == 0)
  584. c1 = f1.visual_solidness;
  585. else if (c2 == 0)
  586. c2 = f2.visual_solidness;
  587. if (c1 == c2) {
  588. *equivalent = true;
  589. // If same solidness, liquid takes precense
  590. if (f1.isLiquid())
  591. return 1;
  592. if (f2.isLiquid())
  593. return 2;
  594. }
  595. if (c1 > c2)
  596. return 1;
  597. return 2;
  598. }
  599. /*
  600. Gets nth node tile (0 <= n <= 5).
  601. */
  602. void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, TileSpec &tile)
  603. {
  604. const NodeDefManager *ndef = data->m_client->ndef();
  605. const ContentFeatures &f = ndef->get(mn);
  606. tile = f.tiles[tileindex];
  607. bool has_crack = p == data->m_crack_pos_relative;
  608. for (TileLayer &layer : tile.layers) {
  609. if (layer.texture_id == 0)
  610. continue;
  611. if (!layer.has_color)
  612. mn.getColor(f, &(layer.color));
  613. // Apply temporary crack
  614. if (has_crack)
  615. layer.material_flags |= MATERIAL_FLAG_CRACK;
  616. }
  617. }
  618. /*
  619. Gets node tile given a face direction.
  620. */
  621. void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data, TileSpec &tile)
  622. {
  623. const NodeDefManager *ndef = data->m_client->ndef();
  624. // Direction must be (1,0,0), (-1,0,0), (0,1,0), (0,-1,0),
  625. // (0,0,1), (0,0,-1) or (0,0,0)
  626. assert(dir.X * dir.X + dir.Y * dir.Y + dir.Z * dir.Z <= 1);
  627. // Convert direction to single integer for table lookup
  628. // 0 = (0,0,0)
  629. // 1 = (1,0,0)
  630. // 2 = (0,1,0)
  631. // 3 = (0,0,1)
  632. // 4 = invalid, treat as (0,0,0)
  633. // 5 = (0,0,-1)
  634. // 6 = (0,-1,0)
  635. // 7 = (-1,0,0)
  636. u8 dir_i = ((dir.X + 2 * dir.Y + 3 * dir.Z) & 7) * 2;
  637. // Get rotation for things like chests
  638. u8 facedir = mn.getFaceDir(ndef, true);
  639. static const u16 dir_to_tile[24 * 16] =
  640. {
  641. // 0 +X +Y +Z -Z -Y -X -> value=tile,rotation
  642. 0,0, 2,0 , 0,0 , 4,0 , 0,0, 5,0 , 1,0 , 3,0 , // rotate around y+ 0 - 3
  643. 0,0, 4,0 , 0,3 , 3,0 , 0,0, 2,0 , 1,1 , 5,0 ,
  644. 0,0, 3,0 , 0,2 , 5,0 , 0,0, 4,0 , 1,2 , 2,0 ,
  645. 0,0, 5,0 , 0,1 , 2,0 , 0,0, 3,0 , 1,3 , 4,0 ,
  646. 0,0, 2,3 , 5,0 , 0,2 , 0,0, 1,0 , 4,2 , 3,1 , // rotate around z+ 4 - 7
  647. 0,0, 4,3 , 2,0 , 0,1 , 0,0, 1,1 , 3,2 , 5,1 ,
  648. 0,0, 3,3 , 4,0 , 0,0 , 0,0, 1,2 , 5,2 , 2,1 ,
  649. 0,0, 5,3 , 3,0 , 0,3 , 0,0, 1,3 , 2,2 , 4,1 ,
  650. 0,0, 2,1 , 4,2 , 1,2 , 0,0, 0,0 , 5,0 , 3,3 , // rotate around z- 8 - 11
  651. 0,0, 4,1 , 3,2 , 1,3 , 0,0, 0,3 , 2,0 , 5,3 ,
  652. 0,0, 3,1 , 5,2 , 1,0 , 0,0, 0,2 , 4,0 , 2,3 ,
  653. 0,0, 5,1 , 2,2 , 1,1 , 0,0, 0,1 , 3,0 , 4,3 ,
  654. 0,0, 0,3 , 3,3 , 4,1 , 0,0, 5,3 , 2,3 , 1,3 , // rotate around x+ 12 - 15
  655. 0,0, 0,2 , 5,3 , 3,1 , 0,0, 2,3 , 4,3 , 1,0 ,
  656. 0,0, 0,1 , 2,3 , 5,1 , 0,0, 4,3 , 3,3 , 1,1 ,
  657. 0,0, 0,0 , 4,3 , 2,1 , 0,0, 3,3 , 5,3 , 1,2 ,
  658. 0,0, 1,1 , 2,1 , 4,3 , 0,0, 5,1 , 3,1 , 0,1 , // rotate around x- 16 - 19
  659. 0,0, 1,2 , 4,1 , 3,3 , 0,0, 2,1 , 5,1 , 0,0 ,
  660. 0,0, 1,3 , 3,1 , 5,3 , 0,0, 4,1 , 2,1 , 0,3 ,
  661. 0,0, 1,0 , 5,1 , 2,3 , 0,0, 3,1 , 4,1 , 0,2 ,
  662. 0,0, 3,2 , 1,2 , 4,2 , 0,0, 5,2 , 0,2 , 2,2 , // rotate around y- 20 - 23
  663. 0,0, 5,2 , 1,3 , 3,2 , 0,0, 2,2 , 0,1 , 4,2 ,
  664. 0,0, 2,2 , 1,0 , 5,2 , 0,0, 4,2 , 0,0 , 3,2 ,
  665. 0,0, 4,2 , 1,1 , 2,2 , 0,0, 3,2 , 0,3 , 5,2
  666. };
  667. u16 tile_index = facedir * 16 + dir_i;
  668. getNodeTileN(mn, p, dir_to_tile[tile_index], data, tile);
  669. tile.rotation = tile.world_aligned ? 0 : dir_to_tile[tile_index + 1];
  670. }
  671. static void getTileInfo(
  672. // Input:
  673. MeshMakeData *data,
  674. const v3s16 &p,
  675. const v3s16 &face_dir,
  676. // Output:
  677. bool &makes_face,
  678. v3s16 &p_corrected,
  679. v3s16 &face_dir_corrected,
  680. u16 *lights,
  681. u8 &waving,
  682. TileSpec &tile
  683. )
  684. {
  685. VoxelManipulator &vmanip = data->m_vmanip;
  686. const NodeDefManager *ndef = data->m_client->ndef();
  687. v3s16 blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE;
  688. const MapNode &n0 = vmanip.getNodeRefUnsafe(blockpos_nodes + p);
  689. // Don't even try to get n1 if n0 is already CONTENT_IGNORE
  690. if (n0.getContent() == CONTENT_IGNORE) {
  691. makes_face = false;
  692. return;
  693. }
  694. const MapNode &n1 = vmanip.getNodeRefUnsafeCheckFlags(blockpos_nodes + p + face_dir);
  695. if (n1.getContent() == CONTENT_IGNORE) {
  696. makes_face = false;
  697. return;
  698. }
  699. // This is hackish
  700. bool equivalent = false;
  701. u8 mf = face_contents(n0.getContent(), n1.getContent(),
  702. &equivalent, ndef);
  703. if (mf == 0) {
  704. makes_face = false;
  705. return;
  706. }
  707. makes_face = true;
  708. MapNode n = n0;
  709. if (mf == 1) {
  710. p_corrected = p;
  711. face_dir_corrected = face_dir;
  712. } else {
  713. n = n1;
  714. p_corrected = p + face_dir;
  715. face_dir_corrected = -face_dir;
  716. }
  717. getNodeTile(n, p_corrected, face_dir_corrected, data, tile);
  718. const ContentFeatures &f = ndef->get(n);
  719. waving = f.waving;
  720. tile.emissive_light = f.light_source;
  721. // eg. water and glass
  722. if (equivalent) {
  723. for (TileLayer &layer : tile.layers)
  724. layer.material_flags |= MATERIAL_FLAG_BACKFACE_CULLING;
  725. }
  726. if (!data->m_smooth_lighting) {
  727. lights[0] = lights[1] = lights[2] = lights[3] =
  728. getFaceLight(n0, n1, face_dir, ndef);
  729. } else {
  730. v3s16 vertex_dirs[4];
  731. getNodeVertexDirs(face_dir_corrected, vertex_dirs);
  732. v3s16 light_p = blockpos_nodes + p_corrected;
  733. for (u16 i = 0; i < 4; i++)
  734. lights[i] = getSmoothLightSolid(light_p, face_dir_corrected, vertex_dirs[i], data);
  735. }
  736. }
  737. /*
  738. startpos:
  739. translate_dir: unit vector with only one of x, y or z
  740. face_dir: unit vector with only one of x, y or z
  741. */
  742. static void updateFastFaceRow(
  743. MeshMakeData *data,
  744. const v3s16 &&startpos,
  745. v3s16 translate_dir,
  746. const v3f &&translate_dir_f,
  747. const v3s16 &&face_dir,
  748. std::vector<FastFace> &dest)
  749. {
  750. static thread_local const bool waving_liquids =
  751. g_settings->getBool("enable_shaders") &&
  752. g_settings->getBool("enable_waving_water");
  753. static thread_local const bool force_not_tiling =
  754. g_settings->getBool("enable_dynamic_shadows");
  755. v3s16 p = startpos;
  756. u16 continuous_tiles_count = 1;
  757. bool makes_face = false;
  758. v3s16 p_corrected;
  759. v3s16 face_dir_corrected;
  760. u16 lights[4] = {0, 0, 0, 0};
  761. u8 waving = 0;
  762. TileSpec tile;
  763. // Get info of first tile
  764. getTileInfo(data, p, face_dir,
  765. makes_face, p_corrected, face_dir_corrected,
  766. lights, waving, tile);
  767. // Unroll this variable which has a significant build cost
  768. TileSpec next_tile;
  769. for (u16 j = 0; j < MAP_BLOCKSIZE; j++) {
  770. // If tiling can be done, this is set to false in the next step
  771. bool next_is_different = true;
  772. bool next_makes_face = false;
  773. v3s16 next_p_corrected;
  774. v3s16 next_face_dir_corrected;
  775. u16 next_lights[4] = {0, 0, 0, 0};
  776. // If at last position, there is nothing to compare to and
  777. // the face must be drawn anyway
  778. if (j != MAP_BLOCKSIZE - 1) {
  779. p += translate_dir;
  780. getTileInfo(data, p, face_dir,
  781. next_makes_face, next_p_corrected,
  782. next_face_dir_corrected, next_lights,
  783. waving,
  784. next_tile);
  785. if (!force_not_tiling
  786. && next_makes_face == makes_face
  787. && next_p_corrected == p_corrected + translate_dir
  788. && next_face_dir_corrected == face_dir_corrected
  789. && memcmp(next_lights, lights, sizeof(lights)) == 0
  790. // Don't apply fast faces to waving water.
  791. && (waving != 3 || !waving_liquids)
  792. && next_tile.isTileable(tile)) {
  793. next_is_different = false;
  794. continuous_tiles_count++;
  795. }
  796. }
  797. if (next_is_different) {
  798. /*
  799. Create a face if there should be one
  800. */
  801. if (makes_face) {
  802. // Floating point conversion of the position vector
  803. v3f pf(p_corrected.X, p_corrected.Y, p_corrected.Z);
  804. // Center point of face (kind of)
  805. v3f sp = pf - ((f32)continuous_tiles_count * 0.5f - 0.5f)
  806. * translate_dir_f;
  807. v3f scale(1, 1, 1);
  808. if (translate_dir.X != 0)
  809. scale.X = continuous_tiles_count;
  810. if (translate_dir.Y != 0)
  811. scale.Y = continuous_tiles_count;
  812. if (translate_dir.Z != 0)
  813. scale.Z = continuous_tiles_count;
  814. makeFastFace(tile, lights[0], lights[1], lights[2], lights[3],
  815. pf, sp, face_dir_corrected, scale, dest);
  816. g_profiler->avg("Meshgen: Tiles per face [#]", continuous_tiles_count);
  817. }
  818. continuous_tiles_count = 1;
  819. }
  820. makes_face = next_makes_face;
  821. p_corrected = next_p_corrected;
  822. face_dir_corrected = next_face_dir_corrected;
  823. memcpy(lights, next_lights, sizeof(lights));
  824. if (next_is_different)
  825. tile = std::move(next_tile); // faster than copy
  826. }
  827. }
  828. static void updateAllFastFaceRows(MeshMakeData *data,
  829. std::vector<FastFace> &dest)
  830. {
  831. /*
  832. Go through every y,z and get top(y+) faces in rows of x+
  833. */
  834. for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
  835. for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
  836. updateFastFaceRow(data,
  837. v3s16(0, y, z),
  838. v3s16(1, 0, 0), //dir
  839. v3f (1, 0, 0),
  840. v3s16(0, 1, 0), //face dir
  841. dest);
  842. /*
  843. Go through every x,y and get right(x+) faces in rows of z+
  844. */
  845. for (s16 x = 0; x < MAP_BLOCKSIZE; x++)
  846. for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
  847. updateFastFaceRow(data,
  848. v3s16(x, y, 0),
  849. v3s16(0, 0, 1), //dir
  850. v3f (0, 0, 1),
  851. v3s16(1, 0, 0), //face dir
  852. dest);
  853. /*
  854. Go through every y,z and get back(z+) faces in rows of x+
  855. */
  856. for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
  857. for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
  858. updateFastFaceRow(data,
  859. v3s16(0, y, z),
  860. v3s16(1, 0, 0), //dir
  861. v3f (1, 0, 0),
  862. v3s16(0, 0, 1), //face dir
  863. dest);
  864. }
  865. static void applyTileColor(PreMeshBuffer &pmb)
  866. {
  867. video::SColor tc = pmb.layer.color;
  868. if (tc == video::SColor(0xFFFFFFFF))
  869. return;
  870. for (video::S3DVertex &vertex : pmb.vertices) {
  871. video::SColor *c = &vertex.Color;
  872. c->set(c->getAlpha(),
  873. c->getRed() * tc.getRed() / 255,
  874. c->getGreen() * tc.getGreen() / 255,
  875. c->getBlue() * tc.getBlue() / 255);
  876. }
  877. }
  878. /*
  879. MapBlockBspTree
  880. */
  881. void MapBlockBspTree::buildTree(const std::vector<MeshTriangle> *triangles)
  882. {
  883. this->triangles = triangles;
  884. nodes.clear();
  885. // assert that triangle index can fit into s32
  886. assert(triangles->size() <= 0x7FFFFFFFL);
  887. std::vector<s32> indexes;
  888. indexes.reserve(triangles->size());
  889. for (u32 i = 0; i < triangles->size(); i++)
  890. indexes.push_back(i);
  891. if (!indexes.empty()) {
  892. // Start in the center of the block with increment of one quarter in each direction
  893. root = buildTree(v3f(1, 0, 0), v3f((MAP_BLOCKSIZE + 1) * 0.5f * BS), MAP_BLOCKSIZE * 0.25f * BS, indexes, 0);
  894. } else {
  895. root = -1;
  896. }
  897. }
  898. /**
  899. * @brief Find a candidate plane to split a set of triangles in two
  900. *
  901. * The candidate plane is represented by one of the triangles from the set.
  902. *
  903. * @param list Vector of indexes of the triangles in the set
  904. * @param triangles Vector of all triangles in the BSP tree
  905. * @return Address of the triangle that represents the proposed split plane
  906. */
  907. static const MeshTriangle *findSplitCandidate(const std::vector<s32> &list, const std::vector<MeshTriangle> &triangles)
  908. {
  909. // find the center of the cluster.
  910. v3f center(0, 0, 0);
  911. size_t n = list.size();
  912. for (s32 i : list) {
  913. center += triangles[i].centroid / n;
  914. }
  915. // find the triangle with the largest area and closest to the center
  916. const MeshTriangle *candidate_triangle = &triangles[list[0]];
  917. const MeshTriangle *ith_triangle;
  918. for (s32 i : list) {
  919. ith_triangle = &triangles[i];
  920. if (ith_triangle->areaSQ > candidate_triangle->areaSQ ||
  921. (ith_triangle->areaSQ == candidate_triangle->areaSQ &&
  922. ith_triangle->centroid.getDistanceFromSQ(center) < candidate_triangle->centroid.getDistanceFromSQ(center))) {
  923. candidate_triangle = ith_triangle;
  924. }
  925. }
  926. return candidate_triangle;
  927. }
  928. s32 MapBlockBspTree::buildTree(v3f normal, v3f origin, float delta, const std::vector<s32> &list, u32 depth)
  929. {
  930. // if the list is empty, don't bother
  931. if (list.empty())
  932. return -1;
  933. // if there is only one triangle, or the delta is insanely small, this is a leaf node
  934. if (list.size() == 1 || delta < 0.01) {
  935. nodes.emplace_back(normal, origin, list, -1, -1);
  936. return nodes.size() - 1;
  937. }
  938. std::vector<s32> front_list;
  939. std::vector<s32> back_list;
  940. std::vector<s32> node_list;
  941. // split the list
  942. for (s32 i : list) {
  943. const MeshTriangle &triangle = (*triangles)[i];
  944. float factor = normal.dotProduct(triangle.centroid - origin);
  945. if (factor == 0)
  946. node_list.push_back(i);
  947. else if (factor > 0)
  948. front_list.push_back(i);
  949. else
  950. back_list.push_back(i);
  951. }
  952. // define the new split-plane
  953. v3f candidate_normal(normal.Z, normal.X, normal.Y);
  954. float candidate_delta = delta;
  955. if (depth % 3 == 2)
  956. candidate_delta /= 2;
  957. s32 front_index = -1;
  958. s32 back_index = -1;
  959. if (!front_list.empty()) {
  960. v3f next_normal = candidate_normal;
  961. v3f next_origin = origin + delta * normal;
  962. float next_delta = candidate_delta;
  963. if (next_delta < 5) {
  964. const MeshTriangle *candidate = findSplitCandidate(front_list, *triangles);
  965. next_normal = candidate->getNormal();
  966. next_origin = candidate->centroid;
  967. }
  968. front_index = buildTree(next_normal, next_origin, next_delta, front_list, depth + 1);
  969. // if there are no other triangles, don't create a new node
  970. if (back_list.empty() && node_list.empty())
  971. return front_index;
  972. }
  973. if (!back_list.empty()) {
  974. v3f next_normal = candidate_normal;
  975. v3f next_origin = origin - delta * normal;
  976. float next_delta = candidate_delta;
  977. if (next_delta < 5) {
  978. const MeshTriangle *candidate = findSplitCandidate(back_list, *triangles);
  979. next_normal = candidate->getNormal();
  980. next_origin = candidate->centroid;
  981. }
  982. back_index = buildTree(next_normal, next_origin, next_delta, back_list, depth + 1);
  983. // if there are no other triangles, don't create a new node
  984. if (front_list.empty() && node_list.empty())
  985. return back_index;
  986. }
  987. nodes.emplace_back(normal, origin, node_list, front_index, back_index);
  988. return nodes.size() - 1;
  989. }
  990. void MapBlockBspTree::traverse(s32 node, v3f viewpoint, std::vector<s32> &output) const
  991. {
  992. if (node < 0) return; // recursion break;
  993. const TreeNode &n = nodes[node];
  994. float factor = n.normal.dotProduct(viewpoint - n.origin);
  995. if (factor > 0)
  996. traverse(n.back_ref, viewpoint, output);
  997. else
  998. traverse(n.front_ref, viewpoint, output);
  999. if (factor != 0)
  1000. for (s32 i : n.triangle_refs)
  1001. output.push_back(i);
  1002. if (factor > 0)
  1003. traverse(n.front_ref, viewpoint, output);
  1004. else
  1005. traverse(n.back_ref, viewpoint, output);
  1006. }
  1007. /*
  1008. PartialMeshBuffer
  1009. */
  1010. void PartialMeshBuffer::beforeDraw() const
  1011. {
  1012. // Patch the indexes in the mesh buffer before draw
  1013. m_buffer->Indices = std::move(m_vertex_indexes);
  1014. m_buffer->setDirty(scene::EBT_INDEX);
  1015. }
  1016. void PartialMeshBuffer::afterDraw() const
  1017. {
  1018. // Take the data back
  1019. m_vertex_indexes = std::move(m_buffer->Indices.steal());
  1020. }
  1021. /*
  1022. MapBlockMesh
  1023. */
  1024. MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset):
  1025. m_minimap_mapblock(NULL),
  1026. m_tsrc(data->m_client->getTextureSource()),
  1027. m_shdrsrc(data->m_client->getShaderSource()),
  1028. m_animation_force_timer(0), // force initial animation
  1029. m_last_crack(-1),
  1030. m_last_daynight_ratio((u32) -1)
  1031. {
  1032. for (auto &m : m_mesh)
  1033. m = new scene::SMesh();
  1034. m_enable_shaders = data->m_use_shaders;
  1035. m_enable_vbo = g_settings->getBool("enable_vbo");
  1036. if (data->m_client->getMinimap()) {
  1037. m_minimap_mapblock = new MinimapMapblock;
  1038. m_minimap_mapblock->getMinimapNodes(
  1039. &data->m_vmanip, data->m_blockpos * MAP_BLOCKSIZE);
  1040. }
  1041. // 4-21ms for MAP_BLOCKSIZE=16 (NOTE: probably outdated)
  1042. // 24-155ms for MAP_BLOCKSIZE=32 (NOTE: probably outdated)
  1043. //TimeTaker timer1("MapBlockMesh()");
  1044. std::vector<FastFace> fastfaces_new;
  1045. fastfaces_new.reserve(512);
  1046. /*
  1047. We are including the faces of the trailing edges of the block.
  1048. This means that when something changes, the caller must
  1049. also update the meshes of the blocks at the leading edges.
  1050. NOTE: This is the slowest part of this method.
  1051. */
  1052. {
  1053. // 4-23ms for MAP_BLOCKSIZE=16 (NOTE: probably outdated)
  1054. //TimeTaker timer2("updateAllFastFaceRows()");
  1055. updateAllFastFaceRows(data, fastfaces_new);
  1056. }
  1057. // End of slow part
  1058. /*
  1059. Convert FastFaces to MeshCollector
  1060. */
  1061. MeshCollector collector;
  1062. {
  1063. // avg 0ms (100ms spikes when loading textures the first time)
  1064. // (NOTE: probably outdated)
  1065. //TimeTaker timer2("MeshCollector building");
  1066. for (const FastFace &f : fastfaces_new) {
  1067. static const u16 indices[] = {0, 1, 2, 2, 3, 0};
  1068. static const u16 indices_alternate[] = {0, 1, 3, 2, 3, 1};
  1069. const u16 *indices_p =
  1070. f.vertex_0_2_connected ? indices : indices_alternate;
  1071. collector.append(f.tile, f.vertices, 4, indices_p, 6);
  1072. }
  1073. }
  1074. /*
  1075. Add special graphics:
  1076. - torches
  1077. - flowing water
  1078. - fences
  1079. - whatever
  1080. */
  1081. {
  1082. MapblockMeshGenerator(data, &collector,
  1083. data->m_client->getSceneManager()->getMeshManipulator()).generate();
  1084. }
  1085. /*
  1086. Convert MeshCollector to SMesh
  1087. */
  1088. const bool desync_animations = g_settings->getBool(
  1089. "desynchronize_mapblock_texture_animation");
  1090. for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
  1091. for(u32 i = 0; i < collector.prebuffers[layer].size(); i++)
  1092. {
  1093. PreMeshBuffer &p = collector.prebuffers[layer][i];
  1094. applyTileColor(p);
  1095. // Generate animation data
  1096. // - Cracks
  1097. if (p.layer.material_flags & MATERIAL_FLAG_CRACK) {
  1098. // Find the texture name plus ^[crack:N:
  1099. std::ostringstream os(std::ios::binary);
  1100. os << m_tsrc->getTextureName(p.layer.texture_id) << "^[crack";
  1101. if (p.layer.material_flags & MATERIAL_FLAG_CRACK_OVERLAY)
  1102. os << "o"; // use ^[cracko
  1103. u8 tiles = p.layer.scale;
  1104. if (tiles > 1)
  1105. os << ":" << (u32)tiles;
  1106. os << ":" << (u32)p.layer.animation_frame_count << ":";
  1107. m_crack_materials.insert(std::make_pair(
  1108. std::pair<u8, u32>(layer, i), os.str()));
  1109. // Replace tile texture with the cracked one
  1110. p.layer.texture = m_tsrc->getTextureForMesh(
  1111. os.str() + "0",
  1112. &p.layer.texture_id);
  1113. }
  1114. // - Texture animation
  1115. if (p.layer.material_flags & MATERIAL_FLAG_ANIMATION) {
  1116. // Add to MapBlockMesh in order to animate these tiles
  1117. auto &info = m_animation_info[{layer, i}];
  1118. info.tile = p.layer;
  1119. info.frame = 0;
  1120. if (desync_animations) {
  1121. // Get starting position from noise
  1122. info.frame_offset =
  1123. 100000 * (2.0 + noise3d(
  1124. data->m_blockpos.X, data->m_blockpos.Y,
  1125. data->m_blockpos.Z, 0));
  1126. } else {
  1127. // Play all synchronized
  1128. info.frame_offset = 0;
  1129. }
  1130. // Replace tile texture with the first animation frame
  1131. p.layer.texture = (*p.layer.frames)[0].texture;
  1132. }
  1133. if (!m_enable_shaders) {
  1134. // Extract colors for day-night animation
  1135. // Dummy sunlight to handle non-sunlit areas
  1136. video::SColorf sunlight;
  1137. get_sunlight_color(&sunlight, 0);
  1138. std::map<u32, video::SColor> colors;
  1139. const u32 vertex_count = p.vertices.size();
  1140. for (u32 j = 0; j < vertex_count; j++) {
  1141. video::SColor *vc = &p.vertices[j].Color;
  1142. video::SColor copy = *vc;
  1143. if (vc->getAlpha() == 0) // No sunlight - no need to animate
  1144. final_color_blend(vc, copy, sunlight); // Finalize color
  1145. else // Record color to animate
  1146. colors[j] = copy;
  1147. // The sunlight ratio has been stored,
  1148. // delete alpha (for the final rendering).
  1149. vc->setAlpha(255);
  1150. }
  1151. if (!colors.empty())
  1152. m_daynight_diffs[{layer, i}] = std::move(colors);
  1153. }
  1154. // Create material
  1155. video::SMaterial material;
  1156. material.setFlag(video::EMF_LIGHTING, false);
  1157. material.setFlag(video::EMF_BACK_FACE_CULLING, true);
  1158. material.setFlag(video::EMF_BILINEAR_FILTER, false);
  1159. material.setFlag(video::EMF_FOG_ENABLE, true);
  1160. material.setTexture(0, p.layer.texture);
  1161. if (m_enable_shaders) {
  1162. material.MaterialType = m_shdrsrc->getShaderInfo(
  1163. p.layer.shader_id).material;
  1164. p.layer.applyMaterialOptionsWithShaders(material);
  1165. if (p.layer.normal_texture)
  1166. material.setTexture(1, p.layer.normal_texture);
  1167. material.setTexture(2, p.layer.flags_texture);
  1168. } else {
  1169. p.layer.applyMaterialOptions(material);
  1170. }
  1171. scene::SMesh *mesh = (scene::SMesh *)m_mesh[layer];
  1172. scene::SMeshBuffer *buf = new scene::SMeshBuffer();
  1173. buf->Material = material;
  1174. if (p.layer.isTransparent()) {
  1175. buf->append(&p.vertices[0], p.vertices.size(), nullptr, 0);
  1176. MeshTriangle t;
  1177. t.buffer = buf;
  1178. m_transparent_triangles.reserve(p.indices.size() / 3);
  1179. for (u32 i = 0; i < p.indices.size(); i += 3) {
  1180. t.p1 = p.indices[i];
  1181. t.p2 = p.indices[i + 1];
  1182. t.p3 = p.indices[i + 2];
  1183. t.updateAttributes();
  1184. m_transparent_triangles.push_back(t);
  1185. }
  1186. } else {
  1187. buf->append(&p.vertices[0], p.vertices.size(),
  1188. &p.indices[0], p.indices.size());
  1189. }
  1190. mesh->addMeshBuffer(buf);
  1191. buf->drop();
  1192. }
  1193. if (m_mesh[layer]) {
  1194. // Use VBO for mesh (this just would set this for ever buffer)
  1195. if (m_enable_vbo)
  1196. m_mesh[layer]->setHardwareMappingHint(scene::EHM_STATIC);
  1197. }
  1198. }
  1199. //std::cout<<"added "<<fastfaces.getSize()<<" faces."<<std::endl;
  1200. m_bsp_tree.buildTree(&m_transparent_triangles);
  1201. // Check if animation is required for this mesh
  1202. m_has_animation =
  1203. !m_crack_materials.empty() ||
  1204. !m_daynight_diffs.empty() ||
  1205. !m_animation_info.empty();
  1206. }
  1207. MapBlockMesh::~MapBlockMesh()
  1208. {
  1209. for (scene::IMesh *m : m_mesh) {
  1210. #if IRRLICHT_VERSION_MT_REVISION < 5
  1211. if (m_enable_vbo) {
  1212. for (u32 i = 0; i < m->getMeshBufferCount(); i++) {
  1213. scene::IMeshBuffer *buf = m->getMeshBuffer(i);
  1214. RenderingEngine::get_video_driver()->removeHardwareBuffer(buf);
  1215. }
  1216. }
  1217. #endif
  1218. m->drop();
  1219. }
  1220. delete m_minimap_mapblock;
  1221. }
  1222. bool MapBlockMesh::animate(bool faraway, float time, int crack,
  1223. u32 daynight_ratio)
  1224. {
  1225. if (!m_has_animation) {
  1226. m_animation_force_timer = 100000;
  1227. return false;
  1228. }
  1229. m_animation_force_timer = myrand_range(5, 100);
  1230. // Cracks
  1231. if (crack != m_last_crack) {
  1232. for (auto &crack_material : m_crack_materials) {
  1233. scene::IMeshBuffer *buf = m_mesh[crack_material.first.first]->
  1234. getMeshBuffer(crack_material.first.second);
  1235. // Create new texture name from original
  1236. std::string s = crack_material.second + itos(crack);
  1237. u32 new_texture_id = 0;
  1238. video::ITexture *new_texture =
  1239. m_tsrc->getTextureForMesh(s, &new_texture_id);
  1240. buf->getMaterial().setTexture(0, new_texture);
  1241. // If the current material is also animated, update animation info
  1242. auto anim_it = m_animation_info.find(crack_material.first);
  1243. if (anim_it != m_animation_info.end()) {
  1244. TileLayer &tile = anim_it->second.tile;
  1245. tile.texture = new_texture;
  1246. tile.texture_id = new_texture_id;
  1247. // force animation update
  1248. anim_it->second.frame = -1;
  1249. }
  1250. }
  1251. m_last_crack = crack;
  1252. }
  1253. // Texture animation
  1254. for (auto &it : m_animation_info) {
  1255. const TileLayer &tile = it.second.tile;
  1256. // Figure out current frame
  1257. int frameno = (int)(time * 1000 / tile.animation_frame_length_ms
  1258. + it.second.frame_offset) % tile.animation_frame_count;
  1259. // If frame doesn't change, skip
  1260. if (frameno == it.second.frame)
  1261. continue;
  1262. it.second.frame = frameno;
  1263. scene::IMeshBuffer *buf = m_mesh[it.first.first]->getMeshBuffer(it.first.second);
  1264. const FrameSpec &frame = (*tile.frames)[frameno];
  1265. buf->getMaterial().setTexture(0, frame.texture);
  1266. if (m_enable_shaders) {
  1267. if (frame.normal_texture)
  1268. buf->getMaterial().setTexture(1, frame.normal_texture);
  1269. buf->getMaterial().setTexture(2, frame.flags_texture);
  1270. }
  1271. }
  1272. // Day-night transition
  1273. if (!m_enable_shaders && (daynight_ratio != m_last_daynight_ratio)) {
  1274. // Force reload mesh to VBO
  1275. if (m_enable_vbo)
  1276. for (scene::IMesh *m : m_mesh)
  1277. m->setDirty();
  1278. video::SColorf day_color;
  1279. get_sunlight_color(&day_color, daynight_ratio);
  1280. for (auto &daynight_diff : m_daynight_diffs) {
  1281. scene::IMeshBuffer *buf = m_mesh[daynight_diff.first.first]->
  1282. getMeshBuffer(daynight_diff.first.second);
  1283. video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices();
  1284. for (const auto &j : daynight_diff.second)
  1285. final_color_blend(&(vertices[j.first].Color), j.second,
  1286. day_color);
  1287. }
  1288. m_last_daynight_ratio = daynight_ratio;
  1289. }
  1290. return true;
  1291. }
  1292. void MapBlockMesh::updateTransparentBuffers(v3f camera_pos, v3s16 block_pos)
  1293. {
  1294. // nothing to do if the entire block is opaque
  1295. if (m_transparent_triangles.empty())
  1296. return;
  1297. v3f block_posf = intToFloat(block_pos * MAP_BLOCKSIZE, BS);
  1298. v3f rel_camera_pos = camera_pos - block_posf;
  1299. std::vector<s32> triangle_refs;
  1300. m_bsp_tree.traverse(rel_camera_pos, triangle_refs);
  1301. // arrange index sequences into partial buffers
  1302. m_transparent_buffers.clear();
  1303. scene::SMeshBuffer *current_buffer = nullptr;
  1304. std::vector<u16> current_strain;
  1305. for (auto i : triangle_refs) {
  1306. const auto &t = m_transparent_triangles[i];
  1307. if (current_buffer != t.buffer) {
  1308. if (current_buffer) {
  1309. m_transparent_buffers.emplace_back(current_buffer, std::move(current_strain));
  1310. current_strain.clear();
  1311. }
  1312. current_buffer = t.buffer;
  1313. }
  1314. current_strain.push_back(t.p1);
  1315. current_strain.push_back(t.p2);
  1316. current_strain.push_back(t.p3);
  1317. }
  1318. if (!current_strain.empty())
  1319. m_transparent_buffers.emplace_back(current_buffer, std::move(current_strain));
  1320. }
  1321. void MapBlockMesh::consolidateTransparentBuffers()
  1322. {
  1323. m_transparent_buffers.clear();
  1324. scene::SMeshBuffer *current_buffer = nullptr;
  1325. std::vector<u16> current_strain;
  1326. // use the fact that m_transparent_triangles is already arranged by buffer
  1327. for (const auto &t : m_transparent_triangles) {
  1328. if (current_buffer != t.buffer) {
  1329. if (current_buffer != nullptr) {
  1330. this->m_transparent_buffers.emplace_back(current_buffer, std::move(current_strain));
  1331. current_strain.clear();
  1332. }
  1333. current_buffer = t.buffer;
  1334. }
  1335. current_strain.push_back(t.p1);
  1336. current_strain.push_back(t.p2);
  1337. current_strain.push_back(t.p3);
  1338. }
  1339. if (!current_strain.empty()) {
  1340. this->m_transparent_buffers.emplace_back(current_buffer, std::move(current_strain));
  1341. }
  1342. }
  1343. video::SColor encode_light(u16 light, u8 emissive_light)
  1344. {
  1345. // Get components
  1346. u32 day = (light & 0xff);
  1347. u32 night = (light >> 8);
  1348. // Add emissive light
  1349. night += emissive_light * 2.5f;
  1350. if (night > 255)
  1351. night = 255;
  1352. // Since we don't know if the day light is sunlight or
  1353. // artificial light, assume it is artificial when the night
  1354. // light bank is also lit.
  1355. if (day < night)
  1356. day = 0;
  1357. else
  1358. day = day - night;
  1359. u32 sum = day + night;
  1360. // Ratio of sunlight:
  1361. u32 r;
  1362. if (sum > 0)
  1363. r = day * 255 / sum;
  1364. else
  1365. r = 0;
  1366. // Average light:
  1367. float b = (day + night) / 2;
  1368. return video::SColor(r, b, b, b);
  1369. }