Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/scene/3d/lightmap_gi.cpp
20892 views
1
/**************************************************************************/
2
/* lightmap_gi.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
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
31
#include "lightmap_gi.h"
32
33
#include "core/config/project_settings.h"
34
#include "core/io/config_file.h"
35
#include "core/math/delaunay_3d.h"
36
#include "core/math/geometry_3d.h"
37
#include "core/object/object.h"
38
#include "scene/3d/lightmap_probe.h"
39
#include "scene/3d/mesh_instance_3d.h"
40
#include "scene/resources/camera_attributes.h"
41
#include "scene/resources/environment.h"
42
#include "scene/resources/image_texture.h"
43
#include "scene/resources/sky.h"
44
45
#include "modules/modules_enabled.gen.h" // For lightmapper_rd.
46
47
void LightmapGIData::add_user(const NodePath &p_path, const Rect2 &p_uv_scale, int p_slice_index, int32_t p_sub_instance) {
48
User user;
49
user.path = p_path;
50
user.uv_scale = p_uv_scale;
51
user.slice_index = p_slice_index;
52
user.sub_instance = p_sub_instance;
53
users.push_back(user);
54
}
55
56
int LightmapGIData::get_user_count() const {
57
return users.size();
58
}
59
60
NodePath LightmapGIData::get_user_path(int p_user) const {
61
ERR_FAIL_INDEX_V(p_user, users.size(), NodePath());
62
return users[p_user].path;
63
}
64
65
int32_t LightmapGIData::get_user_sub_instance(int p_user) const {
66
ERR_FAIL_INDEX_V(p_user, users.size(), -1);
67
return users[p_user].sub_instance;
68
}
69
70
Rect2 LightmapGIData::get_user_lightmap_uv_scale(int p_user) const {
71
ERR_FAIL_INDEX_V(p_user, users.size(), Rect2());
72
return users[p_user].uv_scale;
73
}
74
75
int LightmapGIData::get_user_lightmap_slice_index(int p_user) const {
76
ERR_FAIL_INDEX_V(p_user, users.size(), -1);
77
return users[p_user].slice_index;
78
}
79
80
void LightmapGIData::clear_users() {
81
users.clear();
82
}
83
84
void LightmapGIData::_set_user_data(const Array &p_data) {
85
ERR_FAIL_COND((p_data.size() % 4) != 0);
86
users.clear();
87
for (int i = 0; i < p_data.size(); i += 4) {
88
add_user(p_data[i + 0], p_data[i + 1], p_data[i + 2], p_data[i + 3]);
89
}
90
}
91
92
Array LightmapGIData::_get_user_data() const {
93
Array ret;
94
for (int i = 0; i < users.size(); i++) {
95
ret.push_back(users[i].path);
96
ret.push_back(users[i].uv_scale);
97
ret.push_back(users[i].slice_index);
98
ret.push_back(users[i].sub_instance);
99
}
100
return ret;
101
}
102
103
void LightmapGIData::set_lightmap_textures(const TypedArray<TextureLayered> &p_data) {
104
storage_light_textures = p_data;
105
if (p_data.is_empty()) {
106
combined_light_texture = Ref<TextureLayered>();
107
_reset_lightmap_textures();
108
return;
109
}
110
111
if (p_data.size() == 1) {
112
combined_light_texture = p_data[0];
113
} else {
114
Vector<Ref<Image>> images;
115
for (int i = 0; i < p_data.size(); i++) {
116
Ref<TextureLayered> texture = p_data[i];
117
ERR_FAIL_COND_MSG(texture.is_null(), vformat("Invalid TextureLayered at index %d.", i));
118
for (int j = 0; j < texture->get_layers(); j++) {
119
images.push_back(texture->get_layer_data(j));
120
}
121
}
122
123
Ref<Texture2DArray> combined_texture;
124
combined_texture.instantiate();
125
126
combined_texture->create_from_images(images);
127
combined_light_texture = combined_texture;
128
}
129
_reset_lightmap_textures();
130
}
131
132
TypedArray<TextureLayered> LightmapGIData::get_lightmap_textures() const {
133
return storage_light_textures;
134
}
135
136
void LightmapGIData::set_shadowmask_textures(const TypedArray<TextureLayered> &p_data) {
137
storage_shadowmask_textures = p_data;
138
139
if (p_data.is_empty()) {
140
combined_shadowmask_texture = Ref<TextureLayered>();
141
_reset_shadowmask_textures();
142
return;
143
}
144
145
if (p_data.size() == 1) {
146
combined_shadowmask_texture = p_data[0];
147
148
} else {
149
Vector<Ref<Image>> images;
150
for (int i = 0; i < p_data.size(); i++) {
151
Ref<TextureLayered> texture = p_data[i];
152
ERR_FAIL_COND_MSG(texture.is_null(), vformat("Invalid TextureLayered at index %d.", i));
153
for (int j = 0; j < texture->get_layers(); j++) {
154
images.push_back(texture->get_layer_data(j));
155
}
156
}
157
158
Ref<Texture2DArray> combined_texture;
159
combined_texture.instantiate();
160
161
combined_texture->create_from_images(images);
162
combined_shadowmask_texture = combined_texture;
163
}
164
165
_reset_shadowmask_textures();
166
}
167
168
TypedArray<TextureLayered> LightmapGIData::get_shadowmask_textures() const {
169
return storage_shadowmask_textures;
170
}
171
172
void LightmapGIData::clear_shadowmask_textures() {
173
RS::get_singleton()->lightmap_set_shadowmask_textures(lightmap, RID());
174
storage_shadowmask_textures.clear();
175
combined_shadowmask_texture.unref();
176
}
177
178
bool LightmapGIData::has_shadowmask_textures() {
179
return !storage_shadowmask_textures.is_empty() && combined_shadowmask_texture.is_valid();
180
}
181
182
RID LightmapGIData::get_rid() const {
183
return lightmap;
184
}
185
186
void LightmapGIData::clear() {
187
users.clear();
188
}
189
190
void LightmapGIData::_reset_lightmap_textures() {
191
RS::get_singleton()->lightmap_set_textures(lightmap, combined_light_texture.is_valid() ? combined_light_texture->get_rid() : RID(), uses_spherical_harmonics);
192
}
193
194
void LightmapGIData::_reset_shadowmask_textures() {
195
RS::get_singleton()->lightmap_set_shadowmask_textures(lightmap, combined_shadowmask_texture.is_valid() ? combined_shadowmask_texture->get_rid() : RID());
196
}
197
198
void LightmapGIData::set_uses_spherical_harmonics(bool p_enable) {
199
uses_spherical_harmonics = p_enable;
200
_reset_lightmap_textures();
201
}
202
203
bool LightmapGIData::is_using_spherical_harmonics() const {
204
return uses_spherical_harmonics;
205
}
206
207
void LightmapGIData::_set_uses_packed_directional(bool p_enable) {
208
_uses_packed_directional = p_enable;
209
}
210
211
bool LightmapGIData::_is_using_packed_directional() const {
212
return _uses_packed_directional;
213
}
214
215
void LightmapGIData::update_shadowmask_mode(ShadowmaskMode p_mode) {
216
RS::get_singleton()->lightmap_set_shadowmask_mode(lightmap, (RS::ShadowmaskMode)p_mode);
217
}
218
219
LightmapGIData::ShadowmaskMode LightmapGIData::get_shadowmask_mode() const {
220
return (ShadowmaskMode)RS::get_singleton()->lightmap_get_shadowmask_mode(lightmap);
221
}
222
223
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, float p_baked_exposure, uint32_t p_lightprobe_hash) {
224
if (p_points.size()) {
225
int pc = p_points.size();
226
ERR_FAIL_COND(pc * 9 != p_point_sh.size());
227
ERR_FAIL_COND((p_tetrahedra.size() % 4) != 0);
228
ERR_FAIL_COND((p_bsp_tree.size() % 6) != 0);
229
RS::get_singleton()->lightmap_set_probe_capture_data(lightmap, p_points, p_point_sh, p_tetrahedra, p_bsp_tree);
230
RS::get_singleton()->lightmap_set_probe_bounds(lightmap, p_bounds);
231
RS::get_singleton()->lightmap_set_probe_interior(lightmap, p_interior);
232
} else {
233
RS::get_singleton()->lightmap_set_probe_capture_data(lightmap, PackedVector3Array(), PackedColorArray(), PackedInt32Array(), PackedInt32Array());
234
RS::get_singleton()->lightmap_set_probe_bounds(lightmap, AABB());
235
RS::get_singleton()->lightmap_set_probe_interior(lightmap, false);
236
}
237
RS::get_singleton()->lightmap_set_baked_exposure_normalization(lightmap, p_baked_exposure);
238
baked_exposure = p_baked_exposure;
239
lightprobe_hash = p_lightprobe_hash;
240
interior = p_interior;
241
bounds = p_bounds;
242
}
243
244
PackedVector3Array LightmapGIData::get_capture_points() const {
245
return RS::get_singleton()->lightmap_get_probe_capture_points(lightmap);
246
}
247
248
PackedColorArray LightmapGIData::get_capture_sh() const {
249
return RS::get_singleton()->lightmap_get_probe_capture_sh(lightmap);
250
}
251
252
PackedInt32Array LightmapGIData::get_capture_tetrahedra() const {
253
return RS::get_singleton()->lightmap_get_probe_capture_tetrahedra(lightmap);
254
}
255
256
PackedInt32Array LightmapGIData::get_capture_bsp_tree() const {
257
return RS::get_singleton()->lightmap_get_probe_capture_bsp_tree(lightmap);
258
}
259
260
uint32_t LightmapGIData::get_lightprobe_hash() const {
261
return lightprobe_hash;
262
}
263
264
AABB LightmapGIData::get_capture_bounds() const {
265
return bounds;
266
}
267
268
bool LightmapGIData::is_interior() const {
269
return interior;
270
}
271
272
float LightmapGIData::get_baked_exposure() const {
273
return baked_exposure;
274
}
275
276
void LightmapGIData::_set_probe_data(const Dictionary &p_data) {
277
ERR_FAIL_COND(!p_data.has("bounds"));
278
ERR_FAIL_COND(!p_data.has("points"));
279
ERR_FAIL_COND(!p_data.has("tetrahedra"));
280
ERR_FAIL_COND(!p_data.has("bsp"));
281
ERR_FAIL_COND(!p_data.has("sh"));
282
ERR_FAIL_COND(!p_data.has("interior"));
283
ERR_FAIL_COND(!p_data.has("baked_exposure"));
284
285
uint32_t phash = 0;
286
if (p_data.has("lightprobe_hash")) { // Older versions will not have it.
287
phash = p_data["lightprobe_hash"];
288
}
289
set_capture_data(p_data["bounds"], p_data["interior"], p_data["points"], p_data["sh"], p_data["tetrahedra"], p_data["bsp"], p_data["baked_exposure"], phash);
290
}
291
292
Dictionary LightmapGIData::_get_probe_data() const {
293
Dictionary d;
294
d["bounds"] = get_capture_bounds();
295
d["points"] = get_capture_points();
296
d["tetrahedra"] = get_capture_tetrahedra();
297
d["bsp"] = get_capture_bsp_tree();
298
d["sh"] = get_capture_sh();
299
d["interior"] = is_interior();
300
d["baked_exposure"] = get_baked_exposure();
301
d["lightprobe_hash"] = lightprobe_hash;
302
return d;
303
}
304
305
#ifndef DISABLE_DEPRECATED
306
void LightmapGIData::set_light_texture(const Ref<TextureLayered> &p_light_texture) {
307
TypedArray<TextureLayered> arr = { p_light_texture };
308
set_lightmap_textures(arr);
309
}
310
311
Ref<TextureLayered> LightmapGIData::get_light_texture() const {
312
if (storage_light_textures.is_empty()) {
313
return Ref<TextureLayered>();
314
}
315
return storage_light_textures.get(0);
316
}
317
318
void LightmapGIData::_set_light_textures_data(const Array &p_data) {
319
set_lightmap_textures(p_data);
320
}
321
322
Array LightmapGIData::_get_light_textures_data() const {
323
return Array(storage_light_textures);
324
}
325
#endif
326
327
void LightmapGIData::_bind_methods() {
328
ClassDB::bind_method(D_METHOD("_set_user_data", "data"), &LightmapGIData::_set_user_data);
329
ClassDB::bind_method(D_METHOD("_get_user_data"), &LightmapGIData::_get_user_data);
330
331
ClassDB::bind_method(D_METHOD("set_lightmap_textures", "light_textures"), &LightmapGIData::set_lightmap_textures);
332
ClassDB::bind_method(D_METHOD("get_lightmap_textures"), &LightmapGIData::get_lightmap_textures);
333
334
ClassDB::bind_method(D_METHOD("set_shadowmask_textures", "shadowmask_textures"), &LightmapGIData::set_shadowmask_textures);
335
ClassDB::bind_method(D_METHOD("get_shadowmask_textures"), &LightmapGIData::get_shadowmask_textures);
336
337
ClassDB::bind_method(D_METHOD("set_uses_spherical_harmonics", "uses_spherical_harmonics"), &LightmapGIData::set_uses_spherical_harmonics);
338
ClassDB::bind_method(D_METHOD("is_using_spherical_harmonics"), &LightmapGIData::is_using_spherical_harmonics);
339
340
ClassDB::bind_method(D_METHOD("_set_uses_packed_directional", "_uses_packed_directional"), &LightmapGIData::_set_uses_packed_directional);
341
ClassDB::bind_method(D_METHOD("_is_using_packed_directional"), &LightmapGIData::_is_using_packed_directional);
342
343
ClassDB::bind_method(D_METHOD("add_user", "path", "uv_scale", "slice_index", "sub_instance"), &LightmapGIData::add_user);
344
ClassDB::bind_method(D_METHOD("get_user_count"), &LightmapGIData::get_user_count);
345
ClassDB::bind_method(D_METHOD("get_user_path", "user_idx"), &LightmapGIData::get_user_path);
346
ClassDB::bind_method(D_METHOD("clear_users"), &LightmapGIData::clear_users);
347
348
ClassDB::bind_method(D_METHOD("_set_probe_data", "data"), &LightmapGIData::_set_probe_data);
349
ClassDB::bind_method(D_METHOD("_get_probe_data"), &LightmapGIData::_get_probe_data);
350
351
ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "lightmap_textures", PROPERTY_HINT_ARRAY_TYPE, "TextureLayered", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_READ_ONLY), "set_lightmap_textures", "get_lightmap_textures");
352
ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "shadowmask_textures", PROPERTY_HINT_ARRAY_TYPE, "TextureLayered", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_READ_ONLY), "set_shadowmask_textures", "get_shadowmask_textures");
353
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");
354
ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "user_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_user_data", "_get_user_data");
355
ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "probe_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_probe_data", "_get_probe_data");
356
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "_uses_packed_directional", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_uses_packed_directional", "_is_using_packed_directional");
357
358
#ifndef DISABLE_DEPRECATED
359
ClassDB::bind_method(D_METHOD("set_light_texture", "light_texture"), &LightmapGIData::set_light_texture);
360
ClassDB::bind_method(D_METHOD("get_light_texture"), &LightmapGIData::get_light_texture);
361
362
ClassDB::bind_method(D_METHOD("_set_light_textures_data", "data"), &LightmapGIData::_set_light_textures_data);
363
ClassDB::bind_method(D_METHOD("_get_light_textures_data"), &LightmapGIData::_get_light_textures_data);
364
365
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "light_texture", PROPERTY_HINT_RESOURCE_TYPE, TextureLayered::get_class_static(), PROPERTY_USAGE_NONE), "set_light_texture", "get_light_texture");
366
ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "light_textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_INTERNAL), "_set_light_textures_data", "_get_light_textures_data");
367
#endif
368
369
BIND_ENUM_CONSTANT(SHADOWMASK_MODE_NONE);
370
BIND_ENUM_CONSTANT(SHADOWMASK_MODE_REPLACE);
371
BIND_ENUM_CONSTANT(SHADOWMASK_MODE_OVERLAY);
372
}
373
374
LightmapGIData::LightmapGIData() {
375
lightmap = RS::get_singleton()->lightmap_create();
376
}
377
378
LightmapGIData::~LightmapGIData() {
379
ERR_FAIL_NULL(RenderingServer::get_singleton());
380
RS::get_singleton()->free_rid(lightmap);
381
}
382
383
///////////////////////////
384
385
void LightmapGI::_find_meshes_and_lights(Node *p_at_node, Vector<MeshesFound> &meshes, Vector<LightsFound> &lights, Vector<Vector3> &probes) {
386
MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_at_node);
387
if (mi && mi->get_gi_mode() == GeometryInstance3D::GI_MODE_STATIC && mi->is_visible_in_tree()) {
388
Ref<Mesh> mesh = mi->get_mesh();
389
if (mesh.is_valid()) {
390
bool all_have_uv2_and_normal = true;
391
bool surfaces_found = false;
392
for (int i = 0; i < mesh->get_surface_count(); i++) {
393
if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
394
continue;
395
}
396
if (!(mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_TEX_UV2)) {
397
all_have_uv2_and_normal = false;
398
break;
399
}
400
if (!(mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_NORMAL)) {
401
all_have_uv2_and_normal = false;
402
break;
403
}
404
surfaces_found = true;
405
}
406
407
if (surfaces_found && all_have_uv2_and_normal) {
408
//READY TO BAKE! size hint could be computed if not found, actually..
409
410
MeshesFound mf;
411
mf.xform = get_global_transform().affine_inverse() * mi->get_global_transform();
412
mf.node_path = get_path_to(mi);
413
mf.subindex = -1;
414
mf.mesh = mesh;
415
mf.lightmap_scale = mi->get_lightmap_texel_scale();
416
417
Ref<Material> all_override = mi->get_material_override();
418
for (int i = 0; i < mesh->get_surface_count(); i++) {
419
if (all_override.is_valid()) {
420
mf.overrides.push_back(all_override);
421
} else {
422
mf.overrides.push_back(mi->get_surface_override_material(i));
423
}
424
}
425
426
meshes.push_back(mf);
427
}
428
}
429
}
430
431
Node3D *s = Object::cast_to<Node3D>(p_at_node);
432
433
if (!mi && s) {
434
Array bmeshes = p_at_node->call("get_bake_meshes");
435
if (bmeshes.size() && (bmeshes.size() & 1) == 0) {
436
Transform3D xf = get_global_transform().affine_inverse() * s->get_global_transform();
437
for (int i = 0; i < bmeshes.size(); i += 2) {
438
Ref<Mesh> mesh = bmeshes[i];
439
if (mesh.is_null()) {
440
continue;
441
}
442
443
MeshesFound mf;
444
445
Transform3D mesh_xf = bmeshes[i + 1];
446
mf.xform = xf * mesh_xf;
447
mf.node_path = get_path_to(s);
448
mf.subindex = i / 2;
449
mf.lightmap_scale = 1.0;
450
mf.mesh = mesh;
451
452
meshes.push_back(mf);
453
}
454
}
455
}
456
457
Light3D *light = Object::cast_to<Light3D>(p_at_node);
458
459
if (light && light->get_bake_mode() != Light3D::BAKE_DISABLED) {
460
LightsFound lf;
461
lf.xform = get_global_transform().affine_inverse() * light->get_global_transform();
462
lf.light = light;
463
lights.push_back(lf);
464
}
465
466
LightmapProbe *probe = Object::cast_to<LightmapProbe>(p_at_node);
467
468
if (probe) {
469
Transform3D xf = get_global_transform().affine_inverse() * probe->get_global_transform();
470
probes.push_back(xf.origin);
471
}
472
473
for (int i = 0; i < p_at_node->get_child_count(); i++) {
474
Node *child = p_at_node->get_child(i);
475
if (!child->get_owner()) {
476
continue; //maybe a helper
477
}
478
479
_find_meshes_and_lights(child, meshes, lights, probes);
480
}
481
}
482
483
int LightmapGI::_bsp_get_simplex_side(const LocalVector<Vector3> &p_points, const LocalVector<BSPSimplex> &p_simplices, const Plane &p_plane, uint32_t p_simplex) const {
484
int over = 0;
485
int under = 0;
486
const BSPSimplex &s = p_simplices[p_simplex];
487
for (int i = 0; i < 4; i++) {
488
const Vector3 v = p_points[s.vertices[i]];
489
// The tolerance used here comes from experiments on scenes up to
490
// 1000x1000x100 meters. If it's any smaller, some simplices will
491
// appear to self-intersect due to a lack of precision in Plane.
492
if (p_plane.has_point(v, 1.0 / (1 << 13))) {
493
// Coplanar.
494
} else if (p_plane.is_point_over(v)) {
495
over++;
496
} else {
497
under++;
498
}
499
}
500
501
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
502
if (under == 0) {
503
return 1; // all over
504
} else if (over == 0) {
505
return -1; // all under
506
} else {
507
return 0; // crossing
508
}
509
}
510
511
//#define DEBUG_BSP
512
513
int32_t LightmapGI::_compute_bsp_tree(const LocalVector<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) {
514
ERR_FAIL_COND_V(p_simplex_indices.size() < 2, -1);
515
516
int32_t node_index = (int32_t)bsp_nodes.size();
517
bsp_nodes.push_back(BSPNode());
518
519
//test with all the simplex planes
520
Plane best_plane;
521
float best_plane_score = -1.0;
522
523
for (const int idx : p_simplex_indices) {
524
const BSPSimplex &s = p_simplices[idx];
525
for (int j = 0; j < 4; j++) {
526
uint32_t plane_index = s.planes[j];
527
if (planes_tested[plane_index] == node_index) {
528
continue; //tested this plane already
529
}
530
531
planes_tested[plane_index] = node_index;
532
533
static const int face_order[4][3] = {
534
{ 0, 1, 2 },
535
{ 0, 2, 3 },
536
{ 0, 1, 3 },
537
{ 1, 2, 3 }
538
};
539
540
// despite getting rid of plane duplicates, we should still use here the actual plane to avoid numerical error
541
// from thinking this same simplex is intersecting rather than on a side
542
Vector3 v0 = p_points[s.vertices[face_order[j][0]]];
543
Vector3 v1 = p_points[s.vertices[face_order[j][1]]];
544
Vector3 v2 = p_points[s.vertices[face_order[j][2]]];
545
546
Plane plane(v0, v1, v2);
547
548
//test with all the simplices
549
int over_count = 0;
550
int under_count = 0;
551
552
for (const int &index : p_simplex_indices) {
553
int side = _bsp_get_simplex_side(p_points, p_simplices, plane, index);
554
if (side == -2) {
555
continue; //this simplex is invalid, skip for now
556
} else if (side < 0) {
557
under_count++;
558
} else if (side > 0) {
559
over_count++;
560
}
561
}
562
563
if (under_count == 0 && over_count == 0) {
564
continue; //most likely precision issue with a flat simplex, do not try this plane
565
}
566
567
if (under_count > over_count) { //make sure under is always less than over, so we can compute the same ratio
568
SWAP(under_count, over_count);
569
}
570
571
float score = 0; //by default, score is 0 (worst)
572
if (over_count > 0) {
573
// Simplices that are intersected by the plane are moved into both the over
574
// and under subtrees which makes the entire tree deeper, so the best plane
575
// will have the least intersections while separating the simplices evenly.
576
float balance = float(under_count) / over_count;
577
float separation = float(over_count + under_count) / p_simplex_indices.size();
578
score = balance * separation * separation;
579
}
580
581
if (score > best_plane_score) {
582
best_plane = plane;
583
best_plane_score = score;
584
}
585
}
586
}
587
588
// We often end up with two (or on rare occasions, three) simplices that are
589
// either disjoint or share one vertex and don't have a separating plane
590
// among their faces. The fallback is to loop through new planes created
591
// with one vertex of the first simplex and two vertices of the second until
592
// we find a winner.
593
if (best_plane_score == 0) {
594
const BSPSimplex &simplex0 = p_simplices[p_simplex_indices[0]];
595
const BSPSimplex &simplex1 = p_simplices[p_simplex_indices[1]];
596
597
for (uint32_t i = 0; i < 4 && !best_plane_score; i++) {
598
Vector3 v0 = p_points[simplex0.vertices[i]];
599
for (uint32_t j = 0; j < 3 && !best_plane_score; j++) {
600
if (simplex0.vertices[i] == simplex1.vertices[j]) {
601
break;
602
}
603
Vector3 v1 = p_points[simplex1.vertices[j]];
604
for (uint32_t k = j + 1; k < 4; k++) {
605
if (simplex0.vertices[i] == simplex1.vertices[k]) {
606
break;
607
}
608
Vector3 v2 = p_points[simplex1.vertices[k]];
609
610
Plane plane = Plane(v0, v1, v2);
611
if (plane == Plane()) { // When v0, v1, and v2 are collinear, they can't form a plane.
612
continue;
613
}
614
int32_t side0 = _bsp_get_simplex_side(p_points, p_simplices, plane, p_simplex_indices[0]);
615
int32_t side1 = _bsp_get_simplex_side(p_points, p_simplices, plane, p_simplex_indices[1]);
616
if ((side0 == 1 && side1 == -1) || (side0 == -1 && side1 == 1)) {
617
best_plane = plane;
618
best_plane_score = 1.0;
619
break;
620
}
621
}
622
}
623
}
624
}
625
626
LocalVector<int32_t> indices_over;
627
LocalVector<int32_t> indices_under;
628
629
//split again, but add to list
630
for (const uint32_t index : p_simplex_indices) {
631
int side = _bsp_get_simplex_side(p_points, p_simplices, best_plane, index);
632
633
if (side == -2) {
634
continue; //simplex sits on the plane, does not make sense to use it
635
}
636
if (side <= 0) {
637
indices_under.push_back(index);
638
}
639
640
if (side >= 0) {
641
indices_over.push_back(index);
642
}
643
}
644
645
#ifdef DEBUG_BSP
646
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));
647
#endif
648
649
if (best_plane_score < 0.0 || indices_over.size() == p_simplex_indices.size() || indices_under.size() == p_simplex_indices.size()) {
650
// Failed to separate the tetrahedrons using planes
651
// this means Delaunay broke at some point.
652
// Luckily, because we are using tetrahedrons, we can resort to
653
// less precise but still working ways to generate the separating plane
654
// this will most likely look bad when interpolating, but at least it will not crash.
655
// and the artifact will most likely also be very small, so too difficult to notice.
656
657
//find the longest axis
658
659
WARN_PRINT("Inconsistency found in triangulation while building BSP, probe interpolation quality may degrade a bit.");
660
661
LocalVector<Vector3> centers;
662
AABB bounds_all;
663
for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
664
AABB bounds;
665
for (uint32_t j = 0; j < 4; j++) {
666
Vector3 p = p_points[p_simplices[p_simplex_indices[i]].vertices[j]];
667
if (j == 0) {
668
bounds.position = p;
669
} else {
670
bounds.expand_to(p);
671
}
672
}
673
if (i == 0) {
674
centers.push_back(bounds.get_center());
675
} else {
676
bounds_all.merge_with(bounds);
677
}
678
}
679
Vector3::Axis longest_axis = Vector3::Axis(bounds_all.get_longest_axis_index());
680
681
//find the simplex that will go under
682
uint32_t min_d_idx = 0xFFFFFFFF;
683
float min_d_dist = 1e20;
684
685
for (uint32_t i = 0; i < centers.size(); i++) {
686
if (centers[i][longest_axis] < min_d_dist) {
687
min_d_idx = i;
688
min_d_dist = centers[i][longest_axis];
689
}
690
}
691
//rebuild best_plane and over/under arrays
692
best_plane = Plane();
693
best_plane.normal[longest_axis] = 1.0;
694
best_plane.d = min_d_dist;
695
696
indices_under.clear();
697
indices_under.push_back(min_d_idx);
698
699
indices_over.clear();
700
701
for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
702
if (i == min_d_idx) {
703
continue;
704
}
705
indices_over.push_back(p_simplex_indices[i]);
706
}
707
}
708
709
BSPNode node;
710
node.plane = best_plane;
711
712
if (indices_under.is_empty()) {
713
//nothing to do here
714
node.under = BSPNode::EMPTY_LEAF;
715
} else if (indices_under.size() == 1) {
716
node.under = -(indices_under[0] + 1);
717
} else {
718
node.under = _compute_bsp_tree(p_points, p_planes, planes_tested, p_simplices, indices_under, bsp_nodes);
719
}
720
721
if (indices_over.is_empty()) {
722
//nothing to do here
723
node.over = BSPNode::EMPTY_LEAF;
724
} else if (indices_over.size() == 1) {
725
node.over = -(indices_over[0] + 1);
726
} else {
727
node.over = _compute_bsp_tree(p_points, p_planes, planes_tested, p_simplices, indices_over, bsp_nodes);
728
}
729
730
bsp_nodes[node_index] = node;
731
732
return node_index;
733
}
734
735
bool LightmapGI::_lightmap_bake_step_function(float p_completion, const String &p_text, void *ud, bool p_refresh) {
736
BakeStepUD *bsud = (BakeStepUD *)ud;
737
bool ret = false;
738
if (bsud->func) {
739
ret = bsud->func(bsud->from_percent + p_completion * (bsud->to_percent - bsud->from_percent), p_text, bsud->ud, p_refresh);
740
}
741
return ret;
742
}
743
744
void LightmapGI::_plot_triangle_into_octree(GenProbesOctree *p_cell, float p_cell_size, const Vector3 *p_triangle) {
745
for (int i = 0; i < 8; i++) {
746
Vector3i pos = p_cell->offset;
747
uint32_t half_size = p_cell->size / 2;
748
if (i & 1) {
749
pos.x += half_size;
750
}
751
if (i & 2) {
752
pos.y += half_size;
753
}
754
if (i & 4) {
755
pos.z += half_size;
756
}
757
758
AABB subcell;
759
subcell.position = Vector3(pos) * p_cell_size;
760
subcell.size = Vector3(half_size, half_size, half_size) * p_cell_size;
761
762
if (!Geometry3D::triangle_box_overlap(subcell.get_center(), subcell.size * 0.5, p_triangle)) {
763
continue;
764
}
765
766
if (p_cell->children[i] == nullptr) {
767
GenProbesOctree *child = memnew(GenProbesOctree);
768
child->offset = pos;
769
child->size = half_size;
770
p_cell->children[i] = child;
771
}
772
773
if (half_size > 1) {
774
//still levels missing
775
_plot_triangle_into_octree(p_cell->children[i], p_cell_size, p_triangle);
776
}
777
}
778
}
779
780
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) {
781
for (int i = 0; i < 8; i++) {
782
Vector3i pos = p_cell->offset;
783
if (i & 1) {
784
pos.x += p_cell->size;
785
}
786
if (i & 2) {
787
pos.y += p_cell->size;
788
}
789
if (i & 4) {
790
pos.z += p_cell->size;
791
}
792
793
if (p_cell->size == 1 && !positions_used.has(pos)) {
794
//new position to insert!
795
Vector3 real_pos = p_bounds.position + Vector3(pos) * p_cell_size;
796
//see if a user submitted probe is too close
797
int ppcount = probe_positions.size();
798
const Vector3 *pp = probe_positions.ptr();
799
bool exists = false;
800
for (int j = 0; j < ppcount; j++) {
801
if (pp[j].distance_to(real_pos) < (p_cell_size * 0.5f)) {
802
exists = true;
803
break;
804
}
805
}
806
807
if (!exists) {
808
new_probe_positions.push_back(real_pos);
809
}
810
811
positions_used[pos] = true;
812
}
813
814
if (p_cell->children[i] != nullptr) {
815
_gen_new_positions_from_octree(p_cell->children[i], p_cell_size, probe_positions, new_probe_positions, positions_used, p_bounds);
816
}
817
}
818
}
819
820
LightmapGI::BakeError LightmapGI::_save_and_reimport_atlas_textures(const Ref<Lightmapper> p_lightmapper, const String &p_base_name, TypedArray<TextureLayered> &r_textures, bool p_is_shadowmask) const {
821
Vector<Ref<Image>> images;
822
images.resize(p_is_shadowmask ? p_lightmapper->get_shadowmask_texture_count() : p_lightmapper->get_bake_texture_count());
823
824
for (int i = 0; i < images.size(); i++) {
825
images.set(i, p_is_shadowmask ? p_lightmapper->get_shadowmask_texture(i) : p_lightmapper->get_bake_texture(i));
826
}
827
828
const int slice_count = images.size();
829
const int slice_width = images[0]->get_width();
830
const int slice_height = images[0]->get_height();
831
832
const int slices_per_texture = Image::MAX_HEIGHT / slice_height;
833
const int texture_count = Math::ceil(slice_count / (float)slices_per_texture);
834
const int last_count = slice_count % slices_per_texture;
835
836
r_textures.resize(texture_count);
837
838
for (int i = 0; i < texture_count; i++) {
839
const int texture_slice_count = (i == texture_count - 1 && last_count != 0) ? last_count : slices_per_texture;
840
841
Ref<Image> texture_image = Image::create_empty(slice_width, slice_height * texture_slice_count, false, images[0]->get_format());
842
843
for (int j = 0; j < texture_slice_count; j++) {
844
texture_image->blit_rect(images[i * slices_per_texture + j], Rect2i(0, 0, slice_width, slice_height), Point2i(0, slice_height * j));
845
}
846
847
const String atlas_path = (texture_count > 1 ? p_base_name + "_" + itos(i) : p_base_name) + (p_is_shadowmask ? ".png" : ".exr");
848
const String config_path = atlas_path + ".import";
849
850
Ref<ConfigFile> config;
851
config.instantiate();
852
853
// Load an import configuration if present.
854
if (FileAccess::exists(config_path)) {
855
config->load(config_path);
856
}
857
858
config->set_value("remap", "importer", "2d_array_texture");
859
config->set_value("remap", "type", "CompressedTexture2DArray");
860
if (!config->has_section_key("params", "compress/mode")) {
861
// Do not override an existing compression mode.
862
config->set_value("params", "compress/mode", 2);
863
}
864
config->set_value("params", "compress/channel_pack", 1);
865
config->set_value("params", "mipmaps/generate", false);
866
config->set_value("params", "slices/horizontal", 1);
867
config->set_value("params", "slices/vertical", texture_slice_count);
868
869
config->save(config_path);
870
871
if (supersampling_enabled) {
872
texture_image->resize(texture_image->get_width() / supersampling_factor, texture_image->get_height() / supersampling_factor, Image::INTERPOLATE_TRILINEAR);
873
}
874
875
// Save the file.
876
Error save_err;
877
if (p_is_shadowmask) {
878
save_err = texture_image->save_png(atlas_path);
879
} else {
880
save_err = texture_image->save_exr(atlas_path, false);
881
}
882
883
ERR_FAIL_COND_V(save_err, LightmapGI::BAKE_ERROR_CANT_CREATE_IMAGE);
884
885
// Reimport the file.
886
ResourceLoader::import(atlas_path);
887
Ref<TextureLayered> t = ResourceLoader::load(atlas_path); // If already loaded, it will be updated on refocus?
888
ERR_FAIL_COND_V(t.is_null(), LightmapGI::BAKE_ERROR_CANT_CREATE_IMAGE);
889
890
// Store the atlas in the array.
891
r_textures[i] = t;
892
}
893
894
return LightmapGI::BAKE_ERROR_OK;
895
}
896
897
LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_path, Lightmapper::BakeStepFunc p_bake_step, void *p_bake_userdata) {
898
if (p_image_data_path.is_empty()) {
899
if (get_light_data().is_null()) {
900
return BAKE_ERROR_NO_SAVE_PATH;
901
}
902
903
p_image_data_path = get_light_data()->get_path();
904
if (!p_image_data_path.is_resource_file()) {
905
return BAKE_ERROR_NO_SAVE_PATH;
906
}
907
}
908
909
Ref<Lightmapper> lightmapper = Lightmapper::create();
910
ERR_FAIL_COND_V(lightmapper.is_null(), BAKE_ERROR_NO_LIGHTMAPPER);
911
912
BakeStepUD bsud;
913
bsud.func = p_bake_step;
914
bsud.ud = p_bake_userdata;
915
bsud.from_percent = 0.2;
916
bsud.to_percent = 0.8;
917
918
if (p_bake_step) {
919
p_bake_step(0.0, RTR("Finding meshes, lights and probes"), p_bake_userdata, true);
920
}
921
/* STEP 1, FIND MESHES, LIGHTS AND PROBES */
922
Vector<Lightmapper::MeshData> mesh_data;
923
Vector<LightsFound> lights_found;
924
Vector<Vector3> probes_found;
925
AABB bounds;
926
{
927
Vector<MeshesFound> meshes_found;
928
_find_meshes_and_lights(p_from_node ? p_from_node : get_parent(), meshes_found, lights_found, probes_found);
929
930
if (meshes_found.is_empty()) {
931
return BAKE_ERROR_NO_MESHES;
932
}
933
// create mesh data for insert
934
935
//get the base material textures, help compute atlas size and bounds
936
for (int m_i = 0; m_i < meshes_found.size(); m_i++) {
937
if (p_bake_step) {
938
float p = (float)(m_i) / meshes_found.size();
939
p_bake_step(p * 0.1, vformat(RTR("Preparing geometry %d/%d"), m_i, meshes_found.size()), p_bake_userdata, false);
940
}
941
942
MeshesFound &mf = meshes_found.write[m_i];
943
944
Size2i mesh_lightmap_size = mf.mesh->get_lightmap_size_hint();
945
if (mesh_lightmap_size == Size2i(0, 0)) {
946
// TODO we should compute a size if no lightmap hint is set, as we did in 3.x.
947
// For now set to basic size to avoid crash.
948
mesh_lightmap_size = Size2i(64, 64);
949
}
950
// Double lightmap texel density if downsampling is enabled, as the final texture size will be halved before saving lightmaps.
951
Size2i lightmap_size = Size2i(Size2(mesh_lightmap_size) * mf.lightmap_scale * texel_scale) * (supersampling_enabled ? supersampling_factor : 1.0);
952
ERR_FAIL_COND_V(lightmap_size.x == 0 || lightmap_size.y == 0, BAKE_ERROR_LIGHTMAP_TOO_SMALL);
953
954
TypedArray<RID> overrides;
955
overrides.resize(mf.overrides.size());
956
for (int i = 0; i < mf.overrides.size(); i++) {
957
if (mf.overrides[i].is_valid()) {
958
overrides[i] = mf.overrides[i]->get_rid();
959
}
960
}
961
TypedArray<Image> images = RS::get_singleton()->bake_render_uv2(mf.mesh->get_rid(), overrides, lightmap_size);
962
963
ERR_FAIL_COND_V(images.is_empty(), BAKE_ERROR_CANT_CREATE_IMAGE);
964
965
Ref<Image> albedo = images[RS::BAKE_CHANNEL_ALBEDO_ALPHA];
966
Ref<Image> orm = images[RS::BAKE_CHANNEL_ORM];
967
968
//multiply albedo by metal
969
970
Lightmapper::MeshData md;
971
972
{
973
Dictionary d;
974
d["path"] = mf.node_path;
975
if (mf.subindex >= 0) {
976
d["subindex"] = mf.subindex;
977
}
978
md.userdata = d;
979
}
980
981
{
982
if (albedo->get_format() != Image::FORMAT_RGBA8) {
983
albedo->convert(Image::FORMAT_RGBA8);
984
}
985
if (orm->get_format() != Image::FORMAT_RGBA8) {
986
orm->convert(Image::FORMAT_RGBA8);
987
}
988
Vector<uint8_t> albedo_alpha = albedo->get_data();
989
Vector<uint8_t> orm_data = orm->get_data();
990
991
Vector<uint8_t> albedom;
992
uint32_t len = albedo_alpha.size();
993
albedom.resize(len);
994
const uint8_t *r_aa = albedo_alpha.ptr();
995
const uint8_t *r_orm = orm_data.ptr();
996
uint8_t *w_albedo = albedom.ptrw();
997
998
for (uint32_t i = 0; i < len; i += 4) {
999
w_albedo[i + 0] = uint8_t(CLAMP(float(r_aa[i + 0]) * (1.0 - float(r_orm[i + 2] / 255.0)), 0, 255));
1000
w_albedo[i + 1] = uint8_t(CLAMP(float(r_aa[i + 1]) * (1.0 - float(r_orm[i + 2] / 255.0)), 0, 255));
1001
w_albedo[i + 2] = uint8_t(CLAMP(float(r_aa[i + 2]) * (1.0 - float(r_orm[i + 2] / 255.0)), 0, 255));
1002
w_albedo[i + 3] = r_aa[i + 3];
1003
}
1004
1005
md.albedo_on_uv2.instantiate();
1006
md.albedo_on_uv2->set_data(lightmap_size.width, lightmap_size.height, false, Image::FORMAT_RGBA8, albedom);
1007
}
1008
1009
md.emission_on_uv2 = images[RS::BAKE_CHANNEL_EMISSION];
1010
if (md.emission_on_uv2->get_format() != Image::FORMAT_RGBAH) {
1011
md.emission_on_uv2->convert(Image::FORMAT_RGBAH);
1012
}
1013
1014
//get geometry
1015
1016
Basis normal_xform = mf.xform.basis.inverse().transposed();
1017
1018
for (int i = 0; i < mf.mesh->get_surface_count(); i++) {
1019
if (mf.mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
1020
continue;
1021
}
1022
Array a = mf.mesh->surface_get_arrays(i);
1023
Ref<Material> mat = mf.mesh->surface_get_material(i);
1024
RID mat_rid;
1025
if (mat.is_valid()) {
1026
mat_rid = mat->get_rid();
1027
}
1028
1029
Vector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
1030
const Vector3 *vr = vertices.ptr();
1031
Vector<Vector2> uv = a[Mesh::ARRAY_TEX_UV2];
1032
const Vector2 *uvr = nullptr;
1033
Vector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
1034
const Vector3 *nr = nullptr;
1035
Vector<int> index = a[Mesh::ARRAY_INDEX];
1036
1037
ERR_CONTINUE(uv.is_empty());
1038
ERR_CONTINUE(normals.is_empty());
1039
1040
uvr = uv.ptr();
1041
nr = normals.ptr();
1042
1043
int facecount;
1044
const int *ir = nullptr;
1045
1046
if (index.size()) {
1047
facecount = index.size() / 3;
1048
ir = index.ptr();
1049
} else {
1050
facecount = vertices.size() / 3;
1051
}
1052
1053
for (int j = 0; j < facecount; j++) {
1054
uint32_t vidx[3];
1055
1056
if (ir) {
1057
for (int k = 0; k < 3; k++) {
1058
vidx[k] = ir[j * 3 + k];
1059
}
1060
} else {
1061
for (int k = 0; k < 3; k++) {
1062
vidx[k] = j * 3 + k;
1063
}
1064
}
1065
1066
for (int k = 0; k < 3; k++) {
1067
Vector3 v = mf.xform.xform(vr[vidx[k]]);
1068
if (bounds == AABB()) {
1069
bounds.position = v;
1070
} else {
1071
bounds.expand_to(v);
1072
}
1073
md.points.push_back(v);
1074
1075
md.uv2.push_back(uvr[vidx[k]]);
1076
md.normal.push_back(normal_xform.xform(nr[vidx[k]]).normalized());
1077
md.material.push_back(mat_rid);
1078
}
1079
}
1080
}
1081
1082
mesh_data.push_back(md);
1083
}
1084
}
1085
1086
/* STEP 2, CREATE PROBES */
1087
1088
if (p_bake_step) {
1089
p_bake_step(0.3, RTR("Creating probes"), p_bake_userdata, true);
1090
}
1091
1092
//bounds need to include the user probes
1093
for (int i = 0; i < probes_found.size(); i++) {
1094
bounds.expand_to(probes_found[i]);
1095
}
1096
1097
bounds.grow_by(bounds.size.length() * 0.001);
1098
1099
if (gen_probes == GENERATE_PROBES_DISABLED) {
1100
// generate 8 probes on bound endpoints
1101
for (int i = 0; i < 8; i++) {
1102
probes_found.push_back(bounds.get_endpoint(i));
1103
}
1104
} else {
1105
// detect probes from geometry
1106
static const int subdiv_values[6] = { 0, 4, 8, 16, 32 };
1107
int subdiv = subdiv_values[gen_probes];
1108
1109
float subdiv_cell_size;
1110
Vector3i bound_limit;
1111
{
1112
int longest_axis = bounds.get_longest_axis_index();
1113
subdiv_cell_size = bounds.size[longest_axis] / subdiv;
1114
int axis_n1 = (longest_axis + 1) % 3;
1115
int axis_n2 = (longest_axis + 2) % 3;
1116
1117
bound_limit[longest_axis] = subdiv;
1118
bound_limit[axis_n1] = int(Math::ceil(bounds.size[axis_n1] / subdiv_cell_size));
1119
bound_limit[axis_n2] = int(Math::ceil(bounds.size[axis_n2] / subdiv_cell_size));
1120
//compensate bounds
1121
bounds.size[axis_n1] = bound_limit[axis_n1] * subdiv_cell_size;
1122
bounds.size[axis_n2] = bound_limit[axis_n2] * subdiv_cell_size;
1123
}
1124
1125
GenProbesOctree octree;
1126
octree.size = subdiv;
1127
1128
for (int i = 0; i < mesh_data.size(); i++) {
1129
if (p_bake_step) {
1130
float p = (float)(i) / mesh_data.size();
1131
p_bake_step(0.3 + p * 0.1, vformat(RTR("Creating probes from mesh %d/%d"), i, mesh_data.size()), p_bake_userdata, false);
1132
}
1133
1134
for (int j = 0; j < mesh_data[i].points.size(); j += 3) {
1135
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 };
1136
_plot_triangle_into_octree(&octree, subdiv_cell_size, points);
1137
}
1138
}
1139
1140
LocalVector<Vector3> new_probe_positions;
1141
HashMap<Vector3i, bool> positions_used;
1142
for (uint32_t i = 0; i < 8; i++) { //insert bounding endpoints
1143
Vector3i pos;
1144
if (i & 1) {
1145
pos.x += bound_limit.x;
1146
}
1147
if (i & 2) {
1148
pos.y += bound_limit.y;
1149
}
1150
if (i & 4) {
1151
pos.z += bound_limit.z;
1152
}
1153
1154
positions_used[pos] = true;
1155
Vector3 real_pos = bounds.position + Vector3(pos) * subdiv_cell_size; //use same formula for numerical stability
1156
new_probe_positions.push_back(real_pos);
1157
}
1158
//skip first level, since probes are always added at bounds endpoints anyway (code above this)
1159
for (int i = 0; i < 8; i++) {
1160
if (octree.children[i]) {
1161
_gen_new_positions_from_octree(octree.children[i], subdiv_cell_size, probes_found, new_probe_positions, positions_used, bounds);
1162
}
1163
}
1164
1165
for (const Vector3 &position : new_probe_positions) {
1166
probes_found.push_back(position);
1167
}
1168
}
1169
1170
// Add everything to lightmapper
1171
const bool use_physical_light_units = GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units");
1172
if (p_bake_step) {
1173
p_bake_step(0.4, RTR("Preparing Lightmapper"), p_bake_userdata, true);
1174
}
1175
1176
{
1177
for (int i = 0; i < mesh_data.size(); i++) {
1178
lightmapper->add_mesh(mesh_data[i]);
1179
}
1180
for (int i = 0; i < lights_found.size(); i++) {
1181
Light3D *light = lights_found[i].light;
1182
if (light->is_editor_only()) {
1183
// Don't include editor-only lights in the lightmap bake,
1184
// as this results in inconsistent visuals when running the project.
1185
continue;
1186
}
1187
1188
Transform3D xf = lights_found[i].xform;
1189
1190
// For the lightmapper, the indirect energy represents the multiplier for the indirect bounces caused by the light, so the value is not converted when using physical units.
1191
float indirect_energy = light->get_param(Light3D::PARAM_INDIRECT_ENERGY);
1192
Color linear_color = light->get_color().srgb_to_linear();
1193
float energy = light->get_param(Light3D::PARAM_ENERGY);
1194
if (use_physical_light_units) {
1195
energy *= light->get_param(Light3D::PARAM_INTENSITY);
1196
linear_color *= light->get_correlated_color().srgb_to_linear();
1197
}
1198
1199
if (Object::cast_to<DirectionalLight3D>(light)) {
1200
DirectionalLight3D *l = Object::cast_to<DirectionalLight3D>(light);
1201
if (l->get_sky_mode() != DirectionalLight3D::SKY_MODE_SKY_ONLY) {
1202
lightmapper->add_directional_light(light->get_name(), light->get_bake_mode() == Light3D::BAKE_STATIC, -xf.basis.get_column(Vector3::AXIS_Z).normalized(), linear_color, energy, indirect_energy, l->get_param(Light3D::PARAM_SIZE), l->get_param(Light3D::PARAM_SHADOW_BLUR));
1203
}
1204
} else if (Object::cast_to<OmniLight3D>(light)) {
1205
OmniLight3D *l = Object::cast_to<OmniLight3D>(light);
1206
if (use_physical_light_units) {
1207
energy *= (1.0 / (Math::PI * 4.0));
1208
}
1209
lightmapper->add_omni_light(light->get_name(), light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, linear_color, energy, indirect_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));
1210
} else if (Object::cast_to<SpotLight3D>(light)) {
1211
SpotLight3D *l = Object::cast_to<SpotLight3D>(light);
1212
if (use_physical_light_units) {
1213
energy *= (1.0 / Math::PI);
1214
}
1215
lightmapper->add_spot_light(light->get_name(), light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, -xf.basis.get_column(Vector3::AXIS_Z).normalized(), linear_color, energy, indirect_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));
1216
}
1217
}
1218
for (int i = 0; i < probes_found.size(); i++) {
1219
lightmapper->add_probe(probes_found[i]);
1220
}
1221
}
1222
1223
Ref<Image> environment_image;
1224
Basis environment_transform;
1225
1226
// Add everything to lightmapper
1227
if (environment_mode != ENVIRONMENT_MODE_DISABLED) {
1228
if (p_bake_step) {
1229
p_bake_step(4.1, RTR("Preparing Environment"), p_bake_userdata, true);
1230
}
1231
1232
environment_transform = get_global_transform().basis;
1233
1234
switch (environment_mode) {
1235
case ENVIRONMENT_MODE_DISABLED: {
1236
//nothing
1237
} break;
1238
case ENVIRONMENT_MODE_SCENE: {
1239
Ref<World3D> world = get_world_3d();
1240
if (world.is_valid()) {
1241
Ref<Environment> env = world->get_environment();
1242
if (env.is_null()) {
1243
env = world->get_fallback_environment();
1244
}
1245
1246
if (env.is_valid()) {
1247
environment_image = RS::get_singleton()->environment_bake_panorama(env->get_rid(), true, Size2i(128, 64));
1248
environment_transform = Basis::from_euler(env->get_sky_rotation()).inverse();
1249
}
1250
}
1251
} break;
1252
case ENVIRONMENT_MODE_CUSTOM_SKY: {
1253
if (environment_custom_sky.is_valid()) {
1254
environment_image = RS::get_singleton()->sky_bake_panorama(environment_custom_sky->get_rid(), environment_custom_energy, true, Size2i(128, 64));
1255
}
1256
1257
} break;
1258
case ENVIRONMENT_MODE_CUSTOM_COLOR: {
1259
environment_image.instantiate();
1260
environment_image->initialize_data(128, 64, false, Image::FORMAT_RGBAF);
1261
Color c = environment_custom_color;
1262
c.r *= environment_custom_energy;
1263
c.g *= environment_custom_energy;
1264
c.b *= environment_custom_energy;
1265
environment_image->fill(c);
1266
1267
} break;
1268
}
1269
}
1270
1271
float exposure_normalization = 1.0;
1272
if (camera_attributes.is_valid()) {
1273
exposure_normalization = camera_attributes->get_exposure_multiplier();
1274
if (use_physical_light_units) {
1275
exposure_normalization = camera_attributes->calculate_exposure_normalization();
1276
}
1277
}
1278
1279
Lightmapper::BakeError bake_err = lightmapper->bake(Lightmapper::BakeQuality(bake_quality), use_denoiser, denoiser_strength, denoiser_range, bounces,
1280
bounce_indirect_energy, bias, max_texture_size, directional, shadowmask_mode != LightmapGIData::SHADOWMASK_MODE_NONE, use_texture_for_bounces,
1281
Lightmapper::GenerateProbes(gen_probes), environment_image, environment_transform, _lightmap_bake_step_function, &bsud, exposure_normalization, (supersampling_enabled ? supersampling_factor : 1));
1282
1283
if (bake_err == Lightmapper::BAKE_ERROR_TEXTURE_EXCEEDS_MAX_SIZE) {
1284
return BAKE_ERROR_TEXTURE_SIZE_TOO_SMALL;
1285
} else if (bake_err == Lightmapper::BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES) {
1286
return BAKE_ERROR_MESHES_INVALID;
1287
} else if (bake_err == Lightmapper::BAKE_ERROR_ATLAS_TOO_SMALL) {
1288
return BAKE_ERROR_ATLAS_TOO_SMALL;
1289
} else if (bake_err == Lightmapper::BAKE_ERROR_USER_ABORTED) {
1290
return BAKE_ERROR_USER_ABORTED;
1291
}
1292
1293
// POSTBAKE: Save Textures.
1294
TypedArray<TextureLayered> lightmap_textures;
1295
TypedArray<TextureLayered> shadowmask_textures;
1296
1297
const String texture_filename = p_image_data_path.get_basename();
1298
const int shadowmask_texture_count = lightmapper->get_shadowmask_texture_count();
1299
const bool save_shadowmask = shadowmask_mode != LightmapGIData::SHADOWMASK_MODE_NONE && shadowmask_texture_count > 0;
1300
1301
// Save the lightmap atlases.
1302
BakeError save_err = _save_and_reimport_atlas_textures(lightmapper, texture_filename, lightmap_textures, false);
1303
ERR_FAIL_COND_V(save_err != BAKE_ERROR_OK, save_err);
1304
1305
if (save_shadowmask) {
1306
// Save the shadowmask atlases.
1307
save_err = _save_and_reimport_atlas_textures(lightmapper, texture_filename + "_shadow", shadowmask_textures, true);
1308
ERR_FAIL_COND_V(save_err != BAKE_ERROR_OK, save_err);
1309
}
1310
1311
// POSTBAKE: Save Light Data.
1312
Ref<LightmapGIData> gi_data;
1313
1314
if (get_light_data().is_valid()) {
1315
gi_data = get_light_data();
1316
set_light_data(Ref<LightmapGIData>()); // Clear.
1317
gi_data->clear();
1318
1319
} else {
1320
gi_data.instantiate();
1321
}
1322
1323
gi_data->set_lightmap_textures(lightmap_textures);
1324
1325
if (save_shadowmask) {
1326
gi_data->set_shadowmask_textures(shadowmask_textures);
1327
} else {
1328
gi_data->clear_shadowmask_textures();
1329
}
1330
1331
gi_data->set_uses_spherical_harmonics(directional);
1332
gi_data->_set_uses_packed_directional(directional); // New SH lightmaps are packed automatically.
1333
1334
for (int i = 0; i < lightmapper->get_bake_mesh_count(); i++) {
1335
Dictionary d = lightmapper->get_bake_mesh_userdata(i);
1336
NodePath np = d["path"];
1337
int32_t subindex = -1;
1338
if (d.has("subindex")) {
1339
subindex = d["subindex"];
1340
}
1341
1342
Rect2 uv_scale = lightmapper->get_bake_mesh_uv_scale(i);
1343
int slice_index = lightmapper->get_bake_mesh_texture_slice(i);
1344
gi_data->add_user(np, uv_scale, slice_index, subindex);
1345
}
1346
1347
int probe_count = lightmapper->get_bake_probe_count();
1348
1349
// Probe SH may change between bakes.
1350
LocalVector<Color> probe_sh;
1351
LocalVector<Vector3> probe_points;
1352
probe_sh.resize(probe_count * 9);
1353
probe_points.resize(probe_count);
1354
1355
uint32_t bake_probe_hash = HASH_MURMUR3_SEED;
1356
for (int i = 0; i < probe_count; i++) {
1357
// Calculate the hash from probe positions.
1358
Vector3 point = lightmapper->get_bake_probe_point(i);
1359
bake_probe_hash = hash_murmur3_one_double(point.x, bake_probe_hash);
1360
bake_probe_hash = hash_murmur3_one_double(point.y, bake_probe_hash);
1361
bake_probe_hash = hash_murmur3_one_double(point.z, bake_probe_hash);
1362
1363
probe_points[i] = point;
1364
Vector<Color> colors = lightmapper->get_bake_probe_sh(i);
1365
ERR_CONTINUE(colors.size() != 9);
1366
for (int j = 0; j < 9; j++) {
1367
probe_sh[i * 9 + j] = colors[j];
1368
}
1369
}
1370
1371
// If the probe hash doesn't match, build the BSP tree from scratch.
1372
if (bake_probe_hash != gi_data->get_lightprobe_hash()) {
1373
// Obtain solved simplices.
1374
if (p_bake_step) {
1375
p_bake_step(0.8, RTR("Generating Probe Volumes"), p_bake_userdata, true);
1376
}
1377
1378
Vector<Delaunay3D::OutputSimplex> solved_simplices = Delaunay3D::tetrahedralize(Vector<Vector3>(probe_points));
1379
int64_t simplex_count = solved_simplices.size();
1380
1381
LocalVector<BSPSimplex> bsp_simplices;
1382
LocalVector<Plane> bsp_planes;
1383
LocalVector<int32_t> bsp_simplex_indices;
1384
PackedInt32Array tetrahedrons;
1385
1386
for (int i = 0; i < simplex_count; i++) {
1387
//Prepare a special representation of the simplex, which uses a BSP Tree
1388
BSPSimplex bsp_simplex;
1389
for (int j = 0; j < 4; j++) {
1390
bsp_simplex.vertices[j] = solved_simplices[i].points[j];
1391
}
1392
for (int j = 0; j < 4; j++) {
1393
static const int face_order[4][3] = {
1394
{ 0, 1, 2 },
1395
{ 0, 2, 3 },
1396
{ 0, 1, 3 },
1397
{ 1, 2, 3 }
1398
};
1399
Vector3 a = probe_points[solved_simplices[i].points[face_order[j][0]]];
1400
Vector3 b = probe_points[solved_simplices[i].points[face_order[j][1]]];
1401
Vector3 c = probe_points[solved_simplices[i].points[face_order[j][2]]];
1402
1403
//store planes in an array, but ensure they are reused, to speed up processing
1404
1405
Plane p(a, b, c);
1406
int plane_index = -1;
1407
for (uint32_t k = 0; k < bsp_planes.size(); k++) {
1408
if (bsp_planes[k].is_equal_approx_any_side(p)) {
1409
plane_index = k;
1410
break;
1411
}
1412
}
1413
1414
if (plane_index == -1) {
1415
plane_index = bsp_planes.size();
1416
bsp_planes.push_back(p);
1417
}
1418
1419
bsp_simplex.planes[j] = plane_index;
1420
1421
//also fill simplex array
1422
tetrahedrons.push_back(solved_simplices[i].points[j]);
1423
}
1424
1425
bsp_simplex_indices.push_back(bsp_simplices.size());
1426
bsp_simplices.push_back(bsp_simplex);
1427
}
1428
1429
//#define DEBUG_SIMPLICES_AS_OBJ_FILE
1430
#ifdef DEBUG_SIMPLICES_AS_OBJ_FILE
1431
{
1432
Ref<FileAccess> f = FileAccess::open("res://bsp.obj", FileAccess::WRITE);
1433
for (uint32_t i = 0; i < bsp_simplices.size(); i++) {
1434
f->store_line("o Simplex" + itos(i));
1435
for (int j = 0; j < 4; j++) {
1436
f->store_line(vformat("v %f %f %f", probe_points[bsp_simplices[i].vertices[j]].x, probe_points[bsp_simplices[i].vertices[j]].y, probe_points[bsp_simplices[i].vertices[j]].z));
1437
}
1438
static const int face_order[4][3] = {
1439
{ 1, 2, 3 },
1440
{ 1, 3, 4 },
1441
{ 1, 2, 4 },
1442
{ 2, 3, 4 }
1443
};
1444
1445
for (int j = 0; j < 4; j++) {
1446
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]));
1447
}
1448
}
1449
}
1450
#endif
1451
1452
LocalVector<BSPNode> bsp_nodes;
1453
LocalVector<int32_t> planes_tested;
1454
planes_tested.resize(bsp_planes.size());
1455
for (int &index : planes_tested) {
1456
index = 0x7FFFFFFF;
1457
}
1458
1459
if (p_bake_step) {
1460
p_bake_step(0.9, RTR("Generating Probe Acceleration Structures"), p_bake_userdata, true);
1461
}
1462
1463
// Compute a BSP tree of the simplices, so it's easy to find the exact one.
1464
_compute_bsp_tree(probe_points, bsp_planes, planes_tested, bsp_simplices, bsp_simplex_indices, bsp_nodes);
1465
1466
PackedInt32Array bsp_array;
1467
bsp_array.resize(bsp_nodes.size() * 6); // six 32 bits values used for each BSP node
1468
{
1469
float *fptr = (float *)bsp_array.ptrw();
1470
int32_t *iptr = (int32_t *)bsp_array.ptrw();
1471
for (uint32_t i = 0; i < bsp_nodes.size(); i++) {
1472
fptr[i * 6 + 0] = bsp_nodes[i].plane.normal.x;
1473
fptr[i * 6 + 1] = bsp_nodes[i].plane.normal.y;
1474
fptr[i * 6 + 2] = bsp_nodes[i].plane.normal.z;
1475
fptr[i * 6 + 3] = bsp_nodes[i].plane.d;
1476
iptr[i * 6 + 4] = bsp_nodes[i].over;
1477
iptr[i * 6 + 5] = bsp_nodes[i].under;
1478
}
1479
//#define DEBUG_BSP_TREE
1480
#ifdef DEBUG_BSP_TREE
1481
Ref<FileAccess> f = FileAccess::open("res://bsp.txt", FileAccess::WRITE);
1482
for (uint32_t i = 0; i < bsp_nodes.size(); i++) {
1483
f->store_line(itos(i) + " - plane: " + bsp_nodes[i].plane + " over: " + itos(bsp_nodes[i].over) + " under: " + itos(bsp_nodes[i].under));
1484
}
1485
#endif
1486
}
1487
1488
gi_data->set_capture_data(bounds, interior, Vector<Vector3>(probe_points), Vector<Color>(probe_sh), tetrahedrons, bsp_array, exposure_normalization, bake_probe_hash);
1489
} else {
1490
gi_data->set_capture_data(bounds, interior, Vector<Vector3>(probe_points), Vector<Color>(probe_sh), gi_data->get_capture_tetrahedra(), gi_data->get_capture_bsp_tree(), exposure_normalization, bake_probe_hash);
1491
}
1492
1493
gi_data->set_path(p_image_data_path, true);
1494
Error err = ResourceSaver::save(gi_data);
1495
1496
if (err != OK) {
1497
return BAKE_ERROR_CANT_CREATE_IMAGE;
1498
}
1499
1500
set_light_data(gi_data);
1501
update_configuration_warnings();
1502
1503
return BAKE_ERROR_OK;
1504
}
1505
1506
void LightmapGI::_notification(int p_what) {
1507
switch (p_what) {
1508
case NOTIFICATION_POST_ENTER_TREE: {
1509
if (light_data.is_valid()) {
1510
ERR_FAIL_COND_MSG(
1511
light_data->is_using_spherical_harmonics() && !light_data->_is_using_packed_directional(),
1512
vformat(
1513
"%s (%s): The directional lightmap textures are stored in a format that isn't supported anymore. Please bake lightmaps again to make lightmaps display from this node again.",
1514
get_light_data()->get_path(), get_name()));
1515
1516
if (last_owner && last_owner != get_owner()) {
1517
light_data->clear_users();
1518
}
1519
1520
_assign_lightmaps();
1521
}
1522
} break;
1523
1524
case NOTIFICATION_EXIT_TREE: {
1525
last_owner = get_owner();
1526
1527
if (light_data.is_valid()) {
1528
_clear_lightmaps();
1529
}
1530
} break;
1531
}
1532
}
1533
1534
void LightmapGI::_assign_lightmaps() {
1535
ERR_FAIL_COND(light_data.is_null());
1536
1537
Vector<String> missing_node_paths;
1538
1539
for (int i = 0; i < light_data->get_user_count(); i++) {
1540
NodePath user_path = light_data->get_user_path(i);
1541
Node *node = get_node_or_null(user_path);
1542
if (!node) {
1543
missing_node_paths.push_back(String(user_path));
1544
continue;
1545
}
1546
int instance_idx = light_data->get_user_sub_instance(i);
1547
if (instance_idx >= 0) {
1548
RID instance_id = node->call("get_bake_mesh_instance", instance_idx);
1549
if (instance_id.is_valid()) {
1550
RS::get_singleton()->instance_geometry_set_lightmap(instance_id, get_instance(), light_data->get_user_lightmap_uv_scale(i), light_data->get_user_lightmap_slice_index(i));
1551
}
1552
} else {
1553
VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(node);
1554
ERR_CONTINUE(!vi);
1555
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));
1556
}
1557
}
1558
1559
if (!missing_node_paths.is_empty()) {
1560
String missing_paths_text;
1561
if (missing_node_paths.size() <= 3) {
1562
missing_paths_text = String(", ").join(missing_node_paths);
1563
} else {
1564
missing_paths_text = vformat("%s and %d more", String(", ").join(missing_node_paths.slice(0, 3)), missing_node_paths.size() - 3);
1565
}
1566
WARN_PRINT(vformat("%s couldn't find previously baked nodes and needs a rebake (missing nodes: %s).", get_name(), missing_paths_text));
1567
}
1568
}
1569
1570
void LightmapGI::_clear_lightmaps() {
1571
ERR_FAIL_COND(light_data.is_null());
1572
for (int i = 0; i < light_data->get_user_count(); i++) {
1573
Node *node = get_node_or_null(light_data->get_user_path(i));
1574
if (!node) {
1575
continue;
1576
}
1577
int instance_idx = light_data->get_user_sub_instance(i);
1578
if (instance_idx >= 0) {
1579
RID instance_id = node->call("get_bake_mesh_instance", instance_idx);
1580
if (instance_id.is_valid()) {
1581
RS::get_singleton()->instance_geometry_set_lightmap(instance_id, RID(), Rect2(), 0);
1582
}
1583
} else {
1584
VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(node);
1585
ERR_CONTINUE(!vi);
1586
RS::get_singleton()->instance_geometry_set_lightmap(vi->get_instance(), RID(), Rect2(), 0);
1587
}
1588
}
1589
}
1590
1591
void LightmapGI::set_light_data(const Ref<LightmapGIData> &p_data) {
1592
if (light_data.is_valid()) {
1593
if (is_inside_tree()) {
1594
_clear_lightmaps();
1595
}
1596
set_base(RID());
1597
}
1598
light_data = p_data;
1599
1600
if (light_data.is_valid()) {
1601
set_base(light_data->get_rid());
1602
if (is_inside_tree()) {
1603
_assign_lightmaps();
1604
}
1605
light_data->update_shadowmask_mode(shadowmask_mode);
1606
}
1607
1608
update_gizmos();
1609
}
1610
1611
Ref<LightmapGIData> LightmapGI::get_light_data() const {
1612
return light_data;
1613
}
1614
1615
void LightmapGI::set_bake_quality(BakeQuality p_quality) {
1616
bake_quality = p_quality;
1617
}
1618
1619
LightmapGI::BakeQuality LightmapGI::get_bake_quality() const {
1620
return bake_quality;
1621
}
1622
1623
AABB LightmapGI::get_aabb() const {
1624
return AABB();
1625
}
1626
1627
void LightmapGI::set_use_denoiser(bool p_enable) {
1628
use_denoiser = p_enable;
1629
notify_property_list_changed();
1630
}
1631
1632
bool LightmapGI::is_using_denoiser() const {
1633
return use_denoiser;
1634
}
1635
1636
void LightmapGI::set_denoiser_strength(float p_denoiser_strength) {
1637
denoiser_strength = p_denoiser_strength;
1638
}
1639
1640
float LightmapGI::get_denoiser_strength() const {
1641
return denoiser_strength;
1642
}
1643
1644
void LightmapGI::set_denoiser_range(int p_denoiser_range) {
1645
denoiser_range = p_denoiser_range;
1646
}
1647
1648
int LightmapGI::get_denoiser_range() const {
1649
return denoiser_range;
1650
}
1651
1652
void LightmapGI::set_directional(bool p_enable) {
1653
directional = p_enable;
1654
}
1655
1656
bool LightmapGI::is_directional() const {
1657
return directional;
1658
}
1659
1660
void LightmapGI::set_shadowmask_mode(LightmapGIData::ShadowmaskMode p_mode) {
1661
shadowmask_mode = p_mode;
1662
if (light_data.is_valid()) {
1663
light_data->update_shadowmask_mode(p_mode);
1664
}
1665
1666
update_configuration_warnings();
1667
}
1668
1669
LightmapGIData::ShadowmaskMode LightmapGI::get_shadowmask_mode() const {
1670
return shadowmask_mode;
1671
}
1672
1673
void LightmapGI::set_use_texture_for_bounces(bool p_enable) {
1674
use_texture_for_bounces = p_enable;
1675
}
1676
1677
bool LightmapGI::is_using_texture_for_bounces() const {
1678
return use_texture_for_bounces;
1679
}
1680
1681
void LightmapGI::set_interior(bool p_enable) {
1682
interior = p_enable;
1683
}
1684
1685
bool LightmapGI::is_interior() const {
1686
return interior;
1687
}
1688
1689
void LightmapGI::set_environment_mode(EnvironmentMode p_mode) {
1690
environment_mode = p_mode;
1691
notify_property_list_changed();
1692
}
1693
1694
LightmapGI::EnvironmentMode LightmapGI::get_environment_mode() const {
1695
return environment_mode;
1696
}
1697
1698
void LightmapGI::set_environment_custom_sky(const Ref<Sky> &p_sky) {
1699
environment_custom_sky = p_sky;
1700
}
1701
1702
Ref<Sky> LightmapGI::get_environment_custom_sky() const {
1703
return environment_custom_sky;
1704
}
1705
1706
void LightmapGI::set_environment_custom_color(const Color &p_color) {
1707
environment_custom_color = p_color;
1708
}
1709
1710
Color LightmapGI::get_environment_custom_color() const {
1711
return environment_custom_color;
1712
}
1713
1714
void LightmapGI::set_environment_custom_energy(float p_energy) {
1715
environment_custom_energy = p_energy;
1716
}
1717
1718
float LightmapGI::get_environment_custom_energy() const {
1719
return environment_custom_energy;
1720
}
1721
1722
void LightmapGI::set_bounces(int p_bounces) {
1723
ERR_FAIL_COND(p_bounces < 0 || p_bounces > 16);
1724
bounces = p_bounces;
1725
}
1726
1727
int LightmapGI::get_bounces() const {
1728
return bounces;
1729
}
1730
1731
void LightmapGI::set_bounce_indirect_energy(float p_indirect_energy) {
1732
ERR_FAIL_COND(p_indirect_energy < 0.0);
1733
bounce_indirect_energy = p_indirect_energy;
1734
}
1735
1736
float LightmapGI::get_bounce_indirect_energy() const {
1737
return bounce_indirect_energy;
1738
}
1739
1740
void LightmapGI::set_bias(float p_bias) {
1741
ERR_FAIL_COND(p_bias < 0.00001);
1742
bias = p_bias;
1743
}
1744
1745
float LightmapGI::get_bias() const {
1746
return bias;
1747
}
1748
1749
void LightmapGI::set_texel_scale(float p_multiplier) {
1750
ERR_FAIL_COND(p_multiplier < (0.01 - CMP_EPSILON));
1751
texel_scale = p_multiplier;
1752
}
1753
1754
float LightmapGI::get_texel_scale() const {
1755
return texel_scale;
1756
}
1757
1758
void LightmapGI::set_max_texture_size(int p_size) {
1759
ERR_FAIL_COND_MSG(p_size < 2048, vformat("The LightmapGI maximum texture size supplied (%d) is too small. The minimum allowed value is 2048.", p_size));
1760
ERR_FAIL_COND_MSG(p_size > 16384, vformat("The LightmapGI maximum texture size supplied (%d) is too large. The maximum allowed value is 16384.", p_size));
1761
max_texture_size = p_size;
1762
}
1763
1764
int LightmapGI::get_max_texture_size() const {
1765
return max_texture_size;
1766
}
1767
1768
void LightmapGI::set_supersampling_enabled(bool p_enable) {
1769
supersampling_enabled = p_enable;
1770
1771
notify_property_list_changed();
1772
}
1773
1774
bool LightmapGI::is_supersampling_enabled() const {
1775
return supersampling_enabled;
1776
}
1777
1778
void LightmapGI::set_supersampling_factor(float p_factor) {
1779
ERR_FAIL_COND(p_factor < 1);
1780
1781
supersampling_factor = p_factor;
1782
}
1783
1784
float LightmapGI::get_supersampling_factor() const {
1785
return supersampling_factor;
1786
}
1787
1788
void LightmapGI::set_generate_probes(GenerateProbes p_generate_probes) {
1789
gen_probes = p_generate_probes;
1790
}
1791
1792
LightmapGI::GenerateProbes LightmapGI::get_generate_probes() const {
1793
return gen_probes;
1794
}
1795
1796
void LightmapGI::set_camera_attributes(const Ref<CameraAttributes> &p_camera_attributes) {
1797
camera_attributes = p_camera_attributes;
1798
}
1799
1800
Ref<CameraAttributes> LightmapGI::get_camera_attributes() const {
1801
return camera_attributes;
1802
}
1803
1804
PackedStringArray LightmapGI::get_configuration_warnings() const {
1805
PackedStringArray warnings = VisualInstance3D::get_configuration_warnings();
1806
1807
#ifdef MODULE_LIGHTMAPPER_RD_ENABLED
1808
if (!DisplayServer::get_singleton()->can_create_rendering_device()) {
1809
warnings.push_back(vformat(RTR("Lightmaps can only be baked from a GPU that supports the RenderingDevice backends.\nYour GPU (%s) does not support RenderingDevice, as it does not support Vulkan, Direct3D 12, or Metal.\nLightmap baking will not be available on this device, although rendering existing baked lightmaps will work."), RenderingServer::get_singleton()->get_video_adapter_name()));
1810
return warnings;
1811
}
1812
1813
if (shadowmask_mode != LightmapGIData::SHADOWMASK_MODE_NONE && light_data.is_valid() && !light_data->has_shadowmask_textures()) {
1814
warnings.push_back(RTR("The lightmap has no baked shadowmask textures. Please rebake with the Shadowmask Mode set to anything other than None."));
1815
}
1816
1817
#elif defined(ANDROID_ENABLED) || defined(APPLE_EMBEDDED_ENABLED)
1818
warnings.push_back(vformat(RTR("Lightmaps cannot be baked on %s. Rendering existing baked lightmaps will still work."), OS::get_singleton()->get_name()));
1819
#else
1820
warnings.push_back(RTR("Lightmaps cannot be baked, as the `lightmapper_rd` module was disabled at compile-time. Rendering existing baked lightmaps will still work."));
1821
#endif
1822
1823
return warnings;
1824
}
1825
1826
void LightmapGI::_validate_property(PropertyInfo &p_property) const {
1827
if (!Engine::get_singleton()->is_editor_hint()) {
1828
return;
1829
}
1830
if (p_property.name == "supersampling_factor" && !supersampling_enabled) {
1831
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
1832
}
1833
if (p_property.name == "environment_custom_sky" && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
1834
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
1835
}
1836
if (p_property.name == "environment_custom_color" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR) {
1837
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
1838
}
1839
if (p_property.name == "environment_custom_energy" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
1840
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
1841
}
1842
if (p_property.name == "denoiser_strength" && !use_denoiser) {
1843
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
1844
}
1845
if (p_property.name == "denoiser_range" && !use_denoiser) {
1846
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
1847
}
1848
}
1849
1850
void LightmapGI::_bind_methods() {
1851
ClassDB::bind_method(D_METHOD("set_light_data", "data"), &LightmapGI::set_light_data);
1852
ClassDB::bind_method(D_METHOD("get_light_data"), &LightmapGI::get_light_data);
1853
1854
ClassDB::bind_method(D_METHOD("set_bake_quality", "bake_quality"), &LightmapGI::set_bake_quality);
1855
ClassDB::bind_method(D_METHOD("get_bake_quality"), &LightmapGI::get_bake_quality);
1856
1857
ClassDB::bind_method(D_METHOD("set_bounces", "bounces"), &LightmapGI::set_bounces);
1858
ClassDB::bind_method(D_METHOD("get_bounces"), &LightmapGI::get_bounces);
1859
1860
ClassDB::bind_method(D_METHOD("set_bounce_indirect_energy", "bounce_indirect_energy"), &LightmapGI::set_bounce_indirect_energy);
1861
ClassDB::bind_method(D_METHOD("get_bounce_indirect_energy"), &LightmapGI::get_bounce_indirect_energy);
1862
1863
ClassDB::bind_method(D_METHOD("set_generate_probes", "subdivision"), &LightmapGI::set_generate_probes);
1864
ClassDB::bind_method(D_METHOD("get_generate_probes"), &LightmapGI::get_generate_probes);
1865
1866
ClassDB::bind_method(D_METHOD("set_bias", "bias"), &LightmapGI::set_bias);
1867
ClassDB::bind_method(D_METHOD("get_bias"), &LightmapGI::get_bias);
1868
1869
ClassDB::bind_method(D_METHOD("set_environment_mode", "mode"), &LightmapGI::set_environment_mode);
1870
ClassDB::bind_method(D_METHOD("get_environment_mode"), &LightmapGI::get_environment_mode);
1871
1872
ClassDB::bind_method(D_METHOD("set_environment_custom_sky", "sky"), &LightmapGI::set_environment_custom_sky);
1873
ClassDB::bind_method(D_METHOD("get_environment_custom_sky"), &LightmapGI::get_environment_custom_sky);
1874
1875
ClassDB::bind_method(D_METHOD("set_environment_custom_color", "color"), &LightmapGI::set_environment_custom_color);
1876
ClassDB::bind_method(D_METHOD("get_environment_custom_color"), &LightmapGI::get_environment_custom_color);
1877
1878
ClassDB::bind_method(D_METHOD("set_environment_custom_energy", "energy"), &LightmapGI::set_environment_custom_energy);
1879
ClassDB::bind_method(D_METHOD("get_environment_custom_energy"), &LightmapGI::get_environment_custom_energy);
1880
1881
ClassDB::bind_method(D_METHOD("set_texel_scale", "texel_scale"), &LightmapGI::set_texel_scale);
1882
ClassDB::bind_method(D_METHOD("get_texel_scale"), &LightmapGI::get_texel_scale);
1883
1884
ClassDB::bind_method(D_METHOD("set_max_texture_size", "max_texture_size"), &LightmapGI::set_max_texture_size);
1885
ClassDB::bind_method(D_METHOD("get_max_texture_size"), &LightmapGI::get_max_texture_size);
1886
1887
ClassDB::bind_method(D_METHOD("set_supersampling_enabled", "enable"), &LightmapGI::set_supersampling_enabled);
1888
ClassDB::bind_method(D_METHOD("is_supersampling_enabled"), &LightmapGI::is_supersampling_enabled);
1889
1890
ClassDB::bind_method(D_METHOD("set_supersampling_factor", "factor"), &LightmapGI::set_supersampling_factor);
1891
ClassDB::bind_method(D_METHOD("get_supersampling_factor"), &LightmapGI::get_supersampling_factor);
1892
1893
ClassDB::bind_method(D_METHOD("set_use_denoiser", "use_denoiser"), &LightmapGI::set_use_denoiser);
1894
ClassDB::bind_method(D_METHOD("is_using_denoiser"), &LightmapGI::is_using_denoiser);
1895
1896
ClassDB::bind_method(D_METHOD("set_denoiser_strength", "denoiser_strength"), &LightmapGI::set_denoiser_strength);
1897
ClassDB::bind_method(D_METHOD("get_denoiser_strength"), &LightmapGI::get_denoiser_strength);
1898
1899
ClassDB::bind_method(D_METHOD("set_denoiser_range", "denoiser_range"), &LightmapGI::set_denoiser_range);
1900
ClassDB::bind_method(D_METHOD("get_denoiser_range"), &LightmapGI::get_denoiser_range);
1901
1902
ClassDB::bind_method(D_METHOD("set_interior", "enable"), &LightmapGI::set_interior);
1903
ClassDB::bind_method(D_METHOD("is_interior"), &LightmapGI::is_interior);
1904
1905
ClassDB::bind_method(D_METHOD("set_directional", "directional"), &LightmapGI::set_directional);
1906
ClassDB::bind_method(D_METHOD("is_directional"), &LightmapGI::is_directional);
1907
1908
ClassDB::bind_method(D_METHOD("set_shadowmask_mode", "mode"), &LightmapGI::set_shadowmask_mode);
1909
ClassDB::bind_method(D_METHOD("get_shadowmask_mode"), &LightmapGI::get_shadowmask_mode);
1910
1911
ClassDB::bind_method(D_METHOD("set_use_texture_for_bounces", "use_texture_for_bounces"), &LightmapGI::set_use_texture_for_bounces);
1912
ClassDB::bind_method(D_METHOD("is_using_texture_for_bounces"), &LightmapGI::is_using_texture_for_bounces);
1913
1914
ClassDB::bind_method(D_METHOD("set_camera_attributes", "camera_attributes"), &LightmapGI::set_camera_attributes);
1915
ClassDB::bind_method(D_METHOD("get_camera_attributes"), &LightmapGI::get_camera_attributes);
1916
1917
// ClassDB::bind_method(D_METHOD("bake", "from_node"), &LightmapGI::bake, DEFVAL(Variant()));
1918
1919
ADD_GROUP("Tweaks", "");
1920
ADD_PROPERTY(PropertyInfo(Variant::INT, "quality", PROPERTY_HINT_ENUM, "Low,Medium,High,Ultra"), "set_bake_quality", "get_bake_quality");
1921
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "supersampling"), "set_supersampling_enabled", "is_supersampling_enabled");
1922
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "supersampling_factor", PROPERTY_HINT_RANGE, "1,8,1"), "set_supersampling_factor", "get_supersampling_factor");
1923
ADD_PROPERTY(PropertyInfo(Variant::INT, "bounces", PROPERTY_HINT_RANGE, "0,6,1,or_greater"), "set_bounces", "get_bounces");
1924
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bounce_indirect_energy", PROPERTY_HINT_RANGE, "0,2,0.01"), "set_bounce_indirect_energy", "get_bounce_indirect_energy");
1925
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "directional"), "set_directional", "is_directional");
1926
ADD_PROPERTY(PropertyInfo(Variant::INT, "shadowmask_mode", PROPERTY_HINT_ENUM, "None,Replace,Overlay"), "set_shadowmask_mode", "get_shadowmask_mode");
1927
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_texture_for_bounces"), "set_use_texture_for_bounces", "is_using_texture_for_bounces");
1928
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior"), "set_interior", "is_interior");
1929
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_denoiser"), "set_use_denoiser", "is_using_denoiser");
1930
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "denoiser_strength", PROPERTY_HINT_RANGE, "0.001,0.2,0.001,or_greater"), "set_denoiser_strength", "get_denoiser_strength");
1931
ADD_PROPERTY(PropertyInfo(Variant::INT, "denoiser_range", PROPERTY_HINT_RANGE, "1,20"), "set_denoiser_range", "get_denoiser_range");
1932
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bias", PROPERTY_HINT_RANGE, "0.00001,0.1,0.00001,or_greater"), "set_bias", "get_bias");
1933
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "texel_scale", PROPERTY_HINT_RANGE, "0.01,100.0,0.01"), "set_texel_scale", "get_texel_scale");
1934
ADD_PROPERTY(PropertyInfo(Variant::INT, "max_texture_size", PROPERTY_HINT_RANGE, "2048,16384,1"), "set_max_texture_size", "get_max_texture_size");
1935
ADD_GROUP("Environment", "environment_");
1936
ADD_PROPERTY(PropertyInfo(Variant::INT, "environment_mode", PROPERTY_HINT_ENUM, "Disabled,Scene,Custom Sky,Custom Color"), "set_environment_mode", "get_environment_mode");
1937
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "environment_custom_sky", PROPERTY_HINT_RESOURCE_TYPE, Sky::get_class_static()), "set_environment_custom_sky", "get_environment_custom_sky");
1938
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "environment_custom_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_environment_custom_color", "get_environment_custom_color");
1939
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "environment_custom_energy", PROPERTY_HINT_RANGE, "0,64,0.01"), "set_environment_custom_energy", "get_environment_custom_energy");
1940
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "camera_attributes", PROPERTY_HINT_RESOURCE_TYPE, "CameraAttributesPractical,CameraAttributesPhysical"), "set_camera_attributes", "get_camera_attributes");
1941
ADD_GROUP("Gen Probes", "generate_probes_");
1942
ADD_PROPERTY(PropertyInfo(Variant::INT, "generate_probes_subdiv", PROPERTY_HINT_ENUM, "Disabled,4,8,16,32"), "set_generate_probes", "get_generate_probes");
1943
ADD_GROUP("Data", "");
1944
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "light_data", PROPERTY_HINT_RESOURCE_TYPE, LightmapGIData::get_class_static()), "set_light_data", "get_light_data");
1945
1946
BIND_ENUM_CONSTANT(BAKE_QUALITY_LOW);
1947
BIND_ENUM_CONSTANT(BAKE_QUALITY_MEDIUM);
1948
BIND_ENUM_CONSTANT(BAKE_QUALITY_HIGH);
1949
BIND_ENUM_CONSTANT(BAKE_QUALITY_ULTRA);
1950
1951
BIND_ENUM_CONSTANT(GENERATE_PROBES_DISABLED);
1952
BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_4);
1953
BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_8);
1954
BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_16);
1955
BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_32);
1956
1957
BIND_ENUM_CONSTANT(BAKE_ERROR_OK);
1958
BIND_ENUM_CONSTANT(BAKE_ERROR_NO_SCENE_ROOT);
1959
BIND_ENUM_CONSTANT(BAKE_ERROR_FOREIGN_DATA);
1960
BIND_ENUM_CONSTANT(BAKE_ERROR_NO_LIGHTMAPPER);
1961
BIND_ENUM_CONSTANT(BAKE_ERROR_NO_SAVE_PATH);
1962
BIND_ENUM_CONSTANT(BAKE_ERROR_NO_MESHES);
1963
BIND_ENUM_CONSTANT(BAKE_ERROR_MESHES_INVALID);
1964
BIND_ENUM_CONSTANT(BAKE_ERROR_CANT_CREATE_IMAGE);
1965
BIND_ENUM_CONSTANT(BAKE_ERROR_USER_ABORTED);
1966
BIND_ENUM_CONSTANT(BAKE_ERROR_TEXTURE_SIZE_TOO_SMALL);
1967
BIND_ENUM_CONSTANT(BAKE_ERROR_LIGHTMAP_TOO_SMALL);
1968
BIND_ENUM_CONSTANT(BAKE_ERROR_ATLAS_TOO_SMALL);
1969
1970
BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_DISABLED);
1971
BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_SCENE);
1972
BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_CUSTOM_SKY);
1973
BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_CUSTOM_COLOR);
1974
}
1975
1976
LightmapGI::LightmapGI() {
1977
}
1978
1979