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