Merge branch 'master' into blender2.8
[blender.git] / source / blender / modifiers / intern / MOD_boolean.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_boolean.c
32  *  \ingroup modifiers
33  */
34
35 // #ifdef DEBUG_TIME
36 #define USE_BMESH
37 #ifdef WITH_MOD_BOOLEAN
38 #  define USE_CARVE WITH_MOD_BOOLEAN
39 #endif
40
41 #include <stdio.h>
42
43 #include "DNA_object_types.h"
44
45 #include "BLI_utildefines.h"
46 #include "BLI_math_matrix.h"
47
48 #include "BKE_cdderivedmesh.h"
49 #include "BKE_library_query.h"
50 #include "BKE_modifier.h"
51
52 #include "depsgraph_private.h"
53
54 #include "MOD_boolean_util.h"
55 #include "MOD_util.h"
56
57
58 #ifdef USE_BMESH
59 #include "BLI_alloca.h"
60 #include "BLI_math_geom.h"
61 #include "BKE_material.h"
62 #include "MEM_guardedalloc.h"
63
64 #include "bmesh.h"
65 #include "bmesh_tools.h"
66 #include "tools/bmesh_intersect.h"
67 #endif
68
69 #ifdef DEBUG_TIME
70 #include "PIL_time.h"
71 #include "PIL_time_utildefines.h"
72 #endif
73
74 static void initData(ModifierData *md)
75 {
76         BooleanModifierData *bmd = (BooleanModifierData *)md;
77
78         bmd->solver = eBooleanModifierSolver_BMesh;
79         bmd->double_threshold = 1e-6f;
80 }
81
82 static void copyData(ModifierData *md, ModifierData *target)
83 {
84 #if 0
85         BooleanModifierData *bmd = (BooleanModifierData *) md;
86         BooleanModifierData *tbmd = (BooleanModifierData *) target;
87 #endif
88         modifier_copyData_generic(md, target);
89 }
90
91 static bool isDisabled(ModifierData *md, int UNUSED(useRenderParams))
92 {
93         BooleanModifierData *bmd = (BooleanModifierData *) md;
94
95         return !bmd->object;
96 }
97
98 static void foreachObjectLink(
99         ModifierData *md, Object *ob,
100         ObjectWalkFunc walk, void *userData)
101 {
102         BooleanModifierData *bmd = (BooleanModifierData *) md;
103
104         walk(userData, ob, &bmd->object, IDWALK_CB_NOP);
105 }
106
107 static void updateDepsgraph(ModifierData *md,
108                             struct Main *UNUSED(bmain),
109                             struct Scene *UNUSED(scene),
110                             Object *ob,
111                             struct DepsNodeHandle *node)
112 {
113         BooleanModifierData *bmd = (BooleanModifierData *)md;
114         if (bmd->object != NULL) {
115                 DEG_add_object_relation(node, bmd->object, DEG_OB_COMP_TRANSFORM, "Boolean Modifier");
116                 DEG_add_object_relation(node, bmd->object, DEG_OB_COMP_GEOMETRY, "Boolean Modifier");
117         }
118         /* We need own transformation as well. */
119         DEG_add_object_relation(node, ob, DEG_OB_COMP_TRANSFORM, "Boolean Modifier");
120 }
121
122 #if defined(USE_CARVE) || defined(USE_BMESH)
123
124 static DerivedMesh *get_quick_derivedMesh(
125         Object *ob_self,  DerivedMesh *dm_self,
126         Object *ob_other, DerivedMesh *dm_other,
127         int operation)
128 {
129         DerivedMesh *result = NULL;
130
131         if (dm_self->getNumPolys(dm_self) == 0 || dm_other->getNumPolys(dm_other) == 0) {
132                 switch (operation) {
133                         case eBooleanModifierOp_Intersect:
134                                 result = CDDM_new(0, 0, 0, 0, 0);
135                                 break;
136
137                         case eBooleanModifierOp_Union:
138                                 if (dm_self->getNumPolys(dm_self) != 0) {
139                                         result = dm_self;
140                                 }
141                                 else {
142                                         result = CDDM_copy(dm_other);
143
144                                         float imat[4][4];
145                                         float omat[4][4];
146
147                                         invert_m4_m4(imat, ob_self->obmat);
148                                         mul_m4_m4m4(omat, imat, ob_other->obmat);
149
150                                         const int mverts_len = result->getNumVerts(result);
151                                         MVert *mv = CDDM_get_verts(result);
152
153                                         for (int i = 0; i < mverts_len; i++, mv++) {
154                                                 mul_m4_v3(omat, mv->co);
155                                         }
156
157                                         result->dirty |= DM_DIRTY_NORMALS;
158                                 }
159
160                                 break;
161
162                         case eBooleanModifierOp_Difference:
163                                 result = dm_self;
164                                 break;
165                 }
166         }
167
168         return result;
169 }
170 #endif  /* defined(USE_CARVE) || defined(USE_BMESH) */
171
172
173 /* -------------------------------------------------------------------- */
174 /* BMESH */
175
176 #ifdef USE_BMESH
177
178 /* has no meaning for faces, do this so we can tell which face is which */
179 #define BM_FACE_TAG BM_ELEM_DRAW
180
181 /**
182  * Compare selected/unselected.
183  */
184 static int bm_face_isect_pair(BMFace *f, void *UNUSED(user_data))
185 {
186         return BM_elem_flag_test(f, BM_FACE_TAG) ? 1 : 0;
187 }
188
189 static DerivedMesh *applyModifier_bmesh(
190         ModifierData *md, Object *ob,
191         DerivedMesh *dm,
192         ModifierApplyFlag flag)
193 {
194         BooleanModifierData *bmd = (BooleanModifierData *) md;
195         DerivedMesh *dm_other;
196
197         if (!bmd->object)
198                 return dm;
199
200         dm_other = get_dm_for_modifier(bmd->object, flag);
201
202         if (dm_other) {
203                 DerivedMesh *result;
204
205                 /* when one of objects is empty (has got no faces) we could speed up
206                  * calculation a bit returning one of objects' derived meshes (or empty one)
207                  * Returning mesh is depended on modifiers operation (sergey) */
208                 result = get_quick_derivedMesh(ob, dm, bmd->object, dm_other, bmd->operation);
209
210                 if (result == NULL) {
211                         BMesh *bm;
212                         const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_DM(dm, dm_other);
213
214 #ifdef DEBUG_TIME
215                         TIMEIT_START(boolean_bmesh);
216 #endif
217                         bm = BM_mesh_create(
218                                  &allocsize,
219                                  &((struct BMeshCreateParams){.use_toolflags = false,}));
220
221                         DM_to_bmesh_ex(dm_other, bm, true);
222                         DM_to_bmesh_ex(dm, bm, true);
223
224                         /* main bmesh intersection setup */
225                         {
226                                 /* create tessface & intersect */
227                                 const int looptris_tot = poly_to_tri_count(bm->totface, bm->totloop);
228                                 int tottri;
229                                 BMLoop *(*looptris)[3];
230
231                                 looptris = MEM_mallocN(sizeof(*looptris) * looptris_tot, __func__);
232
233                                 BM_mesh_calc_tessellation(bm, looptris, &tottri);
234
235                                 /* postpone this until after tessellating
236                                  * so we can use the original normals before the vertex are moved */
237                                 {
238                                         BMIter iter;
239                                         int i;
240                                         const int i_verts_end = dm_other->getNumVerts(dm_other);
241                                         const int i_faces_end = dm_other->getNumPolys(dm_other);
242
243                                         float imat[4][4];
244                                         float omat[4][4];
245
246                                         invert_m4_m4(imat, ob->obmat);
247                                         mul_m4_m4m4(omat, imat, bmd->object->obmat);
248
249
250                                         BMVert *eve;
251                                         i = 0;
252                                         BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
253                                                 mul_m4_v3(omat, eve->co);
254                                                 if (++i == i_verts_end) {
255                                                         break;
256                                                 }
257                                         }
258
259                                         /* we need face normals because of 'BM_face_split_edgenet'
260                                          * we could calculate on the fly too (before calling split). */
261                                         {
262                                                 float nmat[4][4];
263                                                 invert_m4_m4(nmat, omat);
264
265                                                 const short ob_src_totcol = bmd->object->totcol;
266                                                 short *material_remap = BLI_array_alloca(material_remap, ob_src_totcol ? ob_src_totcol : 1);
267
268                                                 BKE_material_remap_object_calc(ob, bmd->object, material_remap);
269
270                                                 BMFace *efa;
271                                                 i = 0;
272                                                 BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
273                                                         mul_transposed_mat3_m4_v3(nmat, efa->no);
274                                                         normalize_v3(efa->no);
275                                                         BM_elem_flag_enable(efa, BM_FACE_TAG);  /* temp tag to test which side split faces are from */
276
277                                                         /* remap material */
278                                                         if (LIKELY(efa->mat_nr < ob_src_totcol)) {
279                                                                 efa->mat_nr = material_remap[efa->mat_nr];
280                                                         }
281
282                                                         if (++i == i_faces_end) {
283                                                                 break;
284                                                         }
285                                                 }
286                                         }
287                                 }
288
289                                 /* not needed, but normals for 'dm' will be invalid,
290                                  * currently this is ok for 'BM_mesh_intersect' */
291                                 // BM_mesh_normals_update(bm);
292
293                                 /* change for testing */
294                                 bool use_separate = false;
295                                 bool use_dissolve = true;
296                                 bool use_island_connect = true;
297
298                                 BM_mesh_intersect(
299                                         bm,
300                                         looptris, tottri,
301                                         bm_face_isect_pair, NULL,
302                                         false,
303                                         use_separate,
304                                         use_dissolve,
305                                         use_island_connect,
306                                         false,
307                                         bmd->operation,
308                                         bmd->double_threshold);
309
310                                 MEM_freeN(looptris);
311                         }
312
313                         result = CDDM_from_bmesh(bm, true);
314
315                         BM_mesh_free(bm);
316
317                         result->dirty |= DM_DIRTY_NORMALS;
318
319 #ifdef DEBUG_TIME
320                         TIMEIT_END(boolean_bmesh);
321 #endif
322
323                         return result;
324                 }
325
326                 /* if new mesh returned, return it; otherwise there was
327                  * an error, so delete the modifier object */
328                 if (result)
329                         return result;
330                 else
331                         modifier_setError(md, "Cannot execute boolean operation");
332         }
333
334         return dm;
335 }
336 #endif  /* USE_BMESH */
337
338
339 /* -------------------------------------------------------------------- */
340 /* CARVE */
341
342 #ifdef USE_CARVE
343 static DerivedMesh *applyModifier_carve(
344         ModifierData *md, Object *ob,
345         DerivedMesh *derivedData,
346         ModifierApplyFlag flag)
347 {
348         BooleanModifierData *bmd = (BooleanModifierData *) md;
349         DerivedMesh *dm;
350
351         if (!bmd->object)
352                 return derivedData;
353
354         dm = get_dm_for_modifier(bmd->object, flag);
355
356         if (dm) {
357                 DerivedMesh *result;
358
359                 /* when one of objects is empty (has got no faces) we could speed up
360                  * calculation a bit returning one of objects' derived meshes (or empty one)
361                  * Returning mesh is depended on modifiers operation (sergey) */
362                 result = get_quick_derivedMesh(ob, derivedData, bmd->object, dm, bmd->operation);
363
364                 if (result == NULL) {
365 #ifdef DEBUG_TIME
366                         TIMEIT_START(boolean_carve);
367 #endif
368
369                         result = NewBooleanDerivedMesh(dm, bmd->object, derivedData, ob,
370                                                        1 + bmd->operation);
371 #ifdef DEBUG_TIME
372                         TIMEIT_END(boolean_carve);
373 #endif
374                 }
375
376                 /* if new mesh returned, return it; otherwise there was
377                  * an error, so delete the modifier object */
378                 if (result)
379                         return result;
380                 else
381                         modifier_setError(md, "Cannot execute boolean operation");
382         }
383         
384         return derivedData;
385 }
386 #endif  /* USE_CARVE */
387
388
389 static DerivedMesh *applyModifier_nop(
390         ModifierData *UNUSED(md), Object *UNUSED(ob),
391         DerivedMesh *derivedData,
392         ModifierApplyFlag UNUSED(flag))
393 {
394         return derivedData;
395 }
396
397 static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
398 {
399         CustomDataMask dataMask = CD_MASK_MTFACE | CD_MASK_MEDGE;
400
401         dataMask |= CD_MASK_MDEFORMVERT;
402         
403         return dataMask;
404 }
405
406 static DerivedMesh *applyModifier(
407         ModifierData *md, Object *ob,
408         DerivedMesh *derivedData,
409         ModifierApplyFlag flag)
410 {
411         BooleanModifierData *bmd = (BooleanModifierData *)md;
412
413         switch (bmd->solver) {
414 #ifdef USE_CARVE
415                 case eBooleanModifierSolver_Carve:
416                         return applyModifier_carve(md, ob, derivedData, flag);
417 #endif
418 #ifdef USE_BMESH
419                 case eBooleanModifierSolver_BMesh:
420                         return applyModifier_bmesh(md, ob, derivedData, flag);
421 #endif
422                 default:
423                         return applyModifier_nop(md, ob, derivedData, flag);
424         }
425 }
426
427
428 ModifierTypeInfo modifierType_Boolean = {
429         /* name */              "Boolean",
430         /* structName */        "BooleanModifierData",
431         /* structSize */        sizeof(BooleanModifierData),
432         /* type */              eModifierTypeType_Nonconstructive,
433         /* flags */             eModifierTypeFlag_AcceptsMesh |
434                                 eModifierTypeFlag_UsesPointCache,
435
436         /* copyData */          copyData,
437         /* deformVerts */       NULL,
438         /* deformMatrices */    NULL,
439         /* deformVertsEM */     NULL,
440         /* deformMatricesEM */  NULL,
441         /* applyModifier */     applyModifier,
442         /* applyModifierEM */   NULL,
443         /* initData */          initData,
444         /* requiredDataMask */  requiredDataMask,
445         /* freeData */          NULL,
446         /* isDisabled */        isDisabled,
447         /* updateDepsgraph */   updateDepsgraph,
448         /* dependsOnTime */     NULL,
449         /* dependsOnNormals */  NULL,
450         /* foreachObjectLink */ foreachObjectLink,
451         /* foreachIDLink */     NULL,
452         /* foreachTexLink */    NULL,
453 };