Files
test2/source/blender/blenkernel/intern/mesh_runtime.cc

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

536 lines
16 KiB
C++
Raw Normal View History

/* SPDX-FileCopyrightText: 2005 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
2018-05-08 10:07:21 +02:00
/** \file
* \ingroup bke
2018-05-08 10:07:21 +02:00
*/
#include "BLI_array_utils.hh"
2018-05-08 10:07:21 +02:00
#include "BLI_math_geom.h"
Geometry Nodes: support baking data block references With this patch, materials are kept intact in simulation zones and bake nodes without any additional user action. This implements the design proposed in #108410 to support referencing data-blocks (only materials for now) in the baked data. The task also describes why this is not a trivial issue. A previous attempt was implemented in #109703 but it didn't work well-enough. The solution is to have an explicit `name (+ library name) -> data-block` mapping that is stored in the modifier for each bake node and simulation zone. The `library name` is necessary for it to be unique within a .blend file. Note that this refers to the name of the `Library` data-block and not a file path. The baked data only contains the names of the used data-blocks. When the baked data is loaded, the correct material data-block is looked up from the mapping. ### Automatic Mapping Generation The most tricky aspect of this approach is to make it feel mostly automatic. From the user point-of-view, it should just work. Therefore, we don't want the user to have to create the mapping manually in the majority of cases. Creating the mapping automatically is difficult because the data-blocks that should become part of the mapping are only known during depsgraph evaluation. So we somehow have to gather the missing data blocks during evaluation and then write the new mappings back to the original data. While writing back to original data is something we do in some cases already, the situation here is different, because we are actually creating new relations between data-blocks. This also means that we'll have to do user-counting. Since user counts in data-blocks are *not* atomic, we can't do that from multiple threads at the same time. Also, under some circumstances, it may be necessary to trigger depsgraph evaluation again after the write-back because it actually affects the result. To solve this, a small new API is added in `DEG_depsgraph_writeback_sync.hh`. It allows gathering tasks which write back to original data in a synchronous way which may also require a reevaluation. ### Accessing the Mapping A new `BakeDataBlockMap` is passed to geometry nodes evaluation by the modifier. This map allows getting the `ID` pointer that should be used for a specific data-block name that is stored in baked data. It's also used to gather all the missing data mappings during evaluation. ### Weak ID References The baked/cached geometries may have references to other data-blocks (currently only materials, but in the future also e.g. instanced objects/collections). However, the pointers of these data-blocks are not stable over time. That is especially true when storing/loading the data from disk, but also just when playing back the animation. Therefore, the used data-blocks have to referenced in a different way at run-time. This is solved by adding `std::unique_ptr<bake::BakeMaterialsList>` to the run-time data of various geometry data-blocks. If the data-block is cached over a longer period of time (such that material pointers can't be used directly), it stores the material name (+ library name) used by each material slot. When the geometry is used again, the material pointers are restored using these weak name references and the `BakeDataBlockMap`. ### Manual Mapping Management There is a new `Data-Blocks` panel in the bake settings in the node editor sidebar that allows inspecting and modifying the data-blocks that are used when baking. The user can change what data-block a specific name is mapped to. Pull Request: https://projects.blender.org/blender/blender/pulls/117043
2024-02-01 09:21:55 +01:00
#include "BKE_bake_data_block_id.hh"
#include "BKE_bvhutils.hh"
#include "BKE_customdata.hh"
#include "BKE_editmesh_cache.hh"
2024-01-15 12:44:04 -05:00
#include "BKE_lib_id.hh"
#include "BKE_mesh.hh"
#include "BKE_mesh_mapping.hh"
#include "BKE_mesh_runtime.hh"
#include "BKE_shrinkwrap.hh"
#include "BKE_subdiv_ccg.hh"
2018-05-08 10:07:21 +02:00
Mesh: Move positions to a generic attribute **Changes** As described in T93602, this patch removes all use of the `MVert` struct, replacing it with a generic named attribute with the name `"position"`, consistent with other geometry types. Variable names have been changed from `verts` to `positions`, to align with the attribute name and the more generic design (positions are not vertices, they are just an attribute stored on the point domain). This change is made possible by previous commits that moved all other data out of `MVert` to runtime data or other generic attributes. What remains is mostly a simple type change. Though, the type still shows up 859 times, so the patch is quite large. One compromise is that now `CD_MASK_BAREMESH` now contains `CD_PROP_FLOAT3`. With the general move towards generic attributes over custom data types, we are removing use of these type masks anyway. **Benefits** The most obvious benefit is reduced memory usage and the benefits that brings in memory-bound situations. `float3` is only 3 bytes, in comparison to `MVert` which was 4. When there are millions of vertices this starts to matter more. The other benefits come from using a more generic type. Instead of writing algorithms specifically for `MVert`, code can just use arrays of vectors. This will allow eliminating many temporary arrays or wrappers used to extract positions. Many possible improvements aren't implemented in this patch, though I did switch simplify or remove the process of creating temporary position arrays in a few places. The design clarity that "positions are just another attribute" brings allows removing explicit copying of vertices in some procedural operations-- they are just processed like most other attributes. **Performance** This touches so many areas that it's hard to benchmark exhaustively, but I observed some areas as examples. * The mesh line node with 4 million count was 1.5x (8ms to 12ms) faster. * The Spring splash screen went from ~4.3 to ~4.5 fps. * The subdivision surface modifier/node was slightly faster RNA access through Python may be slightly slower, since now we need a name lookup instead of just a custom data type lookup for each index. **Future Improvements** * Remove uses of "vert_coords" functions: * `BKE_mesh_vert_coords_alloc` * `BKE_mesh_vert_coords_get` * `BKE_mesh_vert_coords_apply{_with_mat4}` * Remove more hidden copying of positions * General simplification now possible in many areas * Convert more code to C++ to use `float3` instead of `float[3]` * Currently `reinterpret_cast` is used for those C-API functions Differential Revision: https://developer.blender.org/D15982
2023-01-10 00:10:43 -05:00
using blender::float3;
Mesh: Remove redundant custom data pointers For copy-on-write, we want to share attribute arrays between meshes where possible. Mutable pointers like `Mesh.mvert` make that difficult by making ownership vague. They also make code more complex by adding redundancy. The simplest solution is just removing them and retrieving layers from `CustomData` as needed. Similar changes have already been applied to curves and point clouds (e9f82d3dc7ee, 410a6efb747f). Removing use of the pointers generally makes code more obvious and more reusable. Mesh data is now accessed with a C++ API (`Mesh::edges()` or `Mesh::edges_for_write()`), and a C API (`BKE_mesh_edges(mesh)`). The CoW changes this commit makes possible are described in T95845 and T95842, and started in D14139 and D14140. The change also simplifies the ongoing mesh struct-of-array refactors from T95965. **RNA/Python Access Performance** Theoretically, accessing mesh elements with the RNA API may become slower, since the layer needs to be found on every random access. However, overhead is already high enough that this doesn't make a noticible differenc, and performance is actually improved in some cases. Random access can be up to 10% faster, but other situations might be a bit slower. Generally using `foreach_get/set` are the best way to improve performance. See the differential revision for more discussion about Python performance. Cycles has been updated to use raw pointers and the internal Blender mesh types, mostly because there is no sense in having this overhead when it's already compiled with Blender. In my tests this roughly halves the Cycles mesh creation time (0.19s to 0.10s for a 1 million face grid). Differential Revision: https://developer.blender.org/D15488
2022-09-05 11:56:34 -05:00
using blender::MutableSpan;
using blender::Span;
/* -------------------------------------------------------------------- */
/** \name Mesh Runtime Struct Utils
* \{ */
2018-05-08 10:07:21 +02:00
namespace blender::bke {
static void free_mesh_eval(MeshRuntime &mesh_runtime)
{
if (mesh_runtime.mesh_eval != nullptr) {
BKE_id_free(nullptr, mesh_runtime.mesh_eval);
mesh_runtime.mesh_eval = nullptr;
}
}
static void free_batch_cache(MeshRuntime &mesh_runtime)
{
if (mesh_runtime.batch_cache) {
BKE_mesh_batch_cache_free(mesh_runtime.batch_cache);
mesh_runtime.batch_cache = nullptr;
}
}
static void free_bvh_caches(MeshRuntime &mesh_runtime)
{
mesh_runtime.bvh_cache_verts.tag_dirty();
mesh_runtime.bvh_cache_edges.tag_dirty();
mesh_runtime.bvh_cache_faces.tag_dirty();
mesh_runtime.bvh_cache_corner_tris.tag_dirty();
mesh_runtime.bvh_cache_corner_tris_no_hidden.tag_dirty();
mesh_runtime.bvh_cache_loose_verts.tag_dirty();
mesh_runtime.bvh_cache_loose_verts_no_hidden.tag_dirty();
mesh_runtime.bvh_cache_loose_edges.tag_dirty();
mesh_runtime.bvh_cache_loose_edges_no_hidden.tag_dirty();
}
2024-01-19 12:08:40 -05:00
MeshRuntime::MeshRuntime() = default;
MeshRuntime::~MeshRuntime()
{
free_mesh_eval(*this);
free_batch_cache(*this);
}
static int reset_bits_and_count(MutableBitSpan bits, const Span<int> indices_to_reset)
{
int count = bits.size();
for (const int i : indices_to_reset) {
if (bits[i]) {
bits[i].reset();
count--;
}
}
return count;
}
static void bit_vector_with_reset_bits_or_empty(const Span<int> indices_to_reset,
const int indexed_elems_num,
BitVector<> &r_bits,
int &r_count)
{
r_bits.resize(0);
r_bits.resize(indexed_elems_num, true);
r_count = reset_bits_and_count(r_bits, indices_to_reset);
if (r_count == 0) {
r_bits.clear_and_shrink();
}
}
/**
* If there are no loose edges and no loose vertices, all vertices are used by faces.
*/
static void try_tag_verts_no_face_none(const Mesh &mesh)
{
if (!mesh.runtime->loose_edges_cache.is_cached() || mesh.loose_edges().count > 0) {
return;
}
if (!mesh.runtime->loose_verts_cache.is_cached() || mesh.loose_verts().count > 0) {
return;
}
mesh.runtime->verts_no_face_cache.ensure([&](LooseVertCache &r_data) {
r_data.is_loose_bits.clear_and_shrink();
r_data.count = 0;
});
}
} // namespace blender::bke
blender::Span<int> Mesh::corner_to_face_map() const
{
using namespace blender;
this->runtime->corner_to_face_map_cache.ensure([&](Array<int> &r_data) {
const OffsetIndices faces = this->faces();
r_data = bke::mesh::build_corner_to_face_map(faces);
});
return this->runtime->corner_to_face_map_cache.data();
}
blender::OffsetIndices<int> Mesh::vert_to_face_map_offsets() const
{
using namespace blender;
this->runtime->vert_to_face_offset_cache.ensure([&](Array<int> &r_data) {
r_data = Array<int>(this->verts_num + 1, 0);
offset_indices::build_reverse_offsets(this->corner_verts(), r_data);
});
return OffsetIndices<int>(this->runtime->vert_to_face_offset_cache.data());
}
blender::GroupedSpan<int> Mesh::vert_to_face_map() const
{
using namespace blender;
const OffsetIndices offsets = this->vert_to_face_map_offsets();
this->runtime->vert_to_face_map_cache.ensure([&](Array<int> &r_data) {
r_data.reinitialize(this->corners_num);
if (this->runtime->vert_to_corner_map_cache.is_cached() &&
this->runtime->corner_to_face_map_cache.is_cached())
{
/* The vertex to face cache can be built from the vertex to face corner
* and face corner to face maps if they are both already cached. */
array_utils::gather(this->runtime->corner_to_face_map_cache.data().as_span(),
this->runtime->vert_to_corner_map_cache.data().as_span(),
r_data.as_mutable_span());
}
else {
bke::mesh::build_vert_to_face_indices(this->faces(), this->corner_verts(), offsets, r_data);
}
});
return {offsets, this->runtime->vert_to_face_map_cache.data()};
}
blender::GroupedSpan<int> Mesh::vert_to_corner_map() const
{
using namespace blender;
const OffsetIndices offsets = this->vert_to_face_map_offsets();
this->runtime->vert_to_corner_map_cache.ensure([&](Array<int> &r_data) {
r_data = bke::mesh::build_vert_to_corner_indices(this->corner_verts(), offsets);
});
return {offsets, this->runtime->vert_to_corner_map_cache.data()};
}
const blender::bke::LooseVertCache &Mesh::loose_verts() const
{
using namespace blender::bke;
this->runtime->loose_verts_cache.ensure([&](LooseVertCache &r_data) {
const Span<int> verts = this->edges().cast<int>();
bit_vector_with_reset_bits_or_empty(
verts, this->verts_num, r_data.is_loose_bits, r_data.count);
});
return this->runtime->loose_verts_cache.data();
}
const blender::bke::LooseVertCache &Mesh::verts_no_face() const
{
using namespace blender::bke;
this->runtime->verts_no_face_cache.ensure([&](LooseVertCache &r_data) {
const Span<int> verts = this->corner_verts();
bit_vector_with_reset_bits_or_empty(
verts, this->verts_num, r_data.is_loose_bits, r_data.count);
});
return this->runtime->verts_no_face_cache.data();
}
bool Mesh::no_overlapping_topology() const
{
return this->flag & ME_NO_OVERLAPPING_TOPOLOGY;
}
const blender::bke::LooseEdgeCache &Mesh::loose_edges() const
{
using namespace blender::bke;
this->runtime->loose_edges_cache.ensure([&](LooseEdgeCache &r_data) {
const Span<int> edges = this->corner_edges();
bit_vector_with_reset_bits_or_empty(
edges, this->edges_num, r_data.is_loose_bits, r_data.count);
});
return this->runtime->loose_edges_cache.data();
}
void Mesh::tag_loose_verts_none() const
{
using namespace blender::bke;
this->runtime->loose_verts_cache.ensure([&](LooseVertCache &r_data) {
r_data.is_loose_bits.clear_and_shrink();
r_data.count = 0;
});
try_tag_verts_no_face_none(*this);
}
void Mesh::tag_loose_edges_none() const
{
using namespace blender::bke;
this->runtime->loose_edges_cache.ensure([&](LooseEdgeCache &r_data) {
r_data.is_loose_bits.clear_and_shrink();
r_data.count = 0;
});
try_tag_verts_no_face_none(*this);
}
void Mesh::tag_overlapping_none()
{
using namespace blender::bke;
this->flag |= ME_NO_OVERLAPPING_TOPOLOGY;
}
namespace blender::bke {
void TrianglesCache::freeze()
{
this->frozen = true;
this->dirty_while_frozen = false;
}
void TrianglesCache::unfreeze()
{
this->frozen = false;
if (this->dirty_while_frozen) {
this->data.tag_dirty();
}
this->dirty_while_frozen = false;
}
void TrianglesCache::tag_dirty()
{
if (this->frozen) {
this->dirty_while_frozen = true;
}
else {
this->data.tag_dirty();
}
}
} // namespace blender::bke
blender::Span<blender::int3> Mesh::corner_tris() const
2018-05-08 10:07:21 +02:00
{
this->runtime->corner_tris_cache.data.ensure([&](blender::Array<blender::int3> &r_data) {
Mesh: Move positions to a generic attribute **Changes** As described in T93602, this patch removes all use of the `MVert` struct, replacing it with a generic named attribute with the name `"position"`, consistent with other geometry types. Variable names have been changed from `verts` to `positions`, to align with the attribute name and the more generic design (positions are not vertices, they are just an attribute stored on the point domain). This change is made possible by previous commits that moved all other data out of `MVert` to runtime data or other generic attributes. What remains is mostly a simple type change. Though, the type still shows up 859 times, so the patch is quite large. One compromise is that now `CD_MASK_BAREMESH` now contains `CD_PROP_FLOAT3`. With the general move towards generic attributes over custom data types, we are removing use of these type masks anyway. **Benefits** The most obvious benefit is reduced memory usage and the benefits that brings in memory-bound situations. `float3` is only 3 bytes, in comparison to `MVert` which was 4. When there are millions of vertices this starts to matter more. The other benefits come from using a more generic type. Instead of writing algorithms specifically for `MVert`, code can just use arrays of vectors. This will allow eliminating many temporary arrays or wrappers used to extract positions. Many possible improvements aren't implemented in this patch, though I did switch simplify or remove the process of creating temporary position arrays in a few places. The design clarity that "positions are just another attribute" brings allows removing explicit copying of vertices in some procedural operations-- they are just processed like most other attributes. **Performance** This touches so many areas that it's hard to benchmark exhaustively, but I observed some areas as examples. * The mesh line node with 4 million count was 1.5x (8ms to 12ms) faster. * The Spring splash screen went from ~4.3 to ~4.5 fps. * The subdivision surface modifier/node was slightly faster RNA access through Python may be slightly slower, since now we need a name lookup instead of just a custom data type lookup for each index. **Future Improvements** * Remove uses of "vert_coords" functions: * `BKE_mesh_vert_coords_alloc` * `BKE_mesh_vert_coords_get` * `BKE_mesh_vert_coords_apply{_with_mat4}` * Remove more hidden copying of positions * General simplification now possible in many areas * Convert more code to C++ to use `float3` instead of `float[3]` * Currently `reinterpret_cast` is used for those C-API functions Differential Revision: https://developer.blender.org/D15982
2023-01-10 00:10:43 -05:00
const Span<float3> positions = this->vert_positions();
const blender::OffsetIndices faces = this->faces();
Mesh: Replace MLoop struct with generic attributes Implements #102359. Split the `MLoop` struct into two separate integer arrays called `corner_verts` and `corner_edges`, referring to the vertex each corner is attached to and the next edge around the face at each corner. These arrays can be sliced to give access to the edges or vertices in a face. Then they are often referred to as "poly_verts" or "poly_edges". The main benefits are halving the necessary memory bandwidth when only one array is used and simplifications from using regular integer indices instead of a special-purpose struct. The commit also starts a renaming from "loop" to "corner" in mesh code. Like the other mesh struct of array refactors, forward compatibility is kept by writing files with the older format. This will be done until 4.0 to ease the transition process. Looking at a small portion of the patch should give a good impression for the rest of the changes. I tried to make the changes as small as possible so it's easy to tell the correctness from the diff. Though I found Blender developers have been very inventive over the last decade when finding different ways to loop over the corners in a face. For performance, nearly every piece of code that deals with `Mesh` is slightly impacted. Any algorithm that is memory bottle-necked should see an improvement. For example, here is a comparison of interpolating a vertex float attribute to face corners (Ryzen 3700x): **Before** (Average: 3.7 ms, Min: 3.4 ms) ``` threading::parallel_for(loops.index_range(), 4096, [&](IndexRange range) { for (const int64_t i : range) { dst[i] = src[loops[i].v]; } }); ``` **After** (Average: 2.9 ms, Min: 2.6 ms) ``` array_utils::gather(src, corner_verts, dst); ``` That's an improvement of 28% to the average timings, and it's also a simplification, since an index-based routine can be used instead. For more examples using the new arrays, see the design task. Pull Request: https://projects.blender.org/blender/blender/pulls/104424
2023-03-20 15:55:13 +01:00
const Span<int> corner_verts = this->corner_verts();
r_data.reinitialize(poly_to_tri_count(faces.size(), corner_verts.size()));
if (BKE_mesh_face_normals_are_dirty(this)) {
blender::bke::mesh::corner_tris_calc(positions, faces, corner_verts, r_data);
2018-05-08 10:07:21 +02:00
}
else {
blender::bke::mesh::corner_tris_calc_with_normals(
positions, faces, corner_verts, this->face_normals(), r_data);
}
});
return this->runtime->corner_tris_cache.data.data();
2018-05-08 10:07:21 +02:00
}
blender::Span<int> Mesh::corner_tri_faces() const
{
using namespace blender;
this->runtime->corner_tri_faces_cache.ensure([&](blender::Array<int> &r_data) {
const OffsetIndices faces = this->faces();
r_data.reinitialize(poly_to_tri_count(faces.size(), this->corners_num));
bke::mesh::corner_tris_calc_face_indices(faces, r_data);
});
return this->runtime->corner_tri_faces_cache.data();
}
int BKE_mesh_runtime_corner_tris_len(const Mesh *mesh)
2018-05-08 10:07:21 +02:00
{
/* Allow returning the size without calculating the cache. */
return poly_to_tri_count(mesh->faces_num, mesh->corners_num);
2018-05-08 10:07:21 +02:00
}
void BKE_mesh_runtime_ensure_edit_data(Mesh *mesh)
{
if (!mesh->runtime->edit_data) {
mesh->runtime->edit_data = std::make_unique<blender::bke::EditMeshData>();
}
}
void BKE_mesh_runtime_clear_cache(Mesh *mesh)
{
using namespace blender::bke;
free_mesh_eval(*mesh->runtime);
free_batch_cache(*mesh->runtime);
mesh->runtime->edit_data.reset();
BKE_mesh_runtime_clear_geometry(mesh);
}
void BKE_mesh_runtime_clear_geometry(Mesh *mesh)
{
/* Tagging shared caches dirty will free the allocated data if there is only one user. */
free_bvh_caches(*mesh->runtime);
mesh->runtime->subdiv_ccg.reset();
mesh->runtime->bounds_cache.tag_dirty();
mesh->runtime->vert_to_face_offset_cache.tag_dirty();
mesh->runtime->vert_to_face_map_cache.tag_dirty();
mesh->runtime->vert_to_corner_map_cache.tag_dirty();
mesh->runtime->corner_to_face_map_cache.tag_dirty();
mesh->runtime->vert_normals_cache.tag_dirty();
Mesh: Add "free" custom normals Add a "dumb vector" storage option for custom normals, with the "custom_normal" attribute. Adjust the mesh normals caching to provide this attribute if it's available, and add a geometry node to store custom normals. ## Free Normals They're called "free" in the sense that they're just direction vectors in the object's local space, rather than the existing "smooth corner fan space" storage. They're also "free" in that they make further normals calculation very inexpensive, since we just use the custom normals instead. That's a big improvement from the existing custom normals storage, which usually significantly decreases viewport performance. For example, in a simple test file just storing the vertex normals on a UV sphere, using free normals gives 25 times better playback performance and 10% lower memory usage. Free normals are adjusted when applying a transformation to the entire mesh or when realizing instances, but in general they're not updated for vertex deformations. ## Set Mesh Normal Node The new geometry node allows storing free custom normals as well as the existing corner fan space normals. When free normals are chosen, free normals can be stored on vertices, faces, or face corners. Using the face corner domain is necessary to bake existing mixed sharp and smooth edges into the custom normal vectors. The node also has a mode for storing edge and mesh sharpness, meant as a "soft" replacement to the "Set Shade Smooth" node that's a bit more convenient. ## Normal Input Node The normal node outputs free custom normals mixed to whatever domain is requested. A "true normal" output that ignores custom normals and sharpness is added as well. Across Blender, custom normals are generally accessed via face and vertex normals, when "true normals" are not requested explicitly. In many cases that means they are mixed from the face corner domain. ## Future Work 1. There are many places where propagation of free normals could be improved. They should probably be normalized after mixing, and it may be useful to not just use 0 vectors for new elements. To keep the scope of this change smaller, that sort of thing generally isn't handled here. Searching `CD_NORMAL` gives a hint of where better propagation could be useful. 2. Free normals are displayed properly in edit mode, but the existing custom normal editing operators don't work with free normals yet. This will hopefully be fairly straightforward since custom normals are usually converted to `float3` for editing anyway. Edit mode changes aren't included here because they're unnecessary for the procedural custom normals use cases. 3. Most importers can probably switch to using free normals instead, or at least provide an option for it. That will give a significant import performance improvement, and an improvement of Blender's FPS for imported scenes too. Pull Request: https://projects.blender.org/blender/blender/pulls/132583
2025-04-04 19:16:51 +02:00
mesh->runtime->vert_normals_true_cache.tag_dirty();
mesh->runtime->face_normals_cache.tag_dirty();
Mesh: Add "free" custom normals Add a "dumb vector" storage option for custom normals, with the "custom_normal" attribute. Adjust the mesh normals caching to provide this attribute if it's available, and add a geometry node to store custom normals. ## Free Normals They're called "free" in the sense that they're just direction vectors in the object's local space, rather than the existing "smooth corner fan space" storage. They're also "free" in that they make further normals calculation very inexpensive, since we just use the custom normals instead. That's a big improvement from the existing custom normals storage, which usually significantly decreases viewport performance. For example, in a simple test file just storing the vertex normals on a UV sphere, using free normals gives 25 times better playback performance and 10% lower memory usage. Free normals are adjusted when applying a transformation to the entire mesh or when realizing instances, but in general they're not updated for vertex deformations. ## Set Mesh Normal Node The new geometry node allows storing free custom normals as well as the existing corner fan space normals. When free normals are chosen, free normals can be stored on vertices, faces, or face corners. Using the face corner domain is necessary to bake existing mixed sharp and smooth edges into the custom normal vectors. The node also has a mode for storing edge and mesh sharpness, meant as a "soft" replacement to the "Set Shade Smooth" node that's a bit more convenient. ## Normal Input Node The normal node outputs free custom normals mixed to whatever domain is requested. A "true normal" output that ignores custom normals and sharpness is added as well. Across Blender, custom normals are generally accessed via face and vertex normals, when "true normals" are not requested explicitly. In many cases that means they are mixed from the face corner domain. ## Future Work 1. There are many places where propagation of free normals could be improved. They should probably be normalized after mixing, and it may be useful to not just use 0 vectors for new elements. To keep the scope of this change smaller, that sort of thing generally isn't handled here. Searching `CD_NORMAL` gives a hint of where better propagation could be useful. 2. Free normals are displayed properly in edit mode, but the existing custom normal editing operators don't work with free normals yet. This will hopefully be fairly straightforward since custom normals are usually converted to `float3` for editing anyway. Edit mode changes aren't included here because they're unnecessary for the procedural custom normals use cases. 3. Most importers can probably switch to using free normals instead, or at least provide an option for it. That will give a significant import performance improvement, and an improvement of Blender's FPS for imported scenes too. Pull Request: https://projects.blender.org/blender/blender/pulls/132583
2025-04-04 19:16:51 +02:00
mesh->runtime->face_normals_true_cache.tag_dirty();
mesh->runtime->corner_normals_cache.tag_dirty();
mesh->runtime->loose_edges_cache.tag_dirty();
mesh->runtime->loose_verts_cache.tag_dirty();
mesh->runtime->verts_no_face_cache.tag_dirty();
mesh->runtime->corner_tris_cache.data.tag_dirty();
mesh->runtime->corner_tri_faces_cache.tag_dirty();
mesh->runtime->shrinkwrap_boundary_cache.tag_dirty();
Fix #132099: crash when using same geometry on objects with different material counts The core issue was that the geometry batch cache (e.g. `MeshBatchCache` or `PointCloudBatchCache`) was dependent on the object. This is problematic when the the same geometry is used with multiple different objects because the cache can't be consistent with all of them. Fortunately, the only thing that was retrieved from the object was the number of material slots, so if that can be avoided we should be fine. We can't just use the number of material slots stored on the geometry because that may have no material slots but still has material indices which are overridden on the object level. The solution is to take make the number of materials for a geometry only dependent on the actual `material_index` attribute and not on the number of available slots. More specifically, we find the maximal referenced material index and handle that many materials. This number does not depend on how many material slots there are on the object, but it still allows the object to override materials slots that the mesh references. A downside is that the maximum material index has to be computed which often requires an iteration over the mesh. Fortunately, we can cache that quite easily and the computation can be done in parallel. Also we are probably able to eagerly update the material index in many cases when it's set instead of computing it lazily. That is not implemented in this patch though. The largest part of the patch is making the maximal material index easily available on all the geometry types. Besides that, the material API is slightly replaced and the drawing code now makes use of the updated API. Pull Request: https://projects.blender.org/blender/blender/pulls/133498
2025-01-24 12:05:25 +01:00
mesh->runtime->max_material_index.tag_dirty();
mesh->runtime->subsurf_face_dot_tags.clear_and_shrink();
mesh->runtime->subsurf_optimal_display_edges.clear_and_shrink();
mesh->flag &= ~ME_NO_OVERLAPPING_TOPOLOGY;
}
void Mesh::tag_edges_split()
{
/* Triangulation didn't change because vertex positions and loop vertex indices didn't change. */
free_bvh_caches(*this->runtime);
this->runtime->vert_normals_cache.tag_dirty();
Mesh: Add "free" custom normals Add a "dumb vector" storage option for custom normals, with the "custom_normal" attribute. Adjust the mesh normals caching to provide this attribute if it's available, and add a geometry node to store custom normals. ## Free Normals They're called "free" in the sense that they're just direction vectors in the object's local space, rather than the existing "smooth corner fan space" storage. They're also "free" in that they make further normals calculation very inexpensive, since we just use the custom normals instead. That's a big improvement from the existing custom normals storage, which usually significantly decreases viewport performance. For example, in a simple test file just storing the vertex normals on a UV sphere, using free normals gives 25 times better playback performance and 10% lower memory usage. Free normals are adjusted when applying a transformation to the entire mesh or when realizing instances, but in general they're not updated for vertex deformations. ## Set Mesh Normal Node The new geometry node allows storing free custom normals as well as the existing corner fan space normals. When free normals are chosen, free normals can be stored on vertices, faces, or face corners. Using the face corner domain is necessary to bake existing mixed sharp and smooth edges into the custom normal vectors. The node also has a mode for storing edge and mesh sharpness, meant as a "soft" replacement to the "Set Shade Smooth" node that's a bit more convenient. ## Normal Input Node The normal node outputs free custom normals mixed to whatever domain is requested. A "true normal" output that ignores custom normals and sharpness is added as well. Across Blender, custom normals are generally accessed via face and vertex normals, when "true normals" are not requested explicitly. In many cases that means they are mixed from the face corner domain. ## Future Work 1. There are many places where propagation of free normals could be improved. They should probably be normalized after mixing, and it may be useful to not just use 0 vectors for new elements. To keep the scope of this change smaller, that sort of thing generally isn't handled here. Searching `CD_NORMAL` gives a hint of where better propagation could be useful. 2. Free normals are displayed properly in edit mode, but the existing custom normal editing operators don't work with free normals yet. This will hopefully be fairly straightforward since custom normals are usually converted to `float3` for editing anyway. Edit mode changes aren't included here because they're unnecessary for the procedural custom normals use cases. 3. Most importers can probably switch to using free normals instead, or at least provide an option for it. That will give a significant import performance improvement, and an improvement of Blender's FPS for imported scenes too. Pull Request: https://projects.blender.org/blender/blender/pulls/132583
2025-04-04 19:16:51 +02:00
this->runtime->corner_normals_cache.tag_dirty();
this->runtime->subdiv_ccg.reset();
this->runtime->vert_to_face_offset_cache.tag_dirty();
this->runtime->vert_to_face_map_cache.tag_dirty();
this->runtime->vert_to_corner_map_cache.tag_dirty();
if (this->runtime->loose_edges_cache.is_cached() &&
this->runtime->loose_edges_cache.data().count != 0)
{
this->runtime->loose_edges_cache.tag_dirty();
}
if (this->runtime->loose_verts_cache.is_cached() &&
this->runtime->loose_verts_cache.data().count != 0)
{
this->runtime->loose_verts_cache.tag_dirty();
}
if (this->runtime->verts_no_face_cache.is_cached() &&
this->runtime->verts_no_face_cache.data().count != 0)
{
this->runtime->verts_no_face_cache.tag_dirty();
}
this->runtime->subsurf_face_dot_tags.clear_and_shrink();
this->runtime->subsurf_optimal_display_edges.clear_and_shrink();
this->runtime->shrinkwrap_boundary_cache.tag_dirty();
}
void Mesh::tag_sharpness_changed()
Mesh: Replace auto smooth with node group Design task: #93551 This PR replaces the auto smooth option with a geometry nodes modifier that sets the sharp edge attribute. This solves a fair number of long- standing problems related to auto smooth, simplifies the process of normal computation, and allows Blender to automatically choose between face, vertex, and face corner normals based on the sharp edge and face attributes. Versioning adds a geometry node group to objects with meshes that had auto-smooth enabled. The modifier can be applied, which also improves performance. Auto smooth is now unnecessary to get a combination of sharp and smooth edges. In general workflows are changed a bit. Separate procedural and destructive workflows are available. Custom normals can be used immediately without turning on the removed auto smooth option. **Procedural** The node group asset "Smooth by Angle" is the main way to set sharp normals based on the edge angle. It can be accessed directly in the add modifier menu. Of course the modifier can be reordered, muted, or applied like any other, or changed internally like any geometry nodes modifier. **Destructive** Often the sharp edges don't need to be dynamic. This can give better performance since edge angles don't need to be recalculated. In edit mode the two operators "Select Sharp Edges" and "Mark Sharp" can be used. In other modes, the "Shade Smooth by Angle" controls the edge sharpness directly. ### Breaking API Changes - `use_auto_smooth` is removed. Face corner normals are now used automatically if there are mixed smooth vs. not smooth tags. Meshes now always use custom normals if they exist. - In Cycles, the lack of the separate auto smooth state makes normals look triangulated when all faces are shaded smooth. - `auto_smooth_angle` is removed. Replaced by a modifier (or operator) controlling the sharp edge attribute. This means the mesh itself (without an object) doesn't know anything about automatically smoothing by angle anymore. - `create_normals_split`, `calc_normals_split`, and `free_normals_split` are removed, and are replaced by the simpler `Mesh.corner_normals` collection property. Since it gives access to the normals cache, it is automatically updated when relevant data changes. Addons are updated here: https://projects.blender.org/blender/blender-addons/pulls/104609 ### Tests - `geo_node_curves_test_deform_curves_on_surface` has slightly different results because face corner normals are used instead of interpolated vertex normals. - `bf_wavefront_obj_tests` has different export results for one file which mixed sharp and smooth faces without turning on auto smooth. - `cycles_mesh_cpu` has one object which is completely flat shaded. Previously every edge was split before rendering, now it looks triangulated. Pull Request: https://projects.blender.org/blender/blender/pulls/108014
2023-10-20 16:54:08 +02:00
{
Mesh: Add "free" custom normals Add a "dumb vector" storage option for custom normals, with the "custom_normal" attribute. Adjust the mesh normals caching to provide this attribute if it's available, and add a geometry node to store custom normals. ## Free Normals They're called "free" in the sense that they're just direction vectors in the object's local space, rather than the existing "smooth corner fan space" storage. They're also "free" in that they make further normals calculation very inexpensive, since we just use the custom normals instead. That's a big improvement from the existing custom normals storage, which usually significantly decreases viewport performance. For example, in a simple test file just storing the vertex normals on a UV sphere, using free normals gives 25 times better playback performance and 10% lower memory usage. Free normals are adjusted when applying a transformation to the entire mesh or when realizing instances, but in general they're not updated for vertex deformations. ## Set Mesh Normal Node The new geometry node allows storing free custom normals as well as the existing corner fan space normals. When free normals are chosen, free normals can be stored on vertices, faces, or face corners. Using the face corner domain is necessary to bake existing mixed sharp and smooth edges into the custom normal vectors. The node also has a mode for storing edge and mesh sharpness, meant as a "soft" replacement to the "Set Shade Smooth" node that's a bit more convenient. ## Normal Input Node The normal node outputs free custom normals mixed to whatever domain is requested. A "true normal" output that ignores custom normals and sharpness is added as well. Across Blender, custom normals are generally accessed via face and vertex normals, when "true normals" are not requested explicitly. In many cases that means they are mixed from the face corner domain. ## Future Work 1. There are many places where propagation of free normals could be improved. They should probably be normalized after mixing, and it may be useful to not just use 0 vectors for new elements. To keep the scope of this change smaller, that sort of thing generally isn't handled here. Searching `CD_NORMAL` gives a hint of where better propagation could be useful. 2. Free normals are displayed properly in edit mode, but the existing custom normal editing operators don't work with free normals yet. This will hopefully be fairly straightforward since custom normals are usually converted to `float3` for editing anyway. Edit mode changes aren't included here because they're unnecessary for the procedural custom normals use cases. 3. Most importers can probably switch to using free normals instead, or at least provide an option for it. That will give a significant import performance improvement, and an improvement of Blender's FPS for imported scenes too. Pull Request: https://projects.blender.org/blender/blender/pulls/132583
2025-04-04 19:16:51 +02:00
this->runtime->vert_normals_cache.tag_dirty();
this->runtime->face_normals_cache.tag_dirty();
this->runtime->corner_normals_cache.tag_dirty();
Mesh: Replace auto smooth with node group Design task: #93551 This PR replaces the auto smooth option with a geometry nodes modifier that sets the sharp edge attribute. This solves a fair number of long- standing problems related to auto smooth, simplifies the process of normal computation, and allows Blender to automatically choose between face, vertex, and face corner normals based on the sharp edge and face attributes. Versioning adds a geometry node group to objects with meshes that had auto-smooth enabled. The modifier can be applied, which also improves performance. Auto smooth is now unnecessary to get a combination of sharp and smooth edges. In general workflows are changed a bit. Separate procedural and destructive workflows are available. Custom normals can be used immediately without turning on the removed auto smooth option. **Procedural** The node group asset "Smooth by Angle" is the main way to set sharp normals based on the edge angle. It can be accessed directly in the add modifier menu. Of course the modifier can be reordered, muted, or applied like any other, or changed internally like any geometry nodes modifier. **Destructive** Often the sharp edges don't need to be dynamic. This can give better performance since edge angles don't need to be recalculated. In edit mode the two operators "Select Sharp Edges" and "Mark Sharp" can be used. In other modes, the "Shade Smooth by Angle" controls the edge sharpness directly. ### Breaking API Changes - `use_auto_smooth` is removed. Face corner normals are now used automatically if there are mixed smooth vs. not smooth tags. Meshes now always use custom normals if they exist. - In Cycles, the lack of the separate auto smooth state makes normals look triangulated when all faces are shaded smooth. - `auto_smooth_angle` is removed. Replaced by a modifier (or operator) controlling the sharp edge attribute. This means the mesh itself (without an object) doesn't know anything about automatically smoothing by angle anymore. - `create_normals_split`, `calc_normals_split`, and `free_normals_split` are removed, and are replaced by the simpler `Mesh.corner_normals` collection property. Since it gives access to the normals cache, it is automatically updated when relevant data changes. Addons are updated here: https://projects.blender.org/blender/blender-addons/pulls/104609 ### Tests - `geo_node_curves_test_deform_curves_on_surface` has slightly different results because face corner normals are used instead of interpolated vertex normals. - `bf_wavefront_obj_tests` has different export results for one file which mixed sharp and smooth faces without turning on auto smooth. - `cycles_mesh_cpu` has one object which is completely flat shaded. Previously every edge was split before rendering, now it looks triangulated. Pull Request: https://projects.blender.org/blender/blender/pulls/108014
2023-10-20 16:54:08 +02:00
}
void Mesh::tag_custom_normals_changed()
{
Mesh: Add "free" custom normals Add a "dumb vector" storage option for custom normals, with the "custom_normal" attribute. Adjust the mesh normals caching to provide this attribute if it's available, and add a geometry node to store custom normals. ## Free Normals They're called "free" in the sense that they're just direction vectors in the object's local space, rather than the existing "smooth corner fan space" storage. They're also "free" in that they make further normals calculation very inexpensive, since we just use the custom normals instead. That's a big improvement from the existing custom normals storage, which usually significantly decreases viewport performance. For example, in a simple test file just storing the vertex normals on a UV sphere, using free normals gives 25 times better playback performance and 10% lower memory usage. Free normals are adjusted when applying a transformation to the entire mesh or when realizing instances, but in general they're not updated for vertex deformations. ## Set Mesh Normal Node The new geometry node allows storing free custom normals as well as the existing corner fan space normals. When free normals are chosen, free normals can be stored on vertices, faces, or face corners. Using the face corner domain is necessary to bake existing mixed sharp and smooth edges into the custom normal vectors. The node also has a mode for storing edge and mesh sharpness, meant as a "soft" replacement to the "Set Shade Smooth" node that's a bit more convenient. ## Normal Input Node The normal node outputs free custom normals mixed to whatever domain is requested. A "true normal" output that ignores custom normals and sharpness is added as well. Across Blender, custom normals are generally accessed via face and vertex normals, when "true normals" are not requested explicitly. In many cases that means they are mixed from the face corner domain. ## Future Work 1. There are many places where propagation of free normals could be improved. They should probably be normalized after mixing, and it may be useful to not just use 0 vectors for new elements. To keep the scope of this change smaller, that sort of thing generally isn't handled here. Searching `CD_NORMAL` gives a hint of where better propagation could be useful. 2. Free normals are displayed properly in edit mode, but the existing custom normal editing operators don't work with free normals yet. This will hopefully be fairly straightforward since custom normals are usually converted to `float3` for editing anyway. Edit mode changes aren't included here because they're unnecessary for the procedural custom normals use cases. 3. Most importers can probably switch to using free normals instead, or at least provide an option for it. That will give a significant import performance improvement, and an improvement of Blender's FPS for imported scenes too. Pull Request: https://projects.blender.org/blender/blender/pulls/132583
2025-04-04 19:16:51 +02:00
this->runtime->vert_normals_cache.tag_dirty();
this->runtime->face_normals_cache.tag_dirty();
this->runtime->corner_normals_cache.tag_dirty();
}
void Mesh::tag_face_winding_changed()
{
this->runtime->vert_normals_cache.tag_dirty();
this->runtime->face_normals_cache.tag_dirty();
Mesh: Add "free" custom normals Add a "dumb vector" storage option for custom normals, with the "custom_normal" attribute. Adjust the mesh normals caching to provide this attribute if it's available, and add a geometry node to store custom normals. ## Free Normals They're called "free" in the sense that they're just direction vectors in the object's local space, rather than the existing "smooth corner fan space" storage. They're also "free" in that they make further normals calculation very inexpensive, since we just use the custom normals instead. That's a big improvement from the existing custom normals storage, which usually significantly decreases viewport performance. For example, in a simple test file just storing the vertex normals on a UV sphere, using free normals gives 25 times better playback performance and 10% lower memory usage. Free normals are adjusted when applying a transformation to the entire mesh or when realizing instances, but in general they're not updated for vertex deformations. ## Set Mesh Normal Node The new geometry node allows storing free custom normals as well as the existing corner fan space normals. When free normals are chosen, free normals can be stored on vertices, faces, or face corners. Using the face corner domain is necessary to bake existing mixed sharp and smooth edges into the custom normal vectors. The node also has a mode for storing edge and mesh sharpness, meant as a "soft" replacement to the "Set Shade Smooth" node that's a bit more convenient. ## Normal Input Node The normal node outputs free custom normals mixed to whatever domain is requested. A "true normal" output that ignores custom normals and sharpness is added as well. Across Blender, custom normals are generally accessed via face and vertex normals, when "true normals" are not requested explicitly. In many cases that means they are mixed from the face corner domain. ## Future Work 1. There are many places where propagation of free normals could be improved. They should probably be normalized after mixing, and it may be useful to not just use 0 vectors for new elements. To keep the scope of this change smaller, that sort of thing generally isn't handled here. Searching `CD_NORMAL` gives a hint of where better propagation could be useful. 2. Free normals are displayed properly in edit mode, but the existing custom normal editing operators don't work with free normals yet. This will hopefully be fairly straightforward since custom normals are usually converted to `float3` for editing anyway. Edit mode changes aren't included here because they're unnecessary for the procedural custom normals use cases. 3. Most importers can probably switch to using free normals instead, or at least provide an option for it. That will give a significant import performance improvement, and an improvement of Blender's FPS for imported scenes too. Pull Request: https://projects.blender.org/blender/blender/pulls/132583
2025-04-04 19:16:51 +02:00
this->runtime->vert_normals_true_cache.tag_dirty();
this->runtime->face_normals_true_cache.tag_dirty();
this->runtime->corner_normals_cache.tag_dirty();
this->runtime->vert_to_corner_map_cache.tag_dirty();
this->runtime->shrinkwrap_boundary_cache.tag_dirty();
}
void Mesh::tag_positions_changed()
{
this->runtime->vert_normals_cache.tag_dirty();
this->runtime->face_normals_cache.tag_dirty();
Mesh: Add "free" custom normals Add a "dumb vector" storage option for custom normals, with the "custom_normal" attribute. Adjust the mesh normals caching to provide this attribute if it's available, and add a geometry node to store custom normals. ## Free Normals They're called "free" in the sense that they're just direction vectors in the object's local space, rather than the existing "smooth corner fan space" storage. They're also "free" in that they make further normals calculation very inexpensive, since we just use the custom normals instead. That's a big improvement from the existing custom normals storage, which usually significantly decreases viewport performance. For example, in a simple test file just storing the vertex normals on a UV sphere, using free normals gives 25 times better playback performance and 10% lower memory usage. Free normals are adjusted when applying a transformation to the entire mesh or when realizing instances, but in general they're not updated for vertex deformations. ## Set Mesh Normal Node The new geometry node allows storing free custom normals as well as the existing corner fan space normals. When free normals are chosen, free normals can be stored on vertices, faces, or face corners. Using the face corner domain is necessary to bake existing mixed sharp and smooth edges into the custom normal vectors. The node also has a mode for storing edge and mesh sharpness, meant as a "soft" replacement to the "Set Shade Smooth" node that's a bit more convenient. ## Normal Input Node The normal node outputs free custom normals mixed to whatever domain is requested. A "true normal" output that ignores custom normals and sharpness is added as well. Across Blender, custom normals are generally accessed via face and vertex normals, when "true normals" are not requested explicitly. In many cases that means they are mixed from the face corner domain. ## Future Work 1. There are many places where propagation of free normals could be improved. They should probably be normalized after mixing, and it may be useful to not just use 0 vectors for new elements. To keep the scope of this change smaller, that sort of thing generally isn't handled here. Searching `CD_NORMAL` gives a hint of where better propagation could be useful. 2. Free normals are displayed properly in edit mode, but the existing custom normal editing operators don't work with free normals yet. This will hopefully be fairly straightforward since custom normals are usually converted to `float3` for editing anyway. Edit mode changes aren't included here because they're unnecessary for the procedural custom normals use cases. 3. Most importers can probably switch to using free normals instead, or at least provide an option for it. That will give a significant import performance improvement, and an improvement of Blender's FPS for imported scenes too. Pull Request: https://projects.blender.org/blender/blender/pulls/132583
2025-04-04 19:16:51 +02:00
this->runtime->vert_normals_true_cache.tag_dirty();
this->runtime->face_normals_true_cache.tag_dirty();
this->runtime->corner_normals_cache.tag_dirty();
this->runtime->shrinkwrap_boundary_cache.tag_dirty();
this->tag_positions_changed_no_normals();
}
void Mesh::tag_positions_changed_no_normals()
{
free_bvh_caches(*this->runtime);
this->runtime->corner_tris_cache.tag_dirty();
this->runtime->bounds_cache.tag_dirty();
this->runtime->shrinkwrap_boundary_cache.tag_dirty();
}
void Mesh::tag_positions_changed_uniformly()
{
/* The normals and triangulation didn't change, since all verts moved by the same amount. */
free_bvh_caches(*this->runtime);
this->runtime->bounds_cache.tag_dirty();
}
void Mesh::tag_topology_changed()
{
BKE_mesh_runtime_clear_geometry(this);
}
void Mesh::tag_visibility_changed()
{
this->runtime->bvh_cache_corner_tris_no_hidden.tag_dirty();
this->runtime->bvh_cache_loose_verts_no_hidden.tag_dirty();
this->runtime->bvh_cache_loose_edges_no_hidden.tag_dirty();
}
Fix #132099: crash when using same geometry on objects with different material counts The core issue was that the geometry batch cache (e.g. `MeshBatchCache` or `PointCloudBatchCache`) was dependent on the object. This is problematic when the the same geometry is used with multiple different objects because the cache can't be consistent with all of them. Fortunately, the only thing that was retrieved from the object was the number of material slots, so if that can be avoided we should be fine. We can't just use the number of material slots stored on the geometry because that may have no material slots but still has material indices which are overridden on the object level. The solution is to take make the number of materials for a geometry only dependent on the actual `material_index` attribute and not on the number of available slots. More specifically, we find the maximal referenced material index and handle that many materials. This number does not depend on how many material slots there are on the object, but it still allows the object to override materials slots that the mesh references. A downside is that the maximum material index has to be computed which often requires an iteration over the mesh. Fortunately, we can cache that quite easily and the computation can be done in parallel. Also we are probably able to eagerly update the material index in many cases when it's set instead of computing it lazily. That is not implemented in this patch though. The largest part of the patch is making the maximal material index easily available on all the geometry types. Besides that, the material API is slightly replaced and the drawing code now makes use of the updated API. Pull Request: https://projects.blender.org/blender/blender/pulls/133498
2025-01-24 12:05:25 +01:00
void Mesh::tag_material_index_changed()
{
this->runtime->max_material_index.tag_dirty();
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Mesh Batch Cache Callbacks
* \{ */
/* Draw Engine */
void (*BKE_mesh_batch_cache_dirty_tag_cb)(Mesh *mesh, eMeshBatchDirtyMode mode) = nullptr;
void (*BKE_mesh_batch_cache_free_cb)(void *batch_cache) = nullptr;
void BKE_mesh_batch_cache_dirty_tag(Mesh *mesh, eMeshBatchDirtyMode mode)
{
if (mesh->runtime->batch_cache) {
BKE_mesh_batch_cache_dirty_tag_cb(mesh, mode);
}
/* Also tag batch cache for subdivided mesh, if it exists this will be
* the mesh that is actually being drawn. */
Mesh *mesh_eval = mesh->runtime->mesh_eval;
if (mesh_eval && mesh_eval->runtime->batch_cache) {
BKE_mesh_batch_cache_dirty_tag_cb(mesh_eval, mode);
}
}
void BKE_mesh_batch_cache_free(void *batch_cache)
{
BKE_mesh_batch_cache_free_cb(batch_cache);
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Mesh Runtime Validation
* \{ */
#ifndef NDEBUG
bool BKE_mesh_runtime_is_valid(Mesh *mesh_eval)
{
const bool do_verbose = true;
const bool do_fixes = false;
bool is_valid = true;
bool changed = true;
if (do_verbose) {
printf("MESH: %s\n", mesh_eval->id.name + 2);
}
MutableSpan<float3> positions = mesh_eval->vert_positions_for_write();
MutableSpan<blender::int2> edges = mesh_eval->edges_for_write();
Span<int> face_offsets = mesh_eval->face_offsets();
Span<int> corner_verts = mesh_eval->corner_verts();
MutableSpan<int> corner_edges = mesh_eval->corner_edges_for_write();
Mesh: Remove redundant custom data pointers For copy-on-write, we want to share attribute arrays between meshes where possible. Mutable pointers like `Mesh.mvert` make that difficult by making ownership vague. They also make code more complex by adding redundancy. The simplest solution is just removing them and retrieving layers from `CustomData` as needed. Similar changes have already been applied to curves and point clouds (e9f82d3dc7ee, 410a6efb747f). Removing use of the pointers generally makes code more obvious and more reusable. Mesh data is now accessed with a C++ API (`Mesh::edges()` or `Mesh::edges_for_write()`), and a C API (`BKE_mesh_edges(mesh)`). The CoW changes this commit makes possible are described in T95845 and T95842, and started in D14139 and D14140. The change also simplifies the ongoing mesh struct-of-array refactors from T95965. **RNA/Python Access Performance** Theoretically, accessing mesh elements with the RNA API may become slower, since the layer needs to be found on every random access. However, overhead is already high enough that this doesn't make a noticible differenc, and performance is actually improved in some cases. Random access can be up to 10% faster, but other situations might be a bit slower. Generally using `foreach_get/set` are the best way to improve performance. See the differential revision for more discussion about Python performance. Cycles has been updated to use raw pointers and the internal Blender mesh types, mostly because there is no sense in having this overhead when it's already compiled with Blender. In my tests this roughly halves the Cycles mesh creation time (0.19s to 0.10s for a 1 million face grid). Differential Revision: https://developer.blender.org/D15488
2022-09-05 11:56:34 -05:00
is_valid &= BKE_mesh_validate_all_customdata(
&mesh_eval->vert_data,
mesh_eval->verts_num,
&mesh_eval->edge_data,
mesh_eval->edges_num,
&mesh_eval->corner_data,
mesh_eval->corners_num,
&mesh_eval->face_data,
mesh_eval->faces_num,
2018-07-13 08:37:20 +02:00
false, /* setting mask here isn't useful, gives false positives */
do_verbose,
do_fixes,
&changed);
MDeformVert *dverts = static_cast<MDeformVert *>(
CustomData_get_layer_for_write(&mesh_eval->vert_data, CD_MDEFORMVERT, mesh_eval->verts_num));
2023-07-24 16:32:08 -04:00
is_valid &= BKE_mesh_validate_arrays(
mesh_eval,
2023-07-24 16:32:08 -04:00
reinterpret_cast<float(*)[3]>(positions.data()),
positions.size(),
edges.data(),
edges.size(),
static_cast<MFace *>(CustomData_get_layer_for_write(
&mesh_eval->fdata_legacy, CD_MFACE, mesh_eval->totface_legacy)),
mesh_eval->totface_legacy,
2023-07-24 16:32:08 -04:00
corner_verts.data(),
corner_edges.data(),
corner_verts.size(),
face_offsets.data(),
mesh_eval->faces_num,
dverts,
2023-07-24 16:32:08 -04:00
do_verbose,
do_fixes,
&changed);
BLI_assert(changed == false);
return is_valid;
}
#endif /* !NDEBUG */
/** \} */