lightmap_gi.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  1. /*************************************************************************/
  2. /* lightmap_gi.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "lightmap_gi.h"
  31. #include "core/io/config_file.h"
  32. #include "core/math/delaunay_3d.h"
  33. #include "lightmap_probe.h"
  34. #include "scene/3d/mesh_instance_3d.h"
  35. void LightmapGIData::add_user(const NodePath &p_path, const Rect2 &p_uv_scale, int p_slice_index, int32_t p_sub_instance) {
  36. User user;
  37. user.path = p_path;
  38. user.uv_scale = p_uv_scale;
  39. user.slice_index = p_slice_index;
  40. user.sub_instance = p_sub_instance;
  41. users.push_back(user);
  42. }
  43. int LightmapGIData::get_user_count() const {
  44. return users.size();
  45. }
  46. NodePath LightmapGIData::get_user_path(int p_user) const {
  47. ERR_FAIL_INDEX_V(p_user, users.size(), NodePath());
  48. return users[p_user].path;
  49. }
  50. int32_t LightmapGIData::get_user_sub_instance(int p_user) const {
  51. ERR_FAIL_INDEX_V(p_user, users.size(), -1);
  52. return users[p_user].sub_instance;
  53. }
  54. Rect2 LightmapGIData::get_user_lightmap_uv_scale(int p_user) const {
  55. ERR_FAIL_INDEX_V(p_user, users.size(), Rect2());
  56. return users[p_user].uv_scale;
  57. }
  58. int LightmapGIData::get_user_lightmap_slice_index(int p_user) const {
  59. ERR_FAIL_INDEX_V(p_user, users.size(), -1);
  60. return users[p_user].slice_index;
  61. }
  62. void LightmapGIData::clear_users() {
  63. users.clear();
  64. }
  65. void LightmapGIData::_set_user_data(const Array &p_data) {
  66. ERR_FAIL_COND(p_data.is_empty());
  67. ERR_FAIL_COND((p_data.size() % 4) != 0);
  68. for (int i = 0; i < p_data.size(); i += 4) {
  69. add_user(p_data[i + 0], p_data[i + 1], p_data[i + 2], p_data[i + 3]);
  70. }
  71. }
  72. Array LightmapGIData::_get_user_data() const {
  73. Array ret;
  74. for (int i = 0; i < users.size(); i++) {
  75. ret.push_back(users[i].path);
  76. ret.push_back(users[i].uv_scale);
  77. ret.push_back(users[i].slice_index);
  78. ret.push_back(users[i].sub_instance);
  79. }
  80. return ret;
  81. }
  82. void LightmapGIData::_set_light_textures_data(const Array &p_data) {
  83. ERR_FAIL_COND(p_data.is_empty());
  84. if (p_data.size() == 1) {
  85. set_light_texture(p_data[0]);
  86. } else {
  87. Vector<Ref<Image>> images;
  88. for (int i = 0; i < p_data.size(); i++) {
  89. Ref<TextureLayered> texture = p_data[i];
  90. for (int j = 0; j < texture->get_layers(); j++) {
  91. images.push_back(texture->get_layer_data(j));
  92. }
  93. }
  94. Ref<Texture2DArray> combined_texture;
  95. combined_texture.instantiate();
  96. combined_texture->create_from_images(images);
  97. set_light_texture(combined_texture);
  98. }
  99. }
  100. Array LightmapGIData::_get_light_textures_data() const {
  101. Array ret;
  102. if (light_texture.is_null() || light_texture->get_layers() == 0) {
  103. return ret;
  104. }
  105. Vector<Ref<Image>> images;
  106. for (int i = 0; i < light_texture->get_layers(); i++) {
  107. images.push_back(light_texture->get_layer_data(i));
  108. }
  109. int slice_count = images.size();
  110. int slice_width = images[0]->get_width();
  111. int slice_height = images[0]->get_height();
  112. int slices_per_texture = Image::MAX_HEIGHT / slice_height;
  113. int texture_count = Math::ceil(slice_count / (float)slices_per_texture);
  114. ret.resize(texture_count);
  115. String base_name = get_path().get_basename();
  116. int last_count = slice_count % slices_per_texture;
  117. for (int i = 0; i < texture_count; i++) {
  118. int texture_slice_count = (i == texture_count - 1 && last_count != 0) ? last_count : slices_per_texture;
  119. Ref<Image> texture_image;
  120. texture_image.instantiate();
  121. texture_image->create(slice_width, slice_height * texture_slice_count, false, images[0]->get_format());
  122. for (int j = 0; j < texture_slice_count; j++) {
  123. texture_image->blit_rect(images[i * slices_per_texture + j], Rect2i(0, 0, slice_width, slice_height), Point2i(0, slice_height * j));
  124. }
  125. String texture_path = texture_count > 1 ? base_name + "_" + itos(i) + ".exr" : base_name + ".exr";
  126. Ref<ConfigFile> config;
  127. config.instantiate();
  128. if (FileAccess::exists(texture_path + ".import")) {
  129. config->load(texture_path + ".import");
  130. }
  131. config->set_value("remap", "importer", "2d_array_texture");
  132. config->set_value("remap", "type", "CompressedTexture2DArray");
  133. if (!config->has_section_key("params", "compress/mode")) {
  134. config->set_value("params", "compress/mode", 2); //user may want another compression, so leave it be
  135. }
  136. config->set_value("params", "compress/channel_pack", 1);
  137. config->set_value("params", "mipmaps/generate", false);
  138. config->set_value("params", "slices/horizontal", 1);
  139. config->set_value("params", "slices/vertical", texture_slice_count);
  140. config->save(texture_path + ".import");
  141. Error err = texture_image->save_exr(texture_path, false);
  142. ERR_FAIL_COND_V(err, ret);
  143. ResourceLoader::import(texture_path);
  144. Ref<TextureLayered> t = ResourceLoader::load(texture_path); //if already loaded, it will be updated on refocus?
  145. ERR_FAIL_COND_V(t.is_null(), ret);
  146. ret[i] = t;
  147. }
  148. return ret;
  149. }
  150. RID LightmapGIData::get_rid() const {
  151. return lightmap;
  152. }
  153. void LightmapGIData::clear() {
  154. users.clear();
  155. }
  156. void LightmapGIData::set_light_texture(const Ref<TextureLayered> &p_light_texture) {
  157. light_texture = p_light_texture;
  158. RS::get_singleton()->lightmap_set_textures(lightmap, light_texture.is_valid() ? light_texture->get_rid() : RID(), uses_spherical_harmonics);
  159. }
  160. Ref<TextureLayered> LightmapGIData::get_light_texture() const {
  161. return light_texture;
  162. }
  163. void LightmapGIData::set_uses_spherical_harmonics(bool p_enable) {
  164. uses_spherical_harmonics = p_enable;
  165. RS::get_singleton()->lightmap_set_textures(lightmap, light_texture.is_valid() ? light_texture->get_rid() : RID(), uses_spherical_harmonics);
  166. }
  167. bool LightmapGIData::is_using_spherical_harmonics() const {
  168. return uses_spherical_harmonics;
  169. }
  170. void LightmapGIData::set_capture_data(const AABB &p_bounds, bool p_interior, const PackedVector3Array &p_points, const PackedColorArray &p_point_sh, const PackedInt32Array &p_tetrahedra, const PackedInt32Array &p_bsp_tree) {
  171. if (p_points.size()) {
  172. int pc = p_points.size();
  173. ERR_FAIL_COND(pc * 9 != p_point_sh.size());
  174. ERR_FAIL_COND((p_tetrahedra.size() % 4) != 0);
  175. ERR_FAIL_COND((p_bsp_tree.size() % 6) != 0);
  176. RS::get_singleton()->lightmap_set_probe_capture_data(lightmap, p_points, p_point_sh, p_tetrahedra, p_bsp_tree);
  177. RS::get_singleton()->lightmap_set_probe_bounds(lightmap, p_bounds);
  178. RS::get_singleton()->lightmap_set_probe_interior(lightmap, p_interior);
  179. } else {
  180. RS::get_singleton()->lightmap_set_probe_capture_data(lightmap, PackedVector3Array(), PackedColorArray(), PackedInt32Array(), PackedInt32Array());
  181. RS::get_singleton()->lightmap_set_probe_bounds(lightmap, AABB());
  182. RS::get_singleton()->lightmap_set_probe_interior(lightmap, false);
  183. }
  184. interior = p_interior;
  185. bounds = p_bounds;
  186. }
  187. PackedVector3Array LightmapGIData::get_capture_points() const {
  188. return RS::get_singleton()->lightmap_get_probe_capture_points(lightmap);
  189. }
  190. PackedColorArray LightmapGIData::get_capture_sh() const {
  191. return RS::get_singleton()->lightmap_get_probe_capture_sh(lightmap);
  192. }
  193. PackedInt32Array LightmapGIData::get_capture_tetrahedra() const {
  194. return RS::get_singleton()->lightmap_get_probe_capture_tetrahedra(lightmap);
  195. }
  196. PackedInt32Array LightmapGIData::get_capture_bsp_tree() const {
  197. return RS::get_singleton()->lightmap_get_probe_capture_bsp_tree(lightmap);
  198. }
  199. AABB LightmapGIData::get_capture_bounds() const {
  200. return bounds;
  201. }
  202. bool LightmapGIData::is_interior() const {
  203. return interior;
  204. }
  205. void LightmapGIData::_set_probe_data(const Dictionary &p_data) {
  206. ERR_FAIL_COND(!p_data.has("bounds"));
  207. ERR_FAIL_COND(!p_data.has("points"));
  208. ERR_FAIL_COND(!p_data.has("tetrahedra"));
  209. ERR_FAIL_COND(!p_data.has("bsp"));
  210. ERR_FAIL_COND(!p_data.has("sh"));
  211. ERR_FAIL_COND(!p_data.has("interior"));
  212. set_capture_data(p_data["bounds"], p_data["interior"], p_data["points"], p_data["sh"], p_data["tetrahedra"], p_data["bsp"]);
  213. }
  214. Dictionary LightmapGIData::_get_probe_data() const {
  215. Dictionary d;
  216. d["bounds"] = get_capture_bounds();
  217. d["points"] = get_capture_points();
  218. d["tetrahedra"] = get_capture_tetrahedra();
  219. d["bsp"] = get_capture_bsp_tree();
  220. d["sh"] = get_capture_sh();
  221. d["interior"] = is_interior();
  222. return d;
  223. }
  224. void LightmapGIData::_bind_methods() {
  225. ClassDB::bind_method(D_METHOD("_set_user_data", "data"), &LightmapGIData::_set_user_data);
  226. ClassDB::bind_method(D_METHOD("_get_user_data"), &LightmapGIData::_get_user_data);
  227. ClassDB::bind_method(D_METHOD("set_light_texture", "light_texture"), &LightmapGIData::set_light_texture);
  228. ClassDB::bind_method(D_METHOD("get_light_texture"), &LightmapGIData::get_light_texture);
  229. ClassDB::bind_method(D_METHOD("_set_light_textures_data", "data"), &LightmapGIData::_set_light_textures_data);
  230. ClassDB::bind_method(D_METHOD("_get_light_textures_data"), &LightmapGIData::_get_light_textures_data);
  231. ClassDB::bind_method(D_METHOD("set_uses_spherical_harmonics", "uses_spherical_harmonics"), &LightmapGIData::set_uses_spherical_harmonics);
  232. ClassDB::bind_method(D_METHOD("is_using_spherical_harmonics"), &LightmapGIData::is_using_spherical_harmonics);
  233. ClassDB::bind_method(D_METHOD("add_user", "path", "uv_scale", "slice_index", "sub_instance"), &LightmapGIData::add_user);
  234. ClassDB::bind_method(D_METHOD("get_user_count"), &LightmapGIData::get_user_count);
  235. ClassDB::bind_method(D_METHOD("get_user_path", "user_idx"), &LightmapGIData::get_user_path);
  236. ClassDB::bind_method(D_METHOD("clear_users"), &LightmapGIData::clear_users);
  237. ClassDB::bind_method(D_METHOD("_set_probe_data", "data"), &LightmapGIData::_set_probe_data);
  238. ClassDB::bind_method(D_METHOD("_get_probe_data"), &LightmapGIData::_get_probe_data);
  239. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "light_texture", PROPERTY_HINT_RESOURCE_TYPE, "TextureLayered", PROPERTY_USAGE_EDITOR), "set_light_texture", "get_light_texture"); // property usage default but no save
  240. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "light_textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_light_textures_data", "_get_light_textures_data");
  241. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "uses_spherical_harmonics", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_uses_spherical_harmonics", "is_using_spherical_harmonics");
  242. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "user_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_user_data", "_get_user_data");
  243. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "probe_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_probe_data", "_get_probe_data");
  244. }
  245. LightmapGIData::LightmapGIData() {
  246. lightmap = RS::get_singleton()->lightmap_create();
  247. }
  248. LightmapGIData::~LightmapGIData() {
  249. RS::get_singleton()->free(lightmap);
  250. }
  251. ///////////////////////////
  252. void LightmapGI::_find_meshes_and_lights(Node *p_at_node, Vector<MeshesFound> &meshes, Vector<LightsFound> &lights, Vector<Vector3> &probes) {
  253. MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_at_node);
  254. if (mi && mi->get_gi_mode() == GeometryInstance3D::GI_MODE_STATIC && mi->is_visible_in_tree()) {
  255. Ref<Mesh> mesh = mi->get_mesh();
  256. if (mesh.is_valid()) {
  257. bool all_have_uv2_and_normal = true;
  258. bool surfaces_found = false;
  259. for (int i = 0; i < mesh->get_surface_count(); i++) {
  260. if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  261. continue;
  262. }
  263. if (!(mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_TEX_UV2)) {
  264. all_have_uv2_and_normal = false;
  265. break;
  266. }
  267. if (!(mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_NORMAL)) {
  268. all_have_uv2_and_normal = false;
  269. break;
  270. }
  271. surfaces_found = true;
  272. }
  273. if (surfaces_found && all_have_uv2_and_normal) {
  274. //READY TO BAKE! size hint could be computed if not found, actually..
  275. MeshesFound mf;
  276. mf.xform = get_global_transform().affine_inverse() * mi->get_global_transform();
  277. mf.node_path = get_path_to(mi);
  278. mf.subindex = -1;
  279. mf.mesh = mesh;
  280. static const int lightmap_scale[GeometryInstance3D::LIGHTMAP_SCALE_MAX] = { 1, 2, 4, 8 };
  281. mf.lightmap_scale = lightmap_scale[mi->get_lightmap_scale()];
  282. Ref<Material> all_override = mi->get_material_override();
  283. for (int i = 0; i < mesh->get_surface_count(); i++) {
  284. if (all_override.is_valid()) {
  285. mf.overrides.push_back(all_override);
  286. } else {
  287. mf.overrides.push_back(mi->get_surface_override_material(i));
  288. }
  289. }
  290. meshes.push_back(mf);
  291. }
  292. }
  293. }
  294. Node3D *s = Object::cast_to<Node3D>(p_at_node);
  295. if (!mi && s) {
  296. Array bmeshes = p_at_node->call("get_bake_bmeshes");
  297. if (bmeshes.size() && (bmeshes.size() & 1) == 0) {
  298. Transform3D xf = get_global_transform().affine_inverse() * s->get_global_transform();
  299. for (int i = 0; i < bmeshes.size(); i += 2) {
  300. Ref<Mesh> mesh = bmeshes[i];
  301. if (!mesh.is_valid()) {
  302. continue;
  303. }
  304. MeshesFound mf;
  305. Transform3D mesh_xf = bmeshes[i + 1];
  306. mf.xform = xf * mesh_xf;
  307. mf.node_path = get_path_to(s);
  308. mf.subindex = i / 2;
  309. mf.lightmap_scale = 1;
  310. mf.mesh = mesh;
  311. meshes.push_back(mf);
  312. }
  313. }
  314. }
  315. Light3D *light = Object::cast_to<Light3D>(p_at_node);
  316. if (light && light->get_bake_mode() != Light3D::BAKE_DISABLED) {
  317. LightsFound lf;
  318. lf.xform = get_global_transform().affine_inverse() * light->get_global_transform();
  319. lf.light = light;
  320. lights.push_back(lf);
  321. }
  322. LightmapProbe *probe = Object::cast_to<LightmapProbe>(p_at_node);
  323. if (probe) {
  324. Transform3D xf = get_global_transform().affine_inverse() * probe->get_global_transform();
  325. probes.push_back(xf.origin);
  326. }
  327. for (int i = 0; i < p_at_node->get_child_count(); i++) {
  328. Node *child = p_at_node->get_child(i);
  329. if (!child->get_owner()) {
  330. continue; //maybe a helper
  331. }
  332. _find_meshes_and_lights(child, meshes, lights, probes);
  333. }
  334. }
  335. int LightmapGI::_bsp_get_simplex_side(const Vector<Vector3> &p_points, const LocalVector<BSPSimplex> &p_simplices, const Plane &p_plane, uint32_t p_simplex) const {
  336. int over = 0;
  337. int under = 0;
  338. const BSPSimplex &s = p_simplices[p_simplex];
  339. for (int i = 0; i < 4; i++) {
  340. const Vector3 v = p_points[s.vertices[i]];
  341. if (p_plane.has_point(v)) {
  342. // Coplanar.
  343. } else if (p_plane.is_point_over(v)) {
  344. over++;
  345. } else {
  346. under++;
  347. }
  348. }
  349. ERR_FAIL_COND_V(under == 0 && over == 0, -2); //should never happen, we discarded flat simplices before, but in any case drop it from the bsp tree and throw an error
  350. if (under == 0) {
  351. return 1; // all over
  352. } else if (over == 0) {
  353. return -1; // all under
  354. } else {
  355. return 0; // crossing
  356. }
  357. }
  358. //#define DEBUG_BSP
  359. int32_t LightmapGI::_compute_bsp_tree(const Vector<Vector3> &p_points, const LocalVector<Plane> &p_planes, LocalVector<int32_t> &planes_tested, const LocalVector<BSPSimplex> &p_simplices, const LocalVector<int32_t> &p_simplex_indices, LocalVector<BSPNode> &bsp_nodes) {
  360. //if we reach here, it means there is more than one simplex
  361. int32_t node_index = (int32_t)bsp_nodes.size();
  362. bsp_nodes.push_back(BSPNode());
  363. //test with all the simplex planes
  364. Plane best_plane;
  365. float best_plane_score = -1.0;
  366. for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
  367. const BSPSimplex &s = p_simplices[p_simplex_indices[i]];
  368. for (int j = 0; j < 4; j++) {
  369. uint32_t plane_index = s.planes[j];
  370. if (planes_tested[plane_index] == node_index) {
  371. continue; //tested this plane already
  372. }
  373. planes_tested[plane_index] = node_index;
  374. static const int face_order[4][3] = {
  375. { 0, 1, 2 },
  376. { 0, 2, 3 },
  377. { 0, 1, 3 },
  378. { 1, 2, 3 }
  379. };
  380. // despite getting rid of plane duplicates, we should still use here the actual plane to avoid numerical error
  381. // from thinking this same simplex is intersecting rather than on a side
  382. Vector3 v0 = p_points[s.vertices[face_order[j][0]]];
  383. Vector3 v1 = p_points[s.vertices[face_order[j][1]]];
  384. Vector3 v2 = p_points[s.vertices[face_order[j][2]]];
  385. Plane plane(v0, v1, v2);
  386. //test with all the simplices
  387. int over_count = 0;
  388. int under_count = 0;
  389. for (uint32_t k = 0; k < p_simplex_indices.size(); k++) {
  390. int side = _bsp_get_simplex_side(p_points, p_simplices, plane, p_simplex_indices[k]);
  391. if (side == -2) {
  392. continue; //this simplex is invalid, skip for now
  393. } else if (side < 0) {
  394. under_count++;
  395. } else if (side > 0) {
  396. over_count++;
  397. }
  398. }
  399. if (under_count == 0 && over_count == 0) {
  400. continue; //most likely precision issue with a flat simplex, do not try this plane
  401. }
  402. if (under_count > over_count) { //make sure under is always less than over, so we can compute the same ratio
  403. SWAP(under_count, over_count);
  404. }
  405. float score = 0; //by default, score is 0 (worst)
  406. if (over_count > 0) {
  407. //give score mainly based on ratio (under / over), this means that this plane is splitting simplices a lot, but its balanced
  408. score = float(under_count) / over_count;
  409. }
  410. //adjusting priority over least splits, probably not a great idea
  411. //score *= Math::sqrt(float(over_count + under_count) / p_simplex_indices.size()); //also multiply score
  412. if (score > best_plane_score) {
  413. best_plane = plane;
  414. best_plane_score = score;
  415. }
  416. }
  417. }
  418. LocalVector<int32_t> indices_over;
  419. LocalVector<int32_t> indices_under;
  420. //split again, but add to list
  421. for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
  422. uint32_t index = p_simplex_indices[i];
  423. int side = _bsp_get_simplex_side(p_points, p_simplices, best_plane, index);
  424. if (side == -2) {
  425. continue; //simplex sits on the plane, does not make sense to use it
  426. }
  427. if (side <= 0) {
  428. indices_under.push_back(index);
  429. }
  430. if (side >= 0) {
  431. indices_over.push_back(index);
  432. }
  433. }
  434. #ifdef DEBUG_BSP
  435. print_line("node " + itos(node_index) + " found plane: " + best_plane + " score:" + rtos(best_plane_score) + " - over " + itos(indices_over.size()) + " under " + itos(indices_under.size()) + " intersecting " + itos(intersecting));
  436. #endif
  437. if (best_plane_score < 0.0 || indices_over.size() == p_simplex_indices.size() || indices_under.size() == p_simplex_indices.size()) {
  438. ERR_FAIL_COND_V(p_simplex_indices.size() <= 1, 0); //should not happen, this is a bug
  439. // Failed to separate the tetrahedrons using planes
  440. // this means Delaunay broke at some point.
  441. // Luckily, because we are using tetrahedrons, we can resort to
  442. // less precise but still working ways to generate the separating plane
  443. // this will most likely look bad when interpolating, but at least it will not crash.
  444. // and the arctifact will most likely also be very small, so too difficult to notice.
  445. //find the longest axis
  446. WARN_PRINT("Inconsistency found in triangulation while building BSP, probe interpolation quality may degrade a bit.");
  447. LocalVector<Vector3> centers;
  448. AABB bounds_all;
  449. for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
  450. AABB bounds;
  451. for (uint32_t j = 0; j < 4; j++) {
  452. Vector3 p = p_points[p_simplices[p_simplex_indices[i]].vertices[j]];
  453. if (j == 0) {
  454. bounds.position = p;
  455. } else {
  456. bounds.expand_to(p);
  457. }
  458. }
  459. if (i == 0) {
  460. centers.push_back(bounds.get_center());
  461. } else {
  462. bounds_all.merge_with(bounds);
  463. }
  464. }
  465. Vector3::Axis longest_axis = Vector3::Axis(bounds_all.get_longest_axis_index());
  466. //find the simplex that will go under
  467. uint32_t min_d_idx = 0xFFFFFFFF;
  468. float min_d_dist = 1e20;
  469. for (uint32_t i = 0; i < centers.size(); i++) {
  470. if (centers[i][longest_axis] < min_d_dist) {
  471. min_d_idx = i;
  472. min_d_dist = centers[i][longest_axis];
  473. }
  474. }
  475. //rebuild best_plane and over/under arrays
  476. best_plane = Plane();
  477. best_plane.normal[longest_axis] = 1.0;
  478. best_plane.d = min_d_dist;
  479. indices_under.clear();
  480. indices_under.push_back(min_d_idx);
  481. indices_over.clear();
  482. for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
  483. if (i == min_d_idx) {
  484. continue;
  485. }
  486. indices_over.push_back(p_simplex_indices[i]);
  487. }
  488. }
  489. BSPNode node;
  490. node.plane = best_plane;
  491. if (indices_under.size() == 0) {
  492. //nothing to do here
  493. node.under = BSPNode::EMPTY_LEAF;
  494. } else if (indices_under.size() == 1) {
  495. node.under = -(indices_under[0] + 1);
  496. } else {
  497. node.under = _compute_bsp_tree(p_points, p_planes, planes_tested, p_simplices, indices_under, bsp_nodes);
  498. }
  499. if (indices_over.size() == 0) {
  500. //nothing to do here
  501. node.over = BSPNode::EMPTY_LEAF;
  502. } else if (indices_over.size() == 1) {
  503. node.over = -(indices_over[0] + 1);
  504. } else {
  505. node.over = _compute_bsp_tree(p_points, p_planes, planes_tested, p_simplices, indices_over, bsp_nodes);
  506. }
  507. bsp_nodes[node_index] = node;
  508. return node_index;
  509. }
  510. bool LightmapGI::_lightmap_bake_step_function(float p_completion, const String &p_text, void *ud, bool p_refresh) {
  511. BakeStepUD *bsud = (BakeStepUD *)ud;
  512. bool ret = false;
  513. if (bsud->func) {
  514. ret = bsud->func(bsud->from_percent + p_completion * (bsud->to_percent - bsud->from_percent), p_text, bsud->ud, p_refresh);
  515. }
  516. return ret;
  517. }
  518. void LightmapGI::_plot_triangle_into_octree(GenProbesOctree *p_cell, float p_cell_size, const Vector3 *p_triangle) {
  519. for (int i = 0; i < 8; i++) {
  520. Vector3i pos = p_cell->offset;
  521. uint32_t half_size = p_cell->size / 2;
  522. if (i & 1) {
  523. pos.x += half_size;
  524. }
  525. if (i & 2) {
  526. pos.y += half_size;
  527. }
  528. if (i & 4) {
  529. pos.z += half_size;
  530. }
  531. AABB subcell;
  532. subcell.position = Vector3(pos) * p_cell_size;
  533. subcell.size = Vector3(half_size, half_size, half_size) * p_cell_size;
  534. if (!Geometry3D::triangle_box_overlap(subcell.get_center(), subcell.size * 0.5, p_triangle)) {
  535. continue;
  536. }
  537. if (p_cell->children[i] == nullptr) {
  538. GenProbesOctree *child = memnew(GenProbesOctree);
  539. child->offset = pos;
  540. child->size = half_size;
  541. p_cell->children[i] = child;
  542. }
  543. if (half_size > 1) {
  544. //still levels missing
  545. _plot_triangle_into_octree(p_cell->children[i], p_cell_size, p_triangle);
  546. }
  547. }
  548. }
  549. void LightmapGI::_gen_new_positions_from_octree(const GenProbesOctree *p_cell, float p_cell_size, const Vector<Vector3> &probe_positions, LocalVector<Vector3> &new_probe_positions, HashMap<Vector3i, bool> &positions_used, const AABB &p_bounds) {
  550. for (int i = 0; i < 8; i++) {
  551. Vector3i pos = p_cell->offset;
  552. if (i & 1) {
  553. pos.x += p_cell->size;
  554. }
  555. if (i & 2) {
  556. pos.y += p_cell->size;
  557. }
  558. if (i & 4) {
  559. pos.z += p_cell->size;
  560. }
  561. if (p_cell->size == 1 && !positions_used.has(pos)) {
  562. //new position to insert!
  563. Vector3 real_pos = p_bounds.position + Vector3(pos) * p_cell_size;
  564. //see if a user submitted probe is too close
  565. int ppcount = probe_positions.size();
  566. const Vector3 *pp = probe_positions.ptr();
  567. bool exists = false;
  568. for (int j = 0; j < ppcount; j++) {
  569. if (pp[j].is_equal_approx(real_pos)) {
  570. exists = true;
  571. break;
  572. }
  573. }
  574. if (!exists) {
  575. new_probe_positions.push_back(real_pos);
  576. }
  577. positions_used[pos] = true;
  578. }
  579. if (p_cell->children[i] != nullptr) {
  580. _gen_new_positions_from_octree(p_cell->children[i], p_cell_size, probe_positions, new_probe_positions, positions_used, p_bounds);
  581. }
  582. }
  583. }
  584. LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_path, Lightmapper::BakeStepFunc p_bake_step, void *p_bake_userdata) {
  585. if (p_image_data_path.is_empty()) {
  586. if (get_light_data().is_null()) {
  587. return BAKE_ERROR_NO_SAVE_PATH;
  588. }
  589. p_image_data_path = get_light_data()->get_path();
  590. if (!p_image_data_path.is_resource_file()) {
  591. return BAKE_ERROR_NO_SAVE_PATH;
  592. }
  593. }
  594. Ref<Lightmapper> lightmapper = Lightmapper::create();
  595. ERR_FAIL_COND_V(lightmapper.is_null(), BAKE_ERROR_NO_LIGHTMAPPER);
  596. BakeStepUD bsud;
  597. bsud.func = p_bake_step;
  598. bsud.ud = p_bake_userdata;
  599. bsud.from_percent = 0.2;
  600. bsud.to_percent = 0.8;
  601. if (p_bake_step) {
  602. p_bake_step(0.0, RTR("Finding meshes, lights and probes"), p_bake_userdata, true);
  603. }
  604. /* STEP 1, FIND MESHES, LIGHTS AND PROBES */
  605. Vector<Lightmapper::MeshData> mesh_data;
  606. Vector<LightsFound> lights_found;
  607. Vector<Vector3> probes_found;
  608. AABB bounds;
  609. {
  610. Vector<MeshesFound> meshes_found;
  611. _find_meshes_and_lights(p_from_node ? p_from_node : get_parent(), meshes_found, lights_found, probes_found);
  612. if (meshes_found.size() == 0) {
  613. return BAKE_ERROR_NO_MESHES;
  614. }
  615. // create mesh data for insert
  616. //get the base material textures, help compute atlas size and bounds
  617. for (int m_i = 0; m_i < meshes_found.size(); m_i++) {
  618. if (p_bake_step) {
  619. float p = (float)(m_i) / meshes_found.size();
  620. p_bake_step(p * 0.1, vformat(RTR("Preparing geometry %d/%d"), m_i, meshes_found.size()), p_bake_userdata, false);
  621. }
  622. MeshesFound &mf = meshes_found.write[m_i];
  623. Size2i lightmap_size = mf.mesh->get_lightmap_size_hint() * mf.lightmap_scale;
  624. Vector<RID> overrides;
  625. overrides.resize(mf.overrides.size());
  626. for (int i = 0; i < mf.overrides.size(); i++) {
  627. if (mf.overrides[i].is_valid()) {
  628. overrides.write[i] = mf.overrides[i]->get_rid();
  629. }
  630. }
  631. TypedArray<Image> images = RS::get_singleton()->bake_render_uv2(mf.mesh->get_rid(), overrides, lightmap_size);
  632. ERR_FAIL_COND_V(images.is_empty(), BAKE_ERROR_CANT_CREATE_IMAGE);
  633. Ref<Image> albedo = images[RS::BAKE_CHANNEL_ALBEDO_ALPHA];
  634. Ref<Image> orm = images[RS::BAKE_CHANNEL_ORM];
  635. //multiply albedo by metal
  636. Lightmapper::MeshData md;
  637. {
  638. Dictionary d;
  639. d["path"] = mf.node_path;
  640. if (mf.subindex >= 0) {
  641. d["subindex"] = mf.subindex;
  642. }
  643. md.userdata = d;
  644. }
  645. {
  646. if (albedo->get_format() != Image::FORMAT_RGBA8) {
  647. albedo->convert(Image::FORMAT_RGBA8);
  648. }
  649. if (orm->get_format() != Image::FORMAT_RGBA8) {
  650. orm->convert(Image::FORMAT_RGBA8);
  651. }
  652. Vector<uint8_t> albedo_alpha = albedo->get_data();
  653. Vector<uint8_t> orm_data = orm->get_data();
  654. Vector<uint8_t> albedom;
  655. uint32_t len = albedo_alpha.size();
  656. albedom.resize(len);
  657. const uint8_t *r_aa = albedo_alpha.ptr();
  658. const uint8_t *r_orm = orm_data.ptr();
  659. uint8_t *w_albedo = albedom.ptrw();
  660. for (uint32_t i = 0; i < len; i += 4) {
  661. w_albedo[i + 0] = uint8_t(CLAMP(float(r_aa[i + 0]) * (1.0 - float(r_orm[i + 2] / 255.0)), 0, 255));
  662. w_albedo[i + 1] = uint8_t(CLAMP(float(r_aa[i + 1]) * (1.0 - float(r_orm[i + 2] / 255.0)), 0, 255));
  663. w_albedo[i + 2] = uint8_t(CLAMP(float(r_aa[i + 2]) * (1.0 - float(r_orm[i + 2] / 255.0)), 0, 255));
  664. w_albedo[i + 3] = 255;
  665. }
  666. md.albedo_on_uv2.instantiate();
  667. md.albedo_on_uv2->create(lightmap_size.width, lightmap_size.height, false, Image::FORMAT_RGBA8, albedom);
  668. }
  669. md.emission_on_uv2 = images[RS::BAKE_CHANNEL_EMISSION];
  670. if (md.emission_on_uv2->get_format() != Image::FORMAT_RGBAH) {
  671. md.emission_on_uv2->convert(Image::FORMAT_RGBAH);
  672. }
  673. //get geometry
  674. Basis normal_xform = mf.xform.basis.inverse().transposed();
  675. for (int i = 0; i < mf.mesh->get_surface_count(); i++) {
  676. if (mf.mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  677. continue;
  678. }
  679. Array a = mf.mesh->surface_get_arrays(i);
  680. Vector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  681. const Vector3 *vr = vertices.ptr();
  682. Vector<Vector2> uv = a[Mesh::ARRAY_TEX_UV2];
  683. const Vector2 *uvr = nullptr;
  684. Vector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
  685. const Vector3 *nr = nullptr;
  686. Vector<int> index = a[Mesh::ARRAY_INDEX];
  687. ERR_CONTINUE(uv.size() == 0);
  688. ERR_CONTINUE(normals.size() == 0);
  689. uvr = uv.ptr();
  690. nr = normals.ptr();
  691. int facecount;
  692. const int *ir = nullptr;
  693. if (index.size()) {
  694. facecount = index.size() / 3;
  695. ir = index.ptr();
  696. } else {
  697. facecount = vertices.size() / 3;
  698. }
  699. for (int j = 0; j < facecount; j++) {
  700. uint32_t vidx[3];
  701. if (ir) {
  702. for (int k = 0; k < 3; k++) {
  703. vidx[k] = ir[j * 3 + k];
  704. }
  705. } else {
  706. for (int k = 0; k < 3; k++) {
  707. vidx[k] = j * 3 + k;
  708. }
  709. }
  710. for (int k = 0; k < 3; k++) {
  711. Vector3 v = mf.xform.xform(vr[vidx[k]]);
  712. if (bounds == AABB()) {
  713. bounds.position = v;
  714. } else {
  715. bounds.expand_to(v);
  716. }
  717. md.points.push_back(v);
  718. md.uv2.push_back(uvr[vidx[k]]);
  719. md.normal.push_back(normal_xform.xform(nr[vidx[k]]).normalized());
  720. }
  721. }
  722. }
  723. mesh_data.push_back(md);
  724. }
  725. }
  726. /* STEP 2, CREATE PROBES */
  727. if (p_bake_step) {
  728. p_bake_step(0.3, RTR("Creating probes"), p_bake_userdata, true);
  729. }
  730. //bounds need to include the user probes
  731. for (int i = 0; i < probes_found.size(); i++) {
  732. bounds.expand_to(probes_found[i]);
  733. }
  734. bounds.grow_by(bounds.size.length() * 0.001);
  735. if (gen_probes == GENERATE_PROBES_DISABLED) {
  736. // generate 8 probes on bound endpoints
  737. for (int i = 0; i < 8; i++) {
  738. probes_found.push_back(bounds.get_endpoint(i));
  739. }
  740. } else {
  741. // detect probes from geometry
  742. static const int subdiv_values[6] = { 0, 4, 8, 16, 32 };
  743. int subdiv = subdiv_values[gen_probes];
  744. float subdiv_cell_size;
  745. Vector3i bound_limit;
  746. {
  747. int longest_axis = bounds.get_longest_axis_index();
  748. subdiv_cell_size = bounds.size[longest_axis] / subdiv;
  749. int axis_n1 = (longest_axis + 1) % 3;
  750. int axis_n2 = (longest_axis + 2) % 3;
  751. bound_limit[longest_axis] = subdiv;
  752. bound_limit[axis_n1] = int(Math::ceil(bounds.size[axis_n1] / subdiv_cell_size));
  753. bound_limit[axis_n2] = int(Math::ceil(bounds.size[axis_n2] / subdiv_cell_size));
  754. //compensate bounds
  755. bounds.size[axis_n1] = bound_limit[axis_n1] * subdiv_cell_size;
  756. bounds.size[axis_n2] = bound_limit[axis_n2] * subdiv_cell_size;
  757. }
  758. GenProbesOctree octree;
  759. octree.size = subdiv;
  760. for (int i = 0; i < mesh_data.size(); i++) {
  761. if (p_bake_step) {
  762. float p = (float)(i) / mesh_data.size();
  763. p_bake_step(0.3 + p * 0.1, vformat(RTR("Creating probes from mesh %d/%d"), i, mesh_data.size()), p_bake_userdata, false);
  764. }
  765. for (int j = 0; j < mesh_data[i].points.size(); j += 3) {
  766. Vector3 points[3] = { mesh_data[i].points[j + 0] - bounds.position, mesh_data[i].points[j + 1] - bounds.position, mesh_data[i].points[j + 2] - bounds.position };
  767. _plot_triangle_into_octree(&octree, subdiv_cell_size, points);
  768. }
  769. }
  770. LocalVector<Vector3> new_probe_positions;
  771. HashMap<Vector3i, bool> positions_used;
  772. for (uint32_t i = 0; i < 8; i++) { //insert bounding endpoints
  773. Vector3i pos;
  774. if (i & 1) {
  775. pos.x += bound_limit.x;
  776. }
  777. if (i & 2) {
  778. pos.y += bound_limit.y;
  779. }
  780. if (i & 4) {
  781. pos.z += bound_limit.z;
  782. }
  783. positions_used[pos] = true;
  784. Vector3 real_pos = bounds.position + Vector3(pos) * subdiv_cell_size; //use same formula for numerical stability
  785. new_probe_positions.push_back(real_pos);
  786. }
  787. //skip first level, since probes are always added at bounds endpoints anyway (code above this)
  788. for (int i = 0; i < 8; i++) {
  789. if (octree.children[i]) {
  790. _gen_new_positions_from_octree(octree.children[i], subdiv_cell_size, probes_found, new_probe_positions, positions_used, bounds);
  791. }
  792. }
  793. for (uint32_t i = 0; i < new_probe_positions.size(); i++) {
  794. probes_found.push_back(new_probe_positions[i]);
  795. }
  796. }
  797. // Add everything to lightmapper
  798. if (p_bake_step) {
  799. p_bake_step(0.4, RTR("Preparing Lightmapper"), p_bake_userdata, true);
  800. }
  801. {
  802. for (int i = 0; i < mesh_data.size(); i++) {
  803. lightmapper->add_mesh(mesh_data[i]);
  804. }
  805. for (int i = 0; i < lights_found.size(); i++) {
  806. Light3D *light = lights_found[i].light;
  807. Transform3D xf = lights_found[i].xform;
  808. Color linear_color = light->get_color().srgb_to_linear();
  809. if (Object::cast_to<DirectionalLight3D>(light)) {
  810. DirectionalLight3D *l = Object::cast_to<DirectionalLight3D>(light);
  811. lightmapper->add_directional_light(light->get_bake_mode() == Light3D::BAKE_STATIC, -xf.basis.get_column(Vector3::AXIS_Z).normalized(), linear_color, l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_SIZE), l->get_param(Light3D::PARAM_SHADOW_BLUR));
  812. } else if (Object::cast_to<OmniLight3D>(light)) {
  813. OmniLight3D *l = Object::cast_to<OmniLight3D>(light);
  814. lightmapper->add_omni_light(light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, linear_color, l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_RANGE), l->get_param(Light3D::PARAM_ATTENUATION), l->get_param(Light3D::PARAM_SIZE), l->get_param(Light3D::PARAM_SHADOW_BLUR));
  815. } else if (Object::cast_to<SpotLight3D>(light)) {
  816. SpotLight3D *l = Object::cast_to<SpotLight3D>(light);
  817. lightmapper->add_spot_light(light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, -xf.basis.get_column(Vector3::AXIS_Z).normalized(), linear_color, l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_RANGE), l->get_param(Light3D::PARAM_ATTENUATION), l->get_param(Light3D::PARAM_SPOT_ANGLE), l->get_param(Light3D::PARAM_SPOT_ATTENUATION), l->get_param(Light3D::PARAM_SIZE), l->get_param(Light3D::PARAM_SHADOW_BLUR));
  818. }
  819. }
  820. for (int i = 0; i < probes_found.size(); i++) {
  821. lightmapper->add_probe(probes_found[i]);
  822. }
  823. }
  824. Ref<Image> environment_image;
  825. Basis environment_transform;
  826. // Add everything to lightmapper
  827. if (environment_mode != ENVIRONMENT_MODE_DISABLED) {
  828. if (p_bake_step) {
  829. p_bake_step(4.1, RTR("Preparing Environment"), p_bake_userdata, true);
  830. }
  831. environment_transform = get_global_transform().basis;
  832. switch (environment_mode) {
  833. case ENVIRONMENT_MODE_DISABLED: {
  834. //nothing
  835. } break;
  836. case ENVIRONMENT_MODE_SCENE: {
  837. Ref<World3D> world = get_world_3d();
  838. if (world.is_valid()) {
  839. Ref<Environment> env = world->get_environment();
  840. if (env.is_null()) {
  841. env = world->get_fallback_environment();
  842. }
  843. if (env.is_valid()) {
  844. environment_image = RS::get_singleton()->environment_bake_panorama(env->get_rid(), true, Size2i(128, 64));
  845. }
  846. }
  847. } break;
  848. case ENVIRONMENT_MODE_CUSTOM_SKY: {
  849. if (environment_custom_sky.is_valid()) {
  850. environment_image = RS::get_singleton()->sky_bake_panorama(environment_custom_sky->get_rid(), environment_custom_energy, true, Size2i(128, 64));
  851. }
  852. } break;
  853. case ENVIRONMENT_MODE_CUSTOM_COLOR: {
  854. environment_image.instantiate();
  855. environment_image->create(128, 64, false, Image::FORMAT_RGBAF);
  856. Color c = environment_custom_color;
  857. c.r *= environment_custom_energy;
  858. c.g *= environment_custom_energy;
  859. c.b *= environment_custom_energy;
  860. environment_image->fill(c);
  861. } break;
  862. }
  863. }
  864. Lightmapper::BakeError bake_err = lightmapper->bake(Lightmapper::BakeQuality(bake_quality), use_denoiser, bounces, bias, max_texture_size, directional, Lightmapper::GenerateProbes(gen_probes), environment_image, environment_transform, _lightmap_bake_step_function, &bsud);
  865. if (bake_err == Lightmapper::BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES) {
  866. return BAKE_ERROR_MESHES_INVALID;
  867. }
  868. /* POSTBAKE: Save Light Data */
  869. Ref<LightmapGIData> data;
  870. if (get_light_data().is_valid()) {
  871. data = get_light_data();
  872. set_light_data(Ref<LightmapGIData>()); //clear
  873. data->clear();
  874. } else {
  875. data.instantiate();
  876. }
  877. Ref<Texture2DArray> texture;
  878. {
  879. Vector<Ref<Image>> images;
  880. for (int i = 0; i < lightmapper->get_bake_texture_count(); i++) {
  881. images.push_back(lightmapper->get_bake_texture(i));
  882. }
  883. texture.instantiate();
  884. texture->create_from_images(images);
  885. }
  886. data->set_light_texture(texture);
  887. data->set_uses_spherical_harmonics(directional);
  888. for (int i = 0; i < lightmapper->get_bake_mesh_count(); i++) {
  889. Dictionary d = lightmapper->get_bake_mesh_userdata(i);
  890. NodePath np = d["path"];
  891. int32_t subindex = -1;
  892. if (d.has("subindex")) {
  893. subindex = d["subindex"];
  894. }
  895. Rect2 uv_scale = lightmapper->get_bake_mesh_uv_scale(i);
  896. int slice_index = lightmapper->get_bake_mesh_texture_slice(i);
  897. data->add_user(np, uv_scale, slice_index, subindex);
  898. }
  899. {
  900. // create tetrahedrons
  901. Vector<Vector3> points;
  902. Vector<Color> sh;
  903. points.resize(lightmapper->get_bake_probe_count());
  904. sh.resize(lightmapper->get_bake_probe_count() * 9);
  905. for (int i = 0; i < lightmapper->get_bake_probe_count(); i++) {
  906. points.write[i] = lightmapper->get_bake_probe_point(i);
  907. Vector<Color> colors = lightmapper->get_bake_probe_sh(i);
  908. ERR_CONTINUE(colors.size() != 9);
  909. for (int j = 0; j < 9; j++) {
  910. sh.write[i * 9 + j] = colors[j];
  911. }
  912. }
  913. //Obtain solved simplices
  914. if (p_bake_step) {
  915. p_bake_step(0.8, RTR("Generating Probe Volumes"), p_bake_userdata, true);
  916. }
  917. Vector<Delaunay3D::OutputSimplex> solved_simplices = Delaunay3D::tetrahedralize(points);
  918. LocalVector<BSPSimplex> bsp_simplices;
  919. LocalVector<Plane> bsp_planes;
  920. LocalVector<int32_t> bsp_simplex_indices;
  921. PackedInt32Array tetrahedrons;
  922. for (int i = 0; i < solved_simplices.size(); i++) {
  923. //Prepare a special representation of the simplex, which uses a BSP Tree
  924. BSPSimplex bsp_simplex;
  925. for (int j = 0; j < 4; j++) {
  926. bsp_simplex.vertices[j] = solved_simplices[i].points[j];
  927. }
  928. for (int j = 0; j < 4; j++) {
  929. static const int face_order[4][3] = {
  930. { 0, 1, 2 },
  931. { 0, 2, 3 },
  932. { 0, 1, 3 },
  933. { 1, 2, 3 }
  934. };
  935. Vector3 a = points[solved_simplices[i].points[face_order[j][0]]];
  936. Vector3 b = points[solved_simplices[i].points[face_order[j][1]]];
  937. Vector3 c = points[solved_simplices[i].points[face_order[j][2]]];
  938. //store planes in an array, but ensure they are reused, to speed up processing
  939. Plane p(a, b, c);
  940. int plane_index = -1;
  941. for (uint32_t k = 0; k < bsp_planes.size(); k++) {
  942. if (bsp_planes[k].is_equal_approx_any_side(p)) {
  943. plane_index = k;
  944. break;
  945. }
  946. }
  947. if (plane_index == -1) {
  948. plane_index = bsp_planes.size();
  949. bsp_planes.push_back(p);
  950. }
  951. bsp_simplex.planes[j] = plane_index;
  952. //also fill simplex array
  953. tetrahedrons.push_back(solved_simplices[i].points[j]);
  954. }
  955. bsp_simplex_indices.push_back(bsp_simplices.size());
  956. bsp_simplices.push_back(bsp_simplex);
  957. }
  958. //#define DEBUG_SIMPLICES_AS_OBJ_FILE
  959. #ifdef DEBUG_SIMPLICES_AS_OBJ_FILE
  960. {
  961. Ref<FileAccess> f = FileAccess::open("res://bsp.obj", FileAccess::WRITE);
  962. for (uint32_t i = 0; i < bsp_simplices.size(); i++) {
  963. f->store_line("o Simplex" + itos(i));
  964. for (int j = 0; j < 4; j++) {
  965. f->store_line(vformat("v %f %f %f", points[bsp_simplices[i].vertices[j]].x, points[bsp_simplices[i].vertices[j]].y, points[bsp_simplices[i].vertices[j]].z));
  966. }
  967. static const int face_order[4][3] = {
  968. { 1, 2, 3 },
  969. { 1, 3, 4 },
  970. { 1, 2, 4 },
  971. { 2, 3, 4 }
  972. };
  973. for (int j = 0; j < 4; j++) {
  974. f->store_line(vformat("f %d %d %d", 4 * i + face_order[j][0], 4 * i + face_order[j][1], 4 * i + face_order[j][2]));
  975. }
  976. }
  977. }
  978. #endif
  979. LocalVector<BSPNode> bsp_nodes;
  980. LocalVector<int32_t> planes_tested;
  981. planes_tested.resize(bsp_planes.size());
  982. for (uint32_t i = 0; i < planes_tested.size(); i++) {
  983. planes_tested[i] = 0x7FFFFFFF;
  984. }
  985. if (p_bake_step) {
  986. p_bake_step(0.9, RTR("Generating Probe Acceleration Structures"), p_bake_userdata, true);
  987. }
  988. _compute_bsp_tree(points, bsp_planes, planes_tested, bsp_simplices, bsp_simplex_indices, bsp_nodes);
  989. PackedInt32Array bsp_array;
  990. bsp_array.resize(bsp_nodes.size() * 6); // six 32 bits values used for each BSP node
  991. {
  992. float *fptr = (float *)bsp_array.ptrw();
  993. int32_t *iptr = (int32_t *)bsp_array.ptrw();
  994. for (uint32_t i = 0; i < bsp_nodes.size(); i++) {
  995. fptr[i * 6 + 0] = bsp_nodes[i].plane.normal.x;
  996. fptr[i * 6 + 1] = bsp_nodes[i].plane.normal.y;
  997. fptr[i * 6 + 2] = bsp_nodes[i].plane.normal.z;
  998. fptr[i * 6 + 3] = bsp_nodes[i].plane.d;
  999. iptr[i * 6 + 4] = bsp_nodes[i].over;
  1000. iptr[i * 6 + 5] = bsp_nodes[i].under;
  1001. }
  1002. //#define DEBUG_BSP_TREE
  1003. #ifdef DEBUG_BSP_TREE
  1004. Ref<FileAccess> f = FileAccess::open("res://bsp.txt", FileAccess::WRITE);
  1005. for (uint32_t i = 0; i < bsp_nodes.size(); i++) {
  1006. f->store_line(itos(i) + " - plane: " + bsp_nodes[i].plane + " over: " + itos(bsp_nodes[i].over) + " under: " + itos(bsp_nodes[i].under));
  1007. }
  1008. #endif
  1009. }
  1010. /* Obtain the colors from the images, they will be re-created as cubemaps on the server, depending on the driver */
  1011. data->set_capture_data(bounds, interior, points, sh, tetrahedrons, bsp_array);
  1012. /* Compute a BSP tree of the simplices, so it's easy to find the exact one */
  1013. }
  1014. data->set_path(p_image_data_path);
  1015. Error err = ResourceSaver::save(data);
  1016. if (err != OK) {
  1017. return BAKE_ERROR_CANT_CREATE_IMAGE;
  1018. }
  1019. set_light_data(data);
  1020. return BAKE_ERROR_OK;
  1021. }
  1022. void LightmapGI::_notification(int p_what) {
  1023. switch (p_what) {
  1024. case NOTIFICATION_POST_ENTER_TREE: {
  1025. if (light_data.is_valid()) {
  1026. _assign_lightmaps();
  1027. }
  1028. } break;
  1029. case NOTIFICATION_EXIT_TREE: {
  1030. if (light_data.is_valid()) {
  1031. _clear_lightmaps();
  1032. }
  1033. } break;
  1034. }
  1035. }
  1036. void LightmapGI::_assign_lightmaps() {
  1037. ERR_FAIL_COND(!light_data.is_valid());
  1038. for (int i = 0; i < light_data->get_user_count(); i++) {
  1039. Node *node = get_node(light_data->get_user_path(i));
  1040. int instance_idx = light_data->get_user_sub_instance(i);
  1041. if (instance_idx >= 0) {
  1042. RID instance = node->call("get_bake_mesh_instance", instance_idx);
  1043. if (instance.is_valid()) {
  1044. RS::get_singleton()->instance_geometry_set_lightmap(instance, get_instance(), light_data->get_user_lightmap_uv_scale(i), light_data->get_user_lightmap_slice_index(i));
  1045. }
  1046. } else {
  1047. VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(node);
  1048. ERR_CONTINUE(!vi);
  1049. RS::get_singleton()->instance_geometry_set_lightmap(vi->get_instance(), get_instance(), light_data->get_user_lightmap_uv_scale(i), light_data->get_user_lightmap_slice_index(i));
  1050. }
  1051. }
  1052. }
  1053. void LightmapGI::_clear_lightmaps() {
  1054. ERR_FAIL_COND(!light_data.is_valid());
  1055. for (int i = 0; i < light_data->get_user_count(); i++) {
  1056. Node *node = get_node(light_data->get_user_path(i));
  1057. int instance_idx = light_data->get_user_sub_instance(i);
  1058. if (instance_idx >= 0) {
  1059. RID instance = node->call("get_bake_mesh_instance", instance_idx);
  1060. if (instance.is_valid()) {
  1061. RS::get_singleton()->instance_geometry_set_lightmap(instance, RID(), Rect2(), 0);
  1062. }
  1063. } else {
  1064. VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(node);
  1065. ERR_CONTINUE(!vi);
  1066. RS::get_singleton()->instance_geometry_set_lightmap(vi->get_instance(), RID(), Rect2(), 0);
  1067. }
  1068. }
  1069. }
  1070. void LightmapGI::set_light_data(const Ref<LightmapGIData> &p_data) {
  1071. if (light_data.is_valid()) {
  1072. if (is_inside_tree()) {
  1073. _clear_lightmaps();
  1074. }
  1075. set_base(RID());
  1076. }
  1077. light_data = p_data;
  1078. if (light_data.is_valid()) {
  1079. set_base(light_data->get_rid());
  1080. if (is_inside_tree()) {
  1081. _assign_lightmaps();
  1082. }
  1083. }
  1084. update_gizmos();
  1085. }
  1086. Ref<LightmapGIData> LightmapGI::get_light_data() const {
  1087. return light_data;
  1088. }
  1089. void LightmapGI::set_bake_quality(BakeQuality p_quality) {
  1090. bake_quality = p_quality;
  1091. }
  1092. LightmapGI::BakeQuality LightmapGI::get_bake_quality() const {
  1093. return bake_quality;
  1094. }
  1095. AABB LightmapGI::get_aabb() const {
  1096. return AABB();
  1097. }
  1098. void LightmapGI::set_use_denoiser(bool p_enable) {
  1099. use_denoiser = p_enable;
  1100. }
  1101. bool LightmapGI::is_using_denoiser() const {
  1102. return use_denoiser;
  1103. }
  1104. void LightmapGI::set_directional(bool p_enable) {
  1105. directional = p_enable;
  1106. }
  1107. bool LightmapGI::is_directional() const {
  1108. return directional;
  1109. }
  1110. void LightmapGI::set_interior(bool p_enable) {
  1111. interior = p_enable;
  1112. }
  1113. bool LightmapGI::is_interior() const {
  1114. return interior;
  1115. }
  1116. void LightmapGI::set_environment_mode(EnvironmentMode p_mode) {
  1117. environment_mode = p_mode;
  1118. notify_property_list_changed();
  1119. }
  1120. LightmapGI::EnvironmentMode LightmapGI::get_environment_mode() const {
  1121. return environment_mode;
  1122. }
  1123. void LightmapGI::set_environment_custom_sky(const Ref<Sky> &p_sky) {
  1124. environment_custom_sky = p_sky;
  1125. }
  1126. Ref<Sky> LightmapGI::get_environment_custom_sky() const {
  1127. return environment_custom_sky;
  1128. }
  1129. void LightmapGI::set_environment_custom_color(const Color &p_color) {
  1130. environment_custom_color = p_color;
  1131. }
  1132. Color LightmapGI::get_environment_custom_color() const {
  1133. return environment_custom_color;
  1134. }
  1135. void LightmapGI::set_environment_custom_energy(float p_energy) {
  1136. environment_custom_energy = p_energy;
  1137. }
  1138. float LightmapGI::get_environment_custom_energy() const {
  1139. return environment_custom_energy;
  1140. }
  1141. void LightmapGI::set_bounces(int p_bounces) {
  1142. ERR_FAIL_COND(p_bounces < 0 || p_bounces > 16);
  1143. bounces = p_bounces;
  1144. }
  1145. int LightmapGI::get_bounces() const {
  1146. return bounces;
  1147. }
  1148. void LightmapGI::set_bias(float p_bias) {
  1149. ERR_FAIL_COND(p_bias < 0.00001);
  1150. bias = p_bias;
  1151. }
  1152. float LightmapGI::get_bias() const {
  1153. return bias;
  1154. }
  1155. void LightmapGI::set_max_texture_size(int p_size) {
  1156. ERR_FAIL_COND(p_size < 2048);
  1157. max_texture_size = p_size;
  1158. }
  1159. int LightmapGI::get_max_texture_size() const {
  1160. return max_texture_size;
  1161. }
  1162. void LightmapGI::set_generate_probes(GenerateProbes p_generate_probes) {
  1163. gen_probes = p_generate_probes;
  1164. }
  1165. LightmapGI::GenerateProbes LightmapGI::get_generate_probes() const {
  1166. return gen_probes;
  1167. }
  1168. void LightmapGI::_validate_property(PropertyInfo &property) const {
  1169. if (property.name == "environment_custom_sky" && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
  1170. property.usage = PROPERTY_USAGE_NONE;
  1171. }
  1172. if (property.name == "environment_custom_color" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR) {
  1173. property.usage = PROPERTY_USAGE_NONE;
  1174. }
  1175. if (property.name == "environment_custom_energy" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
  1176. property.usage = PROPERTY_USAGE_NONE;
  1177. }
  1178. VisualInstance3D::_validate_property(property);
  1179. }
  1180. void LightmapGI::_bind_methods() {
  1181. ClassDB::bind_method(D_METHOD("set_light_data", "data"), &LightmapGI::set_light_data);
  1182. ClassDB::bind_method(D_METHOD("get_light_data"), &LightmapGI::get_light_data);
  1183. ClassDB::bind_method(D_METHOD("set_bake_quality", "bake_quality"), &LightmapGI::set_bake_quality);
  1184. ClassDB::bind_method(D_METHOD("get_bake_quality"), &LightmapGI::get_bake_quality);
  1185. ClassDB::bind_method(D_METHOD("set_bounces", "bounces"), &LightmapGI::set_bounces);
  1186. ClassDB::bind_method(D_METHOD("get_bounces"), &LightmapGI::get_bounces);
  1187. ClassDB::bind_method(D_METHOD("set_generate_probes", "subdivision"), &LightmapGI::set_generate_probes);
  1188. ClassDB::bind_method(D_METHOD("get_generate_probes"), &LightmapGI::get_generate_probes);
  1189. ClassDB::bind_method(D_METHOD("set_bias", "bias"), &LightmapGI::set_bias);
  1190. ClassDB::bind_method(D_METHOD("get_bias"), &LightmapGI::get_bias);
  1191. ClassDB::bind_method(D_METHOD("set_environment_mode", "mode"), &LightmapGI::set_environment_mode);
  1192. ClassDB::bind_method(D_METHOD("get_environment_mode"), &LightmapGI::get_environment_mode);
  1193. ClassDB::bind_method(D_METHOD("set_environment_custom_sky", "sky"), &LightmapGI::set_environment_custom_sky);
  1194. ClassDB::bind_method(D_METHOD("get_environment_custom_sky"), &LightmapGI::get_environment_custom_sky);
  1195. ClassDB::bind_method(D_METHOD("set_environment_custom_color", "color"), &LightmapGI::set_environment_custom_color);
  1196. ClassDB::bind_method(D_METHOD("get_environment_custom_color"), &LightmapGI::get_environment_custom_color);
  1197. ClassDB::bind_method(D_METHOD("set_environment_custom_energy", "energy"), &LightmapGI::set_environment_custom_energy);
  1198. ClassDB::bind_method(D_METHOD("get_environment_custom_energy"), &LightmapGI::get_environment_custom_energy);
  1199. ClassDB::bind_method(D_METHOD("set_max_texture_size", "max_texture_size"), &LightmapGI::set_max_texture_size);
  1200. ClassDB::bind_method(D_METHOD("get_max_texture_size"), &LightmapGI::get_max_texture_size);
  1201. ClassDB::bind_method(D_METHOD("set_use_denoiser", "use_denoiser"), &LightmapGI::set_use_denoiser);
  1202. ClassDB::bind_method(D_METHOD("is_using_denoiser"), &LightmapGI::is_using_denoiser);
  1203. ClassDB::bind_method(D_METHOD("set_interior", "enable"), &LightmapGI::set_interior);
  1204. ClassDB::bind_method(D_METHOD("is_interior"), &LightmapGI::is_interior);
  1205. ClassDB::bind_method(D_METHOD("set_directional", "directional"), &LightmapGI::set_directional);
  1206. ClassDB::bind_method(D_METHOD("is_directional"), &LightmapGI::is_directional);
  1207. // ClassDB::bind_method(D_METHOD("bake", "from_node"), &LightmapGI::bake, DEFVAL(Variant()));
  1208. ADD_GROUP("Tweaks", "");
  1209. ADD_PROPERTY(PropertyInfo(Variant::INT, "quality", PROPERTY_HINT_ENUM, "Low,Medium,High,Ultra"), "set_bake_quality", "get_bake_quality");
  1210. ADD_PROPERTY(PropertyInfo(Variant::INT, "bounces", PROPERTY_HINT_RANGE, "0,16,1"), "set_bounces", "get_bounces");
  1211. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "directional"), "set_directional", "is_directional");
  1212. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior"), "set_interior", "is_interior");
  1213. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_denoiser"), "set_use_denoiser", "is_using_denoiser");
  1214. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bias", PROPERTY_HINT_RANGE, "0.00001,0.1,0.00001,or_greater"), "set_bias", "get_bias");
  1215. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_texture_size"), "set_max_texture_size", "get_max_texture_size");
  1216. ADD_GROUP("Environment", "environment_");
  1217. ADD_PROPERTY(PropertyInfo(Variant::INT, "environment_mode", PROPERTY_HINT_ENUM, "Disabled,Scene,Custom Sky,Custom Color"), "set_environment_mode", "get_environment_mode");
  1218. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "environment_custom_sky", PROPERTY_HINT_RESOURCE_TYPE, "Sky"), "set_environment_custom_sky", "get_environment_custom_sky");
  1219. ADD_PROPERTY(PropertyInfo(Variant::COLOR, "environment_custom_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_environment_custom_color", "get_environment_custom_color");
  1220. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "environment_custom_energy", PROPERTY_HINT_RANGE, "0,64,0.01"), "set_environment_custom_energy", "get_environment_custom_energy");
  1221. ADD_GROUP("Gen Probes", "generate_probes_");
  1222. ADD_PROPERTY(PropertyInfo(Variant::INT, "generate_probes_subdiv", PROPERTY_HINT_ENUM, "Disabled,4,8,16,32"), "set_generate_probes", "get_generate_probes");
  1223. ADD_GROUP("Data", "");
  1224. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "light_data", PROPERTY_HINT_RESOURCE_TYPE, "LightmapGIData"), "set_light_data", "get_light_data");
  1225. BIND_ENUM_CONSTANT(BAKE_QUALITY_LOW);
  1226. BIND_ENUM_CONSTANT(BAKE_QUALITY_MEDIUM);
  1227. BIND_ENUM_CONSTANT(BAKE_QUALITY_HIGH);
  1228. BIND_ENUM_CONSTANT(BAKE_QUALITY_ULTRA);
  1229. BIND_ENUM_CONSTANT(GENERATE_PROBES_DISABLED);
  1230. BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_4);
  1231. BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_8);
  1232. BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_16);
  1233. BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_32);
  1234. BIND_ENUM_CONSTANT(BAKE_ERROR_OK);
  1235. BIND_ENUM_CONSTANT(BAKE_ERROR_NO_LIGHTMAPPER);
  1236. BIND_ENUM_CONSTANT(BAKE_ERROR_NO_SAVE_PATH);
  1237. BIND_ENUM_CONSTANT(BAKE_ERROR_NO_MESHES);
  1238. BIND_ENUM_CONSTANT(BAKE_ERROR_MESHES_INVALID);
  1239. BIND_ENUM_CONSTANT(BAKE_ERROR_CANT_CREATE_IMAGE);
  1240. BIND_ENUM_CONSTANT(BAKE_ERROR_USER_ABORTED);
  1241. BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_DISABLED);
  1242. BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_SCENE);
  1243. BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_CUSTOM_SKY);
  1244. BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_CUSTOM_COLOR);
  1245. }
  1246. LightmapGI::LightmapGI() {
  1247. }