edef19fd0326737e03e889d66c8f70e8bf41dd40
[blender.git] / source / blender / modifiers / intern / MOD_mask.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software  Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 by the Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Daniel Dunbar
22  *                 Ton Roosendaal,
23  *                 Ben Batt,
24  *                 Brecht Van Lommel,
25  *                 Campbell Barton
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 /** \file blender/modifiers/intern/MOD_mask.c
32  *  \ingroup modifiers
33  */
34
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_utildefines.h"
39 #include "BLI_listbase.h"
40 #include "BLI_string.h"
41 #include "BLI_ghash.h"
42
43 #include "DNA_armature_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_modifier_types.h"
46 #include "DNA_object_types.h"
47
48 #include "BKE_action.h" /* get_pose_channel */
49 #include "BKE_cdderivedmesh.h"
50 #include "BKE_mesh.h"
51 #include "BKE_modifier.h"
52 #include "BKE_deform.h"
53
54 #include "depsgraph_private.h"
55
56 #include "MOD_util.h"
57
58 static void copyData(ModifierData *md, ModifierData *target)
59 {
60         MaskModifierData *mmd = (MaskModifierData*) md;
61         MaskModifierData *tmmd = (MaskModifierData*) target;
62         
63         BLI_strncpy(tmmd->vgroup, mmd->vgroup, sizeof(tmmd->vgroup));
64         tmmd->flag = mmd->flag;
65 }
66
67 static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
68 {
69         return CD_MASK_MDEFORMVERT;
70 }
71
72 static void foreachObjectLink(
73                                                   ModifierData *md, Object *ob,
74            void (*walk)(void *userData, Object *ob, Object **obpoin),
75                   void *userData)
76 {
77         MaskModifierData *mmd = (MaskModifierData *)md;
78         walk(userData, ob, &mmd->ob_arm);
79 }
80
81 static void updateDepgraph(ModifierData *md, DagForest *forest,
82                                                 struct Scene *UNUSED(scene),
83                                                 Object *UNUSED(ob),
84                                                 DagNode *obNode)
85 {
86         MaskModifierData *mmd = (MaskModifierData *)md;
87
88         if (mmd->ob_arm) 
89         {
90                 DagNode *armNode = dag_get_node(forest, mmd->ob_arm);
91                 
92                 dag_add_relation(forest, armNode, obNode,
93                                 DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mask Modifier");
94         }
95 }
96
97 static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
98                                                 DerivedMesh *derivedData,
99                                                 int UNUSED(useRenderParams),
100                                                 int UNUSED(isFinalCalc))
101 {
102         MaskModifierData *mmd= (MaskModifierData *)md;
103         DerivedMesh *dm= derivedData, *result= NULL;
104         GHash *vertHash=NULL, *edgeHash, *polyHash;
105         GHashIterator *hashIter;
106         MDeformVert *dvert= NULL, *dv;
107         int numPolys=0, numLoops=0, numEdges=0, numVerts=0;
108         int maxVerts, maxEdges, maxPolys;
109         int i;
110
111         MPoly *mpoly;
112         MLoop *mloop;
113
114         MPoly *mpoly_new;
115         MLoop *mloop_new;
116         MEdge *medge_new;
117         MVert *mvert_new;
118
119
120         int *loop_mapping;
121
122         /* Overview of Method:
123          *      1. Get the vertices that are in the vertexgroup of interest 
124          *      2. Filter out unwanted geometry (i.e. not in vertexgroup), by populating mappings with new vs old indices
125          *      3. Make a new mesh containing only the mapping data
126          */
127         
128         /* get original number of verts, edges, and faces */
129         maxVerts= dm->getNumVerts(dm);
130         maxEdges= dm->getNumEdges(dm);
131         maxPolys= dm->getNumPolys(dm);
132         
133         /* check if we can just return the original mesh 
134          *      - must have verts and therefore verts assigned to vgroups to do anything useful
135          */
136         if ( !(ELEM(mmd->mode, MOD_MASK_MODE_ARM, MOD_MASK_MODE_VGROUP)) ||
137                  (maxVerts == 0) || (ob->defbase.first == NULL) )
138         {
139                 return derivedData;
140         }
141         
142         /* if mode is to use selected armature bones, aggregate the bone groups */
143         if (mmd->mode == MOD_MASK_MODE_ARM) /* --- using selected bones --- */
144         {
145                 GHash *vgroupHash;
146                 Object *oba= mmd->ob_arm;
147                 bPoseChannel *pchan;
148                 bDeformGroup *def;
149                 char *bone_select_array;
150                 int bone_select_tot= 0;
151                 const int defbase_tot= BLI_countlist(&ob->defbase);
152
153                 /* check that there is armature object with bones to use, otherwise return original mesh */
154                 if (ELEM3(NULL, mmd->ob_arm, mmd->ob_arm->pose, ob->defbase.first))
155                         return derivedData;
156
157                 bone_select_array= MEM_mallocN(defbase_tot * sizeof(char), "mask array");
158
159                 for (i = 0, def = ob->defbase.first; def; def = def->next, i++)
160                 {
161                         if (((pchan= get_pose_channel(oba->pose, def->name)) && pchan->bone && (pchan->bone->flag & BONE_SELECTED)))
162                         {
163                                 bone_select_array[i]= TRUE;
164                                 bone_select_tot++;
165                         }
166                         else {
167                                 bone_select_array[i]= FALSE;
168                         }
169                 }
170
171                 /* hashes for finding mapping of:
172                  *      - vgroups to indices -> vgroupHash  (string, int)
173                  *      - bones to vgroup indices -> boneHash (index of vgroup, dummy)
174                  */
175                 vgroupHash= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "mask vgroup gh");
176                 
177                 /* build mapping of names of vertex groups to indices */
178                 for (i = 0, def = ob->defbase.first; def; def = def->next, i++) 
179                         BLI_ghash_insert(vgroupHash, def->name, SET_INT_IN_POINTER(i));
180                 
181                 /* if no bones selected, free hashes and return original mesh */
182                 if (bone_select_tot == 0)
183                 {
184                         BLI_ghash_free(vgroupHash, NULL, NULL);
185                         MEM_freeN(bone_select_array);
186                         
187                         return derivedData;
188                 }
189                 
190                 /* repeat the previous check, but for dverts */
191                 dvert= dm->getVertDataArray(dm, CD_MDEFORMVERT);
192                 if (dvert == NULL)
193                 {
194                         BLI_ghash_free(vgroupHash, NULL, NULL);
195                         MEM_freeN(bone_select_array);
196                         
197                         return derivedData;
198                 }
199                 
200                 /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
201                 vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask vert gh");
202                 
203                 /* add vertices which exist in vertexgroups into vertHash for filtering */
204                 for (i= 0, dv= dvert; i < maxVerts; i++, dv++)
205                 {
206                         MDeformWeight *dw= dv->dw;
207                         int j;
208
209                         for (j= dv->totweight; j > 0; j--, dw++) {
210                                 if (dw->def_nr < defbase_tot) {
211                                         if (bone_select_array[dw->def_nr]) {
212                                                 if(dw->weight != 0.0f) {
213                                                         break;
214                                                 }
215                                         }
216                                 }
217                         }
218                         
219                         /* check if include vert in vertHash */
220                         if (mmd->flag & MOD_MASK_INV) {
221                                 /* if this vert is in the vgroup, don't include it in vertHash */
222                                 if (dw) continue;
223                         }
224                         else {
225                                 /* if this vert isn't in the vgroup, don't include it in vertHash */
226                                 if (!dw) continue;
227                         }
228                         
229                         /* add to ghash for verts (numVerts acts as counter for mapping) */
230                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
231                         numVerts++;
232                 }
233                 
234                 /* free temp hashes */
235                 BLI_ghash_free(vgroupHash, NULL, NULL);
236                 MEM_freeN(bone_select_array);
237         }
238         else            /* --- Using Nominated VertexGroup only --- */ 
239         {
240                 int defgrp_index = defgroup_name_index(ob, mmd->vgroup);
241                 
242                 /* get dverts */
243                 if (defgrp_index >= 0)
244                         dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
245                         
246                 /* if no vgroup (i.e. dverts) found, return the initial mesh */
247                 if ((defgrp_index < 0) || (dvert == NULL))
248                         return dm;
249                         
250                 /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
251                 vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask vert2 bh");
252                 
253                 /* add vertices which exist in vertexgroup into ghash for filtering */
254                 for (i= 0, dv= dvert; i < maxVerts; i++, dv++)
255                 {
256                         const int weight_set= defvert_find_weight(dv, defgrp_index) != 0.0f;
257                         
258                         /* check if include vert in vertHash */
259                         if (mmd->flag & MOD_MASK_INV) {
260                                 /* if this vert is in the vgroup, don't include it in vertHash */
261                                 if (weight_set) continue;
262                         }
263                         else {
264                                 /* if this vert isn't in the vgroup, don't include it in vertHash */
265                                 if (!weight_set) continue;
266                         }
267                         
268                         /* add to ghash for verts (numVerts acts as counter for mapping) */
269                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
270                         numVerts++;
271                 }
272         }
273
274         /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
275         edgeHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask ed2 gh");
276         polyHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask fa2 gh");
277         
278         mpoly = dm->getPolyArray(dm);
279         mloop = dm->getLoopArray(dm);
280
281         loop_mapping = MEM_callocN(sizeof(int) * maxPolys, "mask loopmap"); /* overalloc, assume all polys are seen */
282
283         /* loop over edges and faces, and do the same thing to 
284          * ensure that they only reference existing verts 
285          */
286         for (i = 0; i < maxEdges; i++) 
287         {
288                 MEdge me;
289                 dm->getEdge(dm, i, &me);
290                 
291                 /* only add if both verts will be in new mesh */
292                 if ( BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)) &&
293                          BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)) )
294                 {
295                         BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numEdges));
296                         numEdges++;
297                 }
298         }
299         for (i = 0; i < maxPolys; i++)
300         {
301                 MPoly *mp = &mpoly[i];
302                 MLoop *ml = mloop + mp->loopstart;
303                 int ok = TRUE;
304                 int j;
305
306                 for (j = 0; j < mp->totloop; j++, ml++) {
307                         if (!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(ml->v))) {
308                                 ok = FALSE;
309                                 break;
310                         }
311                 }
312                 
313                 /* all verts must be available */
314                 if (ok)
315                 {
316                         BLI_ghash_insert(polyHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numPolys));
317                         loop_mapping[numPolys] = numLoops;
318                         numPolys++;
319                         numLoops += mp->totloop;
320                 }
321         }
322         
323         
324         /* now we know the number of verts, edges and faces, 
325          * we can create the new (reduced) mesh
326          */
327         result = CDDM_from_template(dm, numVerts, numEdges, 0, numLoops, numPolys);
328         
329         mpoly_new = CDDM_get_polys(result);
330         mloop_new = CDDM_get_loops(result);
331         medge_new = CDDM_get_edges(result);
332         mvert_new = CDDM_get_verts(result);
333         
334         /* using ghash-iterators, map data into new mesh */
335                 /* vertices */
336         for ( hashIter = BLI_ghashIterator_new(vertHash);
337                   !BLI_ghashIterator_isDone(hashIter);
338                   BLI_ghashIterator_step(hashIter) ) 
339         {
340                 MVert source;
341                 MVert *dest;
342                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
343                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
344                 
345                 dm->getVert(dm, oldIndex, &source);
346                 dest = &mvert_new[newIndex];
347                 
348                 DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
349                 *dest = source;
350         }
351         BLI_ghashIterator_free(hashIter);
352                 
353                 /* edges */
354         for ( hashIter = BLI_ghashIterator_new(edgeHash);
355                   !BLI_ghashIterator_isDone(hashIter);
356                   BLI_ghashIterator_step(hashIter) ) 
357         {
358                 MEdge source;
359                 MEdge *dest;
360                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
361                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
362                 
363                 dm->getEdge(dm, oldIndex, &source);
364                 dest = &medge_new[newIndex];
365                 
366                 source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
367                 source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
368                 
369                 DM_copy_edge_data(dm, result, oldIndex, newIndex, 1);
370                 *dest = source;
371         }
372         BLI_ghashIterator_free(hashIter);
373         
374                 /* faces */
375         for ( hashIter = BLI_ghashIterator_new(polyHash);
376                   !BLI_ghashIterator_isDone(hashIter);
377                   BLI_ghashIterator_step(hashIter) ) 
378         {
379                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
380                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
381                 MPoly *source = &mpoly[oldIndex];
382                 MPoly *dest = &mpoly_new[newIndex];
383                 int oldLoopIndex = source->loopstart;
384                 int newLoopIndex = loop_mapping[newIndex];
385                 MLoop *source_loop = &mloop[oldLoopIndex];
386                 MLoop *dest_loop = &mloop_new[newLoopIndex];
387                 
388                 DM_copy_poly_data(dm, result, oldIndex, newIndex, 1);
389                 DM_copy_loop_data(dm, result, oldLoopIndex, newLoopIndex, source->totloop);
390
391                 *dest = *source;
392                 dest->loopstart = newLoopIndex;
393                 for (i = 0; i < source->totloop; i++) {
394                         dest_loop[i].v = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source_loop[i].v)));
395                         dest_loop[i].e = GET_INT_FROM_POINTER(BLI_ghash_lookup(edgeHash, SET_INT_IN_POINTER(source_loop[i].e)));
396                 }
397         }
398
399         BLI_ghashIterator_free(hashIter);
400
401         MEM_freeN(loop_mapping);
402
403         /* why is this needed? - campbell */
404         /* recalculate normals */
405         CDDM_calc_normals(result);
406         
407         /* free hashes */
408         BLI_ghash_free(vertHash, NULL, NULL);
409         BLI_ghash_free(edgeHash, NULL, NULL);
410         BLI_ghash_free(polyHash, NULL, NULL);
411
412         /* return the new mesh */
413         return result;
414 }
415
416
417 ModifierTypeInfo modifierType_Mask = {
418         /* name */              "Mask",
419         /* structName */        "MaskModifierData",
420         /* structSize */        sizeof(MaskModifierData),
421         /* type */              eModifierTypeType_Nonconstructive,
422         /* flags */             eModifierTypeFlag_AcceptsMesh|eModifierTypeFlag_SupportsMapping|eModifierTypeFlag_SupportsEditmode,
423
424         /* copyData */          copyData,
425         /* deformVerts */       NULL,
426         /* deformMatrices */    NULL,
427         /* deformVertsEM */     NULL,
428         /* deformMatricesEM */  NULL,
429         /* applyModifier */     applyModifier,
430         /* applyModifierEM */   NULL,
431         /* initData */          NULL,
432         /* requiredDataMask */  requiredDataMask,
433         /* freeData */          NULL,
434         /* isDisabled */        NULL,
435         /* updateDepgraph */    updateDepgraph,
436         /* dependsOnTime */     NULL,
437         /* dependsOnNormals */  NULL,
438         /* foreachObjectLink */ foreachObjectLink,
439         /* foreachIDLink */     NULL,
440         /* foreachTexLink */    NULL,
441 };