Files
test2/source/blender/modifiers/intern/MOD_util.cc

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

295 lines
8.3 KiB
C++
Raw Normal View History

/* SPDX-FileCopyrightText: 2005 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup modifiers
*/
#include <cstring>
#include "BLI_utildefines.h"
#include "BLI_bitmap.h"
#include "BLI_math_matrix.h"
#include "BLI_math_vector.h"
#include "DNA_image_types.h"
#include "DNA_mesh_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
#include "BKE_action.h" /* BKE_pose_channel_find_name */
#include "BKE_attribute.hh"
2024-01-29 18:57:16 -05:00
#include "BKE_deform.hh"
#include "BKE_editmesh.hh"
#include "BKE_image.h"
#include "BKE_lattice.hh"
2023-11-14 09:30:40 +01:00
#include "BKE_modifier.hh"
#include "DEG_depsgraph.hh"
#include "DEG_depsgraph_query.hh"
#include "MOD_modifiertypes.hh"
#include "MOD_util.hh"
#include "MEM_guardedalloc.h"
void MOD_init_texture(MappingInfoModifierData *dmd, const ModifierEvalContext *ctx)
{
Tex *tex = dmd->texture;
if (tex == nullptr) {
return;
}
if (tex->ima && BKE_image_is_animated(tex->ima)) {
BKE_image_user_frame_calc(tex->ima, &tex->iuser, DEG_get_ctime(ctx->depsgraph));
}
}
void MOD_get_texture_coords(MappingInfoModifierData *dmd,
const ModifierEvalContext * /*ctx*/,
Object *ob,
Mesh *mesh,
float (*cos)[3],
float (*r_texco)[3])
{
/* TODO: to be renamed to `get_texture_coords` once we are done with moving modifiers to Mesh. */
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
using namespace blender;
const int verts_num = mesh->verts_num;
int i;
int texmapping = dmd->texmapping;
float mapref_imat[4][4];
if (texmapping == MOD_DISP_MAP_OBJECT) {
if (dmd->map_object != nullptr) {
Object *map_object = dmd->map_object;
if (dmd->map_bone[0] != '\0') {
bPoseChannel *pchan = BKE_pose_channel_find_name(map_object->pose, dmd->map_bone);
if (pchan) {
float mat_bone_world[4][4];
mul_m4_m4m4(mat_bone_world, map_object->object_to_world().ptr(), pchan->pose_mat);
invert_m4_m4(mapref_imat, mat_bone_world);
}
else {
invert_m4_m4(mapref_imat, map_object->object_to_world().ptr());
}
}
else {
invert_m4_m4(mapref_imat, map_object->object_to_world().ptr());
}
}
else { /* if there is no map object, default to local */
texmapping = MOD_DISP_MAP_LOCAL;
}
}
/* UVs need special handling, since they come from faces */
if (texmapping == MOD_DISP_MAP_UV) {
if (CustomData_has_layer(&mesh->corner_data, CD_PROP_FLOAT2)) {
const OffsetIndices faces = mesh->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 = mesh->corner_verts();
BLI_bitmap *done = BLI_BITMAP_NEW(verts_num, __func__);
char uvname[MAX_CUSTOMDATA_LAYER_NAME];
CustomData_validate_layer_name(
&mesh->corner_data, CD_PROP_FLOAT2, dmd->uvlayer_name, uvname);
const bke::AttributeAccessor attributes = mesh->attributes();
const VArraySpan uv_map = *attributes.lookup_or_default<float2>(
uvname, bke::AttrDomain::Corner, float2(0));
/* verts are given the UV from the first face that uses them */
for (const int i : faces.index_range()) {
const IndexRange face = faces[i];
for (const int corner : face) {
const int vert = corner_verts[corner];
if (!BLI_BITMAP_TEST(done, vert)) {
/* remap UVs from [0, 1] to [-1, 1] */
r_texco[vert][0] = (uv_map[corner][0] * 2.0f) - 1.0f;
r_texco[vert][1] = (uv_map[corner][1] * 2.0f) - 1.0f;
BLI_BITMAP_ENABLE(done, vert);
}
}
}
MEM_freeN(done);
return;
}
/* if there are no UVs, default to local */
texmapping = MOD_DISP_MAP_LOCAL;
}
const Span<float3> positions = mesh->vert_positions();
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
for (i = 0; i < verts_num; i++, r_texco++) {
switch (texmapping) {
case MOD_DISP_MAP_LOCAL:
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
copy_v3_v3(*r_texco, cos != nullptr ? *cos : positions[i]);
break;
case MOD_DISP_MAP_GLOBAL:
mul_v3_m4v3(*r_texco, ob->object_to_world().ptr(), cos != nullptr ? *cos : positions[i]);
break;
case MOD_DISP_MAP_OBJECT:
mul_v3_m4v3(*r_texco, ob->object_to_world().ptr(), cos != nullptr ? *cos : positions[i]);
mul_m4_v3(mapref_imat, *r_texco);
break;
}
if (cos != nullptr) {
cos++;
}
}
}
void MOD_previous_vcos_store(ModifierData *md, const float (*vert_coords)[3])
{
2012-05-06 13:38:33 +00:00
while ((md = md->next) && md->type == eModifierType_Armature) {
ArmatureModifierData *amd = (ArmatureModifierData *)md;
if (amd->multi && amd->vert_coords_prev == nullptr) {
amd->vert_coords_prev = static_cast<float(*)[3]>(MEM_dupallocN(vert_coords));
}
else {
break;
}
}
/* lattice/mesh modifier too */
}
void MOD_get_vgroup(const Object *ob,
const Mesh *mesh,
const char *name,
const MDeformVert **dvert,
int *defgrp_index)
{
if (mesh) {
*defgrp_index = BKE_id_defgroup_name_index(&mesh->id, name);
if (*defgrp_index != -1) {
*dvert = mesh->deform_verts().data();
}
else {
*dvert = nullptr;
}
}
else if (OB_TYPE_SUPPORT_VGROUP(ob->type)) {
*defgrp_index = BKE_object_defgroup_name_index(ob, name);
if (*defgrp_index != -1 && ob->type == OB_LATTICE) {
*dvert = BKE_lattice_deform_verts_get(ob);
}
else {
*dvert = nullptr;
}
}
else {
*defgrp_index = -1;
*dvert = nullptr;
}
}
void MOD_depsgraph_update_object_bone_relation(DepsNodeHandle *node,
Object *object,
const char *bonename,
const char *description)
{
if (object == nullptr) {
return;
}
if (bonename[0] != '\0' && object->type == OB_ARMATURE) {
DEG_add_object_relation(node, object, DEG_OB_COMP_EVAL_POSE, description);
}
else {
DEG_add_object_relation(node, object, DEG_OB_COMP_TRANSFORM, description);
}
}
void modifier_type_init(ModifierTypeInfo *types[])
{
#define INIT_TYPE(typeName) (types[eModifierType_##typeName] = &modifierType_##typeName)
INIT_TYPE(None);
INIT_TYPE(Curve);
INIT_TYPE(Lattice);
INIT_TYPE(Subsurf);
INIT_TYPE(Build);
INIT_TYPE(Array);
INIT_TYPE(Mirror);
INIT_TYPE(EdgeSplit);
INIT_TYPE(Bevel);
INIT_TYPE(Displace);
INIT_TYPE(UVProject);
INIT_TYPE(Decimate);
INIT_TYPE(Smooth);
INIT_TYPE(Cast);
INIT_TYPE(Wave);
INIT_TYPE(Armature);
INIT_TYPE(Hook);
INIT_TYPE(Softbody);
INIT_TYPE(Cloth);
INIT_TYPE(Collision);
INIT_TYPE(Boolean);
INIT_TYPE(MeshDeform);
INIT_TYPE(Ocean);
INIT_TYPE(ParticleSystem);
INIT_TYPE(ParticleInstance);
INIT_TYPE(Explode);
INIT_TYPE(Shrinkwrap);
INIT_TYPE(Mask);
INIT_TYPE(SimpleDeform);
INIT_TYPE(Multires);
INIT_TYPE(Surface);
INIT_TYPE(Fluid);
INIT_TYPE(ShapeKey);
INIT_TYPE(Solidify);
INIT_TYPE(Screw);
INIT_TYPE(Warp);
INIT_TYPE(WeightVGEdit);
INIT_TYPE(WeightVGMix);
INIT_TYPE(WeightVGProximity);
INIT_TYPE(DynamicPaint);
INIT_TYPE(Remesh);
INIT_TYPE(Skin);
INIT_TYPE(LaplacianSmooth);
INIT_TYPE(Triangulate);
INIT_TYPE(UVWarp);
INIT_TYPE(MeshCache);
INIT_TYPE(LaplacianDeform);
INIT_TYPE(Wireframe);
INIT_TYPE(Weld);
INIT_TYPE(DataTransfer);
INIT_TYPE(NormalEdit);
INIT_TYPE(CorrectiveSmooth);
INIT_TYPE(MeshSequenceCache);
INIT_TYPE(SurfaceDeform);
2018-05-25 22:24:24 +05:30
INIT_TYPE(WeightedNormal);
INIT_TYPE(MeshToVolume);
INIT_TYPE(VolumeDisplace);
INIT_TYPE(VolumeToMesh);
Geometry Nodes: initial scattering and geometry nodes This is the initial merge from the geometry-nodes branch. Nodes: * Attribute Math * Boolean * Edge Split * Float Compare * Object Info * Point Distribute * Point Instance * Random Attribute * Random Float * Subdivision Surface * Transform * Triangulate It includes the initial evaluation of geometry node groups in the Geometry Nodes modifier. Notes on the Generic attribute access API The API adds an indirection for attribute access. That has the following benefits: * Most code does not have to care about how an attribute is stored internally. This is mainly necessary, because we have to deal with "legacy" attributes such as vertex weights and attributes that are embedded into other structs such as vertex positions. * When reading from an attribute, we generally don't care what domain the attribute is stored on. So we want to abstract away the interpolation that that adapts attributes from one domain to another domain (this is not actually implemented yet). Other possible improvements for later iterations include: * Actually implement interpolation between domains. * Don't use inheritance for the different attribute types. A single class for read access and one for write access might be enough, because we know all the ways in which attributes are stored internally. We don't want more different internal structures in the future. On the contrary, ideally we can consolidate the different storage formats in the future to reduce the need for this indirection. * Remove the need for heap allocations when creating attribute accessors. It includes commits from: * Dalai Felinto * Hans Goudey * Jacques Lucke * Léo Depoix
2020-12-02 13:25:25 +01:00
INIT_TYPE(Nodes);
GPv3: Opacity modifier Opacity modifier implementation based on GP2. Functionality is largely unchanged. _Color Mode_ is either `Stroke` or `Fill` for modifying color opacity or `Hardness`. _Uniform Opacity_ does two things at once (!): - Sets the same opacity value for every point in a stroke. - Sets opacity as an absolute value rather than a factor. _Weight as Factor_ (button to the right of Opacity Factor): Use the vertex group as opacity __factor__ rather than an overall __influence__. This is confusing and hard to convey, but copies behavior from GP2. The _Influence_ panel contains the same filter settings as the GP2 modifier, with some small changes: - _Layer_ selects only strokes in the respective layer (with an _Invert_ option) - _Material_ selects only points with the respective material (with an _Invert_ option) - _Layer Pass_ and _Material Pass_ select only strokes/points which are rendered in the respective pass. _Note 1: Layers don't have UI for setting a pass yet, this will be a generic layer attribute. This can be set through the API for testing._ _Note 2: In GP2 a pass value of zero was used to disable pass filters. Since zero is a valid pass ID an explicit flag has been added for the purpose of turning pass filters on and off._ - _Vertex Group_: This can be used as an additional influence filter on points. If _Weight as Factor_ is enable the vertex group instead replaces the opacity factor. In _Fill_ mode the vertex group weight of the stroke's first point is used as influence for the entire stroke. - _Custom Curve_ is another possible influence factor per point. The curve input value is the relative position of a point along its stroke. The Influence settings have been moved into a separate DNA struct, which should help with reusability in various modifiers. Various utility functions can be found int `MOD_grease_pencil_util.hh` for handling influence settings and generating `IndexMasks` for modernized C++ code. Pull Request: https://projects.blender.org/blender/blender/pulls/116946
2024-01-16 16:56:14 +01:00
INIT_TYPE(GreasePencilOpacity);
INIT_TYPE(GreasePencilSubdiv);
INIT_TYPE(GreasePencilColor);
INIT_TYPE(GreasePencilTint);
INIT_TYPE(GreasePencilSmooth);
INIT_TYPE(GreasePencilOffset);
INIT_TYPE(GreasePencilNoise);
INIT_TYPE(GreasePencilMirror);
INIT_TYPE(GreasePencilThickness);
INIT_TYPE(GreasePencilLattice);
INIT_TYPE(GreasePencilDash);
INIT_TYPE(GreasePencilMultiply);
INIT_TYPE(GreasePencilLength);
INIT_TYPE(GreasePencilWeightAngle);
INIT_TYPE(GreasePencilArray);
INIT_TYPE(GreasePencilWeightProximity);
INIT_TYPE(GreasePencilHook);
INIT_TYPE(GreasePencilLineart);
INIT_TYPE(GreasePencilArmature);
INIT_TYPE(GreasePencilTime);
INIT_TYPE(GreasePencilSimplify);
INIT_TYPE(GreasePencilEnvelope);
INIT_TYPE(GreasePencilOutline);
INIT_TYPE(GreasePencilShrinkwrap);
INIT_TYPE(GreasePencilBuild);
INIT_TYPE(GreasePencilTexture);
#undef INIT_TYPE
}