svn merge ^/trunk/blender -r46300:46330
[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" /* BKE_pose_channel_find_name */
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                 DagNode *armNode = dag_get_node(forest, mmd->ob_arm);
90                 
91                 dag_add_relation(forest, armNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mask Modifier");
92         }
93 }
94
95 static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
96                                                 DerivedMesh *derivedData,
97                                                 int UNUSED(useRenderParams),
98                                                 int UNUSED(isFinalCalc))
99 {
100         MaskModifierData *mmd= (MaskModifierData *)md;
101         DerivedMesh *dm= derivedData, *result= NULL;
102         GHash *vertHash=NULL, *edgeHash, *polyHash;
103         GHashIterator *hashIter;
104         MDeformVert *dvert= NULL, *dv;
105         int numPolys=0, numLoops=0, numEdges=0, numVerts=0;
106         int maxVerts, maxEdges, maxPolys;
107         int i;
108
109         MPoly *mpoly;
110         MLoop *mloop;
111
112         MPoly *mpoly_new;
113         MLoop *mloop_new;
114         MEdge *medge_new;
115         MVert *mvert_new;
116
117
118         int *loop_mapping;
119
120         /* Overview of Method:
121          *      1. Get the vertices that are in the vertexgroup of interest 
122          *      2. Filter out unwanted geometry (i.e. not in vertexgroup), by populating mappings with new vs old indices
123          *      3. Make a new mesh containing only the mapping data
124          */
125         
126         /* get original number of verts, edges, and faces */
127         maxVerts= dm->getNumVerts(dm);
128         maxEdges= dm->getNumEdges(dm);
129         maxPolys= dm->getNumPolys(dm);
130         
131         /* check if we can just return the original mesh 
132          *      - must have verts and therefore verts assigned to vgroups to do anything useful
133          */
134         if ( !(ELEM(mmd->mode, MOD_MASK_MODE_ARM, MOD_MASK_MODE_VGROUP)) ||
135                  (maxVerts == 0) || (ob->defbase.first == NULL) )
136         {
137                 return derivedData;
138         }
139         
140         /* if mode is to use selected armature bones, aggregate the bone groups */
141         if (mmd->mode == MOD_MASK_MODE_ARM) { /* --- using selected bones --- */
142                 GHash *vgroupHash;
143                 Object *oba= mmd->ob_arm;
144                 bPoseChannel *pchan;
145                 bDeformGroup *def;
146                 char *bone_select_array;
147                 int bone_select_tot= 0;
148                 const int defbase_tot= BLI_countlist(&ob->defbase);
149                 
150                 /* check that there is armature object with bones to use, otherwise return original mesh */
151                 if (ELEM3(NULL, mmd->ob_arm, mmd->ob_arm->pose, ob->defbase.first))
152                         return derivedData;
153                 
154                 bone_select_array= MEM_mallocN(defbase_tot * sizeof(char), "mask array");
155                 
156                 for (i = 0, def = ob->defbase.first; def; def = def->next, i++) {
157                         pchan = BKE_pose_channel_find_name(oba->pose, def->name);
158                         if (pchan && pchan->bone && (pchan->bone->flag & BONE_SELECTED)) {
159                                 bone_select_array[i]= TRUE;
160                                 bone_select_tot++;
161                         }
162                         else {
163                                 bone_select_array[i]= FALSE;
164                         }
165                 }
166
167                 /* hashes for finding mapping of:
168                  *      - vgroups to indices -> vgroupHash  (string, int)
169                  *      - bones to vgroup indices -> boneHash (index of vgroup, dummy)
170                  */
171                 vgroupHash= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "mask vgroup gh");
172                 
173                 /* build mapping of names of vertex groups to indices */
174                 for (i = 0, def = ob->defbase.first; def; def = def->next, i++) 
175                         BLI_ghash_insert(vgroupHash, def->name, SET_INT_IN_POINTER(i));
176                 
177                 /* if no bones selected, free hashes and return original mesh */
178                 if (bone_select_tot == 0) {
179                         BLI_ghash_free(vgroupHash, NULL, NULL);
180                         MEM_freeN(bone_select_array);
181                         
182                         return derivedData;
183                 }
184                 
185                 /* repeat the previous check, but for dverts */
186                 dvert= dm->getVertDataArray(dm, CD_MDEFORMVERT);
187                 if (dvert == NULL) {
188                         BLI_ghash_free(vgroupHash, NULL, NULL);
189                         MEM_freeN(bone_select_array);
190                         
191                         return derivedData;
192                 }
193                 
194                 /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
195                 vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask vert gh");
196                 
197                 /* add vertices which exist in vertexgroups into vertHash for filtering */
198                 for (i= 0, dv= dvert; i < maxVerts; i++, dv++) {
199                         MDeformWeight *dw= dv->dw;
200                         int j;
201                         
202                         for (j= dv->totweight; j > 0; j--, dw++) {
203                                 if (dw->def_nr < defbase_tot) {
204                                         if (bone_select_array[dw->def_nr]) {
205                                                 if (dw->weight != 0.0f) {
206                                                         break;
207                                                 }
208                                         }
209                                 }
210                         }
211                         
212                         /* check if include vert in vertHash */
213                         if (mmd->flag & MOD_MASK_INV) {
214                                 /* if this vert is in the vgroup, don't include it in vertHash */
215                                 if (dw) continue;
216                         }
217                         else {
218                                 /* if this vert isn't in the vgroup, don't include it in vertHash */
219                                 if (!dw) continue;
220                         }
221                         
222                         /* add to ghash for verts (numVerts acts as counter for mapping) */
223                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
224                         numVerts++;
225                 }
226                 
227                 /* free temp hashes */
228                 BLI_ghash_free(vgroupHash, NULL, NULL);
229                 MEM_freeN(bone_select_array);
230         }
231         else {          /* --- Using Nominated VertexGroup only --- */
232                 int defgrp_index = defgroup_name_index(ob, mmd->vgroup);
233                 
234                 /* get dverts */
235                 if (defgrp_index >= 0)
236                         dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
237                         
238                 /* if no vgroup (i.e. dverts) found, return the initial mesh */
239                 if ((defgrp_index < 0) || (dvert == NULL))
240                         return dm;
241                         
242                 /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
243                 vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask vert2 bh");
244                 
245                 /* add vertices which exist in vertexgroup into ghash for filtering */
246                 for (i= 0, dv= dvert; i < maxVerts; i++, dv++) {
247                         const int weight_set= defvert_find_weight(dv, defgrp_index) != 0.0f;
248                         
249                         /* check if include vert in vertHash */
250                         if (mmd->flag & MOD_MASK_INV) {
251                                 /* if this vert is in the vgroup, don't include it in vertHash */
252                                 if (weight_set) continue;
253                         }
254                         else {
255                                 /* if this vert isn't in the vgroup, don't include it in vertHash */
256                                 if (!weight_set) continue;
257                         }
258                         
259                         /* add to ghash for verts (numVerts acts as counter for mapping) */
260                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
261                         numVerts++;
262                 }
263         }
264
265         /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
266         edgeHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask ed2 gh");
267         polyHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "mask fa2 gh");
268         
269         mpoly = dm->getPolyArray(dm);
270         mloop = dm->getLoopArray(dm);
271
272         loop_mapping = MEM_callocN(sizeof(int) * maxPolys, "mask loopmap"); /* overalloc, assume all polys are seen */
273
274         /* loop over edges and faces, and do the same thing to 
275          * ensure that they only reference existing verts 
276          */
277         for (i = 0; i < maxEdges; i++)  {
278                 MEdge me;
279                 dm->getEdge(dm, i, &me);
280                 
281                 /* only add if both verts will be in new mesh */
282                 if (BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)) &&
283                     BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)))
284                 {
285                         BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numEdges));
286                         numEdges++;
287                 }
288         }
289         for (i = 0; i < maxPolys; i++) {
290                 MPoly *mp = &mpoly[i];
291                 MLoop *ml = mloop + mp->loopstart;
292                 int ok = TRUE;
293                 int j;
294                 
295                 for (j = 0; j < mp->totloop; j++, ml++) {
296                         if (!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(ml->v))) {
297                                 ok = FALSE;
298                                 break;
299                         }
300                 }
301                 
302                 /* all verts must be available */
303                 if (ok) {
304                         BLI_ghash_insert(polyHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numPolys));
305                         loop_mapping[numPolys] = numLoops;
306                         numPolys++;
307                         numLoops += mp->totloop;
308                 }
309         }
310         
311         
312         /* now we know the number of verts, edges and faces, 
313          * we can create the new (reduced) mesh
314          */
315         result = CDDM_from_template(dm, numVerts, numEdges, 0, numLoops, numPolys);
316         
317         mpoly_new = CDDM_get_polys(result);
318         mloop_new = CDDM_get_loops(result);
319         medge_new = CDDM_get_edges(result);
320         mvert_new = CDDM_get_verts(result);
321         
322         /* using ghash-iterators, map data into new mesh */
323         /* vertices */
324         for (hashIter = BLI_ghashIterator_new(vertHash);
325              !BLI_ghashIterator_isDone(hashIter);
326              BLI_ghashIterator_step(hashIter) )
327         {
328                 MVert source;
329                 MVert *dest;
330                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
331                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
332                 
333                 dm->getVert(dm, oldIndex, &source);
334                 dest = &mvert_new[newIndex];
335                 
336                 DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
337                 *dest = source;
338         }
339         BLI_ghashIterator_free(hashIter);
340                 
341         /* edges */
342         for (hashIter = BLI_ghashIterator_new(edgeHash);
343              !BLI_ghashIterator_isDone(hashIter);
344              BLI_ghashIterator_step(hashIter))
345         {
346                 MEdge source;
347                 MEdge *dest;
348                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
349                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
350                 
351                 dm->getEdge(dm, oldIndex, &source);
352                 dest = &medge_new[newIndex];
353                 
354                 source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
355                 source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
356                 
357                 DM_copy_edge_data(dm, result, oldIndex, newIndex, 1);
358                 *dest = source;
359         }
360         BLI_ghashIterator_free(hashIter);
361         
362         /* faces */
363         for (hashIter = BLI_ghashIterator_new(polyHash);
364              !BLI_ghashIterator_isDone(hashIter);
365              BLI_ghashIterator_step(hashIter) )
366         {
367                 int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
368                 int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
369                 MPoly *source = &mpoly[oldIndex];
370                 MPoly *dest = &mpoly_new[newIndex];
371                 int oldLoopIndex = source->loopstart;
372                 int newLoopIndex = loop_mapping[newIndex];
373                 MLoop *source_loop = &mloop[oldLoopIndex];
374                 MLoop *dest_loop = &mloop_new[newLoopIndex];
375                 
376                 DM_copy_poly_data(dm, result, oldIndex, newIndex, 1);
377                 DM_copy_loop_data(dm, result, oldLoopIndex, newLoopIndex, source->totloop);
378
379                 *dest = *source;
380                 dest->loopstart = newLoopIndex;
381                 for (i = 0; i < source->totloop; i++) {
382                         dest_loop[i].v = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source_loop[i].v)));
383                         dest_loop[i].e = GET_INT_FROM_POINTER(BLI_ghash_lookup(edgeHash, SET_INT_IN_POINTER(source_loop[i].e)));
384                 }
385         }
386
387         BLI_ghashIterator_free(hashIter);
388
389         MEM_freeN(loop_mapping);
390
391         /* why is this needed? - campbell */
392         /* recalculate normals */
393         CDDM_calc_normals(result);
394         
395         /* free hashes */
396         BLI_ghash_free(vertHash, NULL, NULL);
397         BLI_ghash_free(edgeHash, NULL, NULL);
398         BLI_ghash_free(polyHash, NULL, NULL);
399
400         /* return the new mesh */
401         return result;
402 }
403
404
405 ModifierTypeInfo modifierType_Mask = {
406         /* name */              "Mask",
407         /* structName */        "MaskModifierData",
408         /* structSize */        sizeof(MaskModifierData),
409         /* type */              eModifierTypeType_Nonconstructive,
410         /* flags */             eModifierTypeFlag_AcceptsMesh|eModifierTypeFlag_SupportsMapping|eModifierTypeFlag_SupportsEditmode,
411
412         /* copyData */          copyData,
413         /* deformVerts */       NULL,
414         /* deformMatrices */    NULL,
415         /* deformVertsEM */     NULL,
416         /* deformMatricesEM */  NULL,
417         /* applyModifier */     applyModifier,
418         /* applyModifierEM */   NULL,
419         /* initData */          NULL,
420         /* requiredDataMask */  requiredDataMask,
421         /* freeData */          NULL,
422         /* isDisabled */        NULL,
423         /* updateDepgraph */    updateDepgraph,
424         /* dependsOnTime */     NULL,
425         /* dependsOnNormals */  NULL,
426         /* foreachObjectLink */ foreachObjectLink,
427         /* foreachIDLink */     NULL,
428         /* foreachTexLink */    NULL,
429 };