1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19 
20 /** \file
21  * \ingroup bke
22  */
23 
24 #include "MEM_guardedalloc.h"
25 
26 /* Allow using deprecated functionality for .blend file I/O. */
27 #define DNA_DEPRECATED_ALLOW
28 
29 #include "DNA_defaults.h"
30 #include "DNA_key_types.h"
31 #include "DNA_material_types.h"
32 #include "DNA_mesh_types.h"
33 #include "DNA_meshdata_types.h"
34 #include "DNA_object_types.h"
35 
36 #include "BLI_bitmap.h"
37 #include "BLI_edgehash.h"
38 #include "BLI_endian_switch.h"
39 #include "BLI_ghash.h"
40 #include "BLI_hash.h"
41 #include "BLI_linklist.h"
42 #include "BLI_math.h"
43 #include "BLI_memarena.h"
44 #include "BLI_string.h"
45 #include "BLI_utildefines.h"
46 
47 #include "BLT_translation.h"
48 
49 #include "BKE_anim_data.h"
50 #include "BKE_deform.h"
51 #include "BKE_editmesh.h"
52 #include "BKE_global.h"
53 #include "BKE_idtype.h"
54 #include "BKE_key.h"
55 #include "BKE_lib_id.h"
56 #include "BKE_lib_query.h"
57 #include "BKE_main.h"
58 #include "BKE_material.h"
59 #include "BKE_mesh.h"
60 #include "BKE_mesh_runtime.h"
61 #include "BKE_mesh_wrapper.h"
62 #include "BKE_modifier.h"
63 #include "BKE_multires.h"
64 #include "BKE_object.h"
65 
66 #include "PIL_time.h"
67 
68 #include "DEG_depsgraph.h"
69 #include "DEG_depsgraph_query.h"
70 
71 #include "BLO_read_write.h"
72 
73 static void mesh_clear_geometry(Mesh *mesh);
74 static void mesh_tessface_clear_intern(Mesh *mesh, int free_customdata);
75 
mesh_init_data(ID * id)76 static void mesh_init_data(ID *id)
77 {
78   Mesh *mesh = (Mesh *)id;
79 
80   BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(mesh, id));
81 
82   MEMCPY_STRUCT_AFTER(mesh, DNA_struct_default_get(Mesh), id);
83 
84   CustomData_reset(&mesh->vdata);
85   CustomData_reset(&mesh->edata);
86   CustomData_reset(&mesh->fdata);
87   CustomData_reset(&mesh->pdata);
88   CustomData_reset(&mesh->ldata);
89 
90   BKE_mesh_runtime_reset(mesh);
91 
92   mesh->face_sets_color_seed = BLI_hash_int(PIL_check_seconds_timer_i() & UINT_MAX);
93 }
94 
mesh_copy_data(Main * bmain,ID * id_dst,const ID * id_src,const int flag)95 static void mesh_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const int flag)
96 {
97   Mesh *mesh_dst = (Mesh *)id_dst;
98   const Mesh *mesh_src = (const Mesh *)id_src;
99 
100   BKE_mesh_runtime_reset_on_copy(mesh_dst, flag);
101   if ((mesh_src->id.tag & LIB_TAG_NO_MAIN) == 0) {
102     /* This is a direct copy of a main mesh, so for now it has the same topology. */
103     mesh_dst->runtime.deformed_only = true;
104   }
105   /* This option is set for run-time meshes that have been copied from the current objects mode.
106    * Currently this is used for edit-mesh although it could be used for sculpt or other
107    * kinds of data specific to an objects mode.
108    *
109    * The flag signals that the mesh hasn't been modified from the data that generated it,
110    * allowing us to use the object-mode data for drawing.
111    *
112    * While this could be the callers responsibility, keep here since it's
113    * highly unlikely we want to create a duplicate and not use it for drawing. */
114   mesh_dst->runtime.is_original = false;
115 
116   /* Only do tessface if we have no polys. */
117   const bool do_tessface = ((mesh_src->totface != 0) && (mesh_src->totpoly == 0));
118 
119   CustomData_MeshMasks mask = CD_MASK_MESH;
120 
121   if (mesh_src->id.tag & LIB_TAG_NO_MAIN) {
122     /* For copies in depsgraph, keep data like origindex and orco. */
123     CustomData_MeshMasks_update(&mask, &CD_MASK_DERIVEDMESH);
124   }
125 
126   mesh_dst->mat = MEM_dupallocN(mesh_src->mat);
127 
128   const eCDAllocType alloc_type = (flag & LIB_ID_COPY_CD_REFERENCE) ? CD_REFERENCE : CD_DUPLICATE;
129   CustomData_copy(&mesh_src->vdata, &mesh_dst->vdata, mask.vmask, alloc_type, mesh_dst->totvert);
130   CustomData_copy(&mesh_src->edata, &mesh_dst->edata, mask.emask, alloc_type, mesh_dst->totedge);
131   CustomData_copy(&mesh_src->ldata, &mesh_dst->ldata, mask.lmask, alloc_type, mesh_dst->totloop);
132   CustomData_copy(&mesh_src->pdata, &mesh_dst->pdata, mask.pmask, alloc_type, mesh_dst->totpoly);
133   if (do_tessface) {
134     CustomData_copy(&mesh_src->fdata, &mesh_dst->fdata, mask.fmask, alloc_type, mesh_dst->totface);
135   }
136   else {
137     mesh_tessface_clear_intern(mesh_dst, false);
138   }
139 
140   BKE_mesh_update_customdata_pointers(mesh_dst, do_tessface);
141 
142   mesh_dst->edit_mesh = NULL;
143 
144   mesh_dst->mselect = MEM_dupallocN(mesh_dst->mselect);
145 
146   /* TODO Do we want to add flag to prevent this? */
147   if (mesh_src->key && (flag & LIB_ID_COPY_SHAPEKEY)) {
148     BKE_id_copy_ex(bmain, &mesh_src->key->id, (ID **)&mesh_dst->key, flag);
149     /* XXX This is not nice, we need to make BKE_id_copy_ex fully re-entrant... */
150     mesh_dst->key->from = &mesh_dst->id;
151   }
152 }
153 
mesh_free_data(ID * id)154 static void mesh_free_data(ID *id)
155 {
156   Mesh *mesh = (Mesh *)id;
157 
158   BKE_mesh_runtime_clear_cache(mesh);
159   mesh_clear_geometry(mesh);
160   MEM_SAFE_FREE(mesh->mat);
161 }
162 
mesh_foreach_id(ID * id,LibraryForeachIDData * data)163 static void mesh_foreach_id(ID *id, LibraryForeachIDData *data)
164 {
165   Mesh *mesh = (Mesh *)id;
166   BKE_LIB_FOREACHID_PROCESS(data, mesh->texcomesh, IDWALK_CB_NEVER_SELF);
167   BKE_LIB_FOREACHID_PROCESS(data, mesh->key, IDWALK_CB_USER);
168   for (int i = 0; i < mesh->totcol; i++) {
169     BKE_LIB_FOREACHID_PROCESS(data, mesh->mat[i], IDWALK_CB_USER);
170   }
171 }
172 
mesh_blend_write(BlendWriter * writer,ID * id,const void * id_address)173 static void mesh_blend_write(BlendWriter *writer, ID *id, const void *id_address)
174 {
175   Mesh *mesh = (Mesh *)id;
176   if (mesh->id.us > 0 || BLO_write_is_undo(writer)) {
177     /* cache only - don't write */
178     mesh->mface = NULL;
179     mesh->totface = 0;
180     memset(&mesh->fdata, 0, sizeof(mesh->fdata));
181     memset(&mesh->runtime, 0, sizeof(mesh->runtime));
182 
183     CustomDataLayer *vlayers = NULL, vlayers_buff[CD_TEMP_CHUNK_SIZE];
184     CustomDataLayer *elayers = NULL, elayers_buff[CD_TEMP_CHUNK_SIZE];
185     CustomDataLayer *flayers = NULL, flayers_buff[CD_TEMP_CHUNK_SIZE];
186     CustomDataLayer *llayers = NULL, llayers_buff[CD_TEMP_CHUNK_SIZE];
187     CustomDataLayer *players = NULL, players_buff[CD_TEMP_CHUNK_SIZE];
188 
189     CustomData_blend_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff));
190     CustomData_blend_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff));
191     flayers = flayers_buff;
192     CustomData_blend_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff));
193     CustomData_blend_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff));
194 
195     BLO_write_id_struct(writer, Mesh, id_address, &mesh->id);
196     BKE_id_blend_write(writer, &mesh->id);
197 
198     /* direct data */
199     if (mesh->adt) {
200       BKE_animdata_blend_write(writer, mesh->adt);
201     }
202 
203     BLO_write_pointer_array(writer, mesh->totcol, mesh->mat);
204     BLO_write_raw(writer, sizeof(MSelect) * mesh->totselect, mesh->mselect);
205 
206     CustomData_blend_write(
207         writer, &mesh->vdata, vlayers, mesh->totvert, CD_MASK_MESH.vmask, &mesh->id);
208     CustomData_blend_write(
209         writer, &mesh->edata, elayers, mesh->totedge, CD_MASK_MESH.emask, &mesh->id);
210     /* fdata is really a dummy - written so slots align */
211     CustomData_blend_write(
212         writer, &mesh->fdata, flayers, mesh->totface, CD_MASK_MESH.fmask, &mesh->id);
213     CustomData_blend_write(
214         writer, &mesh->ldata, llayers, mesh->totloop, CD_MASK_MESH.lmask, &mesh->id);
215     CustomData_blend_write(
216         writer, &mesh->pdata, players, mesh->totpoly, CD_MASK_MESH.pmask, &mesh->id);
217 
218     /* Free temporary data */
219 
220 /* Free custom-data layers, when not assigned a buffer value. */
221 #define CD_LAYERS_FREE(id) \
222   if (id && id != id##_buff) { \
223     MEM_freeN(id); \
224   } \
225   ((void)0)
226 
227     CD_LAYERS_FREE(vlayers);
228     CD_LAYERS_FREE(elayers);
229     /* CD_LAYER_FREE(flayers); */ /* Never allocated. */
230     CD_LAYERS_FREE(llayers);
231     CD_LAYERS_FREE(players);
232 
233 #undef CD_LAYERS_FREE
234   }
235 }
236 
mesh_blend_read_data(BlendDataReader * reader,ID * id)237 static void mesh_blend_read_data(BlendDataReader *reader, ID *id)
238 {
239   Mesh *mesh = (Mesh *)id;
240   BLO_read_pointer_array(reader, (void **)&mesh->mat);
241 
242   BLO_read_data_address(reader, &mesh->mvert);
243   BLO_read_data_address(reader, &mesh->medge);
244   BLO_read_data_address(reader, &mesh->mface);
245   BLO_read_data_address(reader, &mesh->mloop);
246   BLO_read_data_address(reader, &mesh->mpoly);
247   BLO_read_data_address(reader, &mesh->tface);
248   BLO_read_data_address(reader, &mesh->mtface);
249   BLO_read_data_address(reader, &mesh->mcol);
250   BLO_read_data_address(reader, &mesh->dvert);
251   BLO_read_data_address(reader, &mesh->mloopcol);
252   BLO_read_data_address(reader, &mesh->mloopuv);
253   BLO_read_data_address(reader, &mesh->mselect);
254 
255   /* animdata */
256   BLO_read_data_address(reader, &mesh->adt);
257   BKE_animdata_blend_read_data(reader, mesh->adt);
258 
259   /* Normally BKE_defvert_blend_read should be called in CustomData_blend_read,
260    * but for backwards compatibility in do_versions to work we do it here. */
261   BKE_defvert_blend_read(reader, mesh->totvert, mesh->dvert);
262 
263   CustomData_blend_read(reader, &mesh->vdata, mesh->totvert);
264   CustomData_blend_read(reader, &mesh->edata, mesh->totedge);
265   CustomData_blend_read(reader, &mesh->fdata, mesh->totface);
266   CustomData_blend_read(reader, &mesh->ldata, mesh->totloop);
267   CustomData_blend_read(reader, &mesh->pdata, mesh->totpoly);
268 
269   mesh->texflag &= ~ME_AUTOSPACE_EVALUATED;
270   mesh->edit_mesh = NULL;
271   BKE_mesh_runtime_reset(mesh);
272 
273   /* happens with old files */
274   if (mesh->mselect == NULL) {
275     mesh->totselect = 0;
276   }
277 
278   /* Multires data */
279   BLO_read_data_address(reader, &mesh->mr);
280   if (mesh->mr) {
281     BLO_read_list(reader, &mesh->mr->levels);
282     MultiresLevel *lvl = mesh->mr->levels.first;
283 
284     CustomData_blend_read(reader, &mesh->mr->vdata, lvl->totvert);
285     BKE_defvert_blend_read(
286         reader, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
287     CustomData_blend_read(reader, &mesh->mr->fdata, lvl->totface);
288 
289     BLO_read_data_address(reader, &mesh->mr->edge_flags);
290     BLO_read_data_address(reader, &mesh->mr->edge_creases);
291 
292     BLO_read_data_address(reader, &mesh->mr->verts);
293 
294     /* If mesh has the same number of vertices as the
295      * highest multires level, load the current mesh verts
296      * into multires and discard the old data. Needed
297      * because some saved files either do not have a verts
298      * array, or the verts array contains out-of-date
299      * data. */
300     if (mesh->totvert == ((MultiresLevel *)mesh->mr->levels.last)->totvert) {
301       if (mesh->mr->verts) {
302         MEM_freeN(mesh->mr->verts);
303       }
304       mesh->mr->verts = MEM_dupallocN(mesh->mvert);
305     }
306 
307     for (; lvl; lvl = lvl->next) {
308       BLO_read_data_address(reader, &lvl->verts);
309       BLO_read_data_address(reader, &lvl->faces);
310       BLO_read_data_address(reader, &lvl->edges);
311       BLO_read_data_address(reader, &lvl->colfaces);
312     }
313   }
314 
315   /* if multires is present but has no valid vertex data,
316    * there's no way to recover it; silently remove multires */
317   if (mesh->mr && !mesh->mr->verts) {
318     multires_free(mesh->mr);
319     mesh->mr = NULL;
320   }
321 
322   if ((BLO_read_requires_endian_switch(reader)) && mesh->tface) {
323     TFace *tf = mesh->tface;
324     for (int i = 0; i < mesh->totface; i++, tf++) {
325       BLI_endian_switch_uint32_array(tf->col, 4);
326     }
327   }
328 }
329 
mesh_blend_read_lib(BlendLibReader * reader,ID * id)330 static void mesh_blend_read_lib(BlendLibReader *reader, ID *id)
331 {
332   Mesh *me = (Mesh *)id;
333   /* this check added for python created meshes */
334   if (me->mat) {
335     for (int i = 0; i < me->totcol; i++) {
336       BLO_read_id_address(reader, me->id.lib, &me->mat[i]);
337     }
338   }
339   else {
340     me->totcol = 0;
341   }
342 
343   BLO_read_id_address(reader, me->id.lib, &me->ipo);  // XXX: deprecated: old anim sys
344   BLO_read_id_address(reader, me->id.lib, &me->key);
345   BLO_read_id_address(reader, me->id.lib, &me->texcomesh);
346 }
347 
mesh_read_expand(BlendExpander * expander,ID * id)348 static void mesh_read_expand(BlendExpander *expander, ID *id)
349 {
350   Mesh *me = (Mesh *)id;
351   for (int a = 0; a < me->totcol; a++) {
352     BLO_expand(expander, me->mat[a]);
353   }
354 
355   BLO_expand(expander, me->key);
356   BLO_expand(expander, me->texcomesh);
357 }
358 
359 IDTypeInfo IDType_ID_ME = {
360     .id_code = ID_ME,
361     .id_filter = FILTER_ID_ME,
362     .main_listbase_index = INDEX_ID_ME,
363     .struct_size = sizeof(Mesh),
364     .name = "Mesh",
365     .name_plural = "meshes",
366     .translation_context = BLT_I18NCONTEXT_ID_MESH,
367     .flags = 0,
368 
369     .init_data = mesh_init_data,
370     .copy_data = mesh_copy_data,
371     .free_data = mesh_free_data,
372     .make_local = NULL,
373     .foreach_id = mesh_foreach_id,
374     .foreach_cache = NULL,
375 
376     .blend_write = mesh_blend_write,
377     .blend_read_data = mesh_blend_read_data,
378     .blend_read_lib = mesh_blend_read_lib,
379     .blend_read_expand = mesh_read_expand,
380 };
381 
382 enum {
383   MESHCMP_DVERT_WEIGHTMISMATCH = 1,
384   MESHCMP_DVERT_GROUPMISMATCH,
385   MESHCMP_DVERT_TOTGROUPMISMATCH,
386   MESHCMP_LOOPCOLMISMATCH,
387   MESHCMP_LOOPUVMISMATCH,
388   MESHCMP_LOOPMISMATCH,
389   MESHCMP_POLYVERTMISMATCH,
390   MESHCMP_POLYMISMATCH,
391   MESHCMP_EDGEUNKNOWN,
392   MESHCMP_VERTCOMISMATCH,
393   MESHCMP_CDLAYERS_MISMATCH,
394 };
395 
cmpcode_to_str(int code)396 static const char *cmpcode_to_str(int code)
397 {
398   switch (code) {
399     case MESHCMP_DVERT_WEIGHTMISMATCH:
400       return "Vertex Weight Mismatch";
401     case MESHCMP_DVERT_GROUPMISMATCH:
402       return "Vertex Group Mismatch";
403     case MESHCMP_DVERT_TOTGROUPMISMATCH:
404       return "Vertex Doesn't Belong To Same Number Of Groups";
405     case MESHCMP_LOOPCOLMISMATCH:
406       return "Vertex Color Mismatch";
407     case MESHCMP_LOOPUVMISMATCH:
408       return "UV Mismatch";
409     case MESHCMP_LOOPMISMATCH:
410       return "Loop Mismatch";
411     case MESHCMP_POLYVERTMISMATCH:
412       return "Loop Vert Mismatch In Poly Test";
413     case MESHCMP_POLYMISMATCH:
414       return "Loop Vert Mismatch";
415     case MESHCMP_EDGEUNKNOWN:
416       return "Edge Mismatch";
417     case MESHCMP_VERTCOMISMATCH:
418       return "Vertex Coordinate Mismatch";
419     case MESHCMP_CDLAYERS_MISMATCH:
420       return "CustomData Layer Count Mismatch";
421     default:
422       return "Mesh Comparison Code Unknown";
423   }
424 }
425 
426 /* thresh is threshold for comparing vertices, uvs, vertex colors,
427  * weights, etc.*/
customdata_compare(CustomData * c1,CustomData * c2,Mesh * m1,Mesh * m2,const float thresh)428 static int customdata_compare(
429     CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2, const float thresh)
430 {
431   const float thresh_sq = thresh * thresh;
432   CustomDataLayer *l1, *l2;
433   int i, i1 = 0, i2 = 0, tot, j;
434 
435   for (i = 0; i < c1->totlayer; i++) {
436     if (ELEM(c1->layers[i].type,
437              CD_MVERT,
438              CD_MEDGE,
439              CD_MPOLY,
440              CD_MLOOPUV,
441              CD_MLOOPCOL,
442              CD_MDEFORMVERT)) {
443       i1++;
444     }
445   }
446 
447   for (i = 0; i < c2->totlayer; i++) {
448     if (ELEM(c2->layers[i].type,
449              CD_MVERT,
450              CD_MEDGE,
451              CD_MPOLY,
452              CD_MLOOPUV,
453              CD_MLOOPCOL,
454              CD_MDEFORMVERT)) {
455       i2++;
456     }
457   }
458 
459   if (i1 != i2) {
460     return MESHCMP_CDLAYERS_MISMATCH;
461   }
462 
463   l1 = c1->layers;
464   l2 = c2->layers;
465   tot = i1;
466   i1 = 0;
467   i2 = 0;
468   for (i = 0; i < tot; i++) {
469     while (
470         i1 < c1->totlayer &&
471         !ELEM(l1->type, CD_MVERT, CD_MEDGE, CD_MPOLY, CD_MLOOPUV, CD_MLOOPCOL, CD_MDEFORMVERT)) {
472       i1++;
473       l1++;
474     }
475 
476     while (
477         i2 < c2->totlayer &&
478         !ELEM(l2->type, CD_MVERT, CD_MEDGE, CD_MPOLY, CD_MLOOPUV, CD_MLOOPCOL, CD_MDEFORMVERT)) {
479       i2++;
480       l2++;
481     }
482 
483     if (l1->type == CD_MVERT) {
484       MVert *v1 = l1->data;
485       MVert *v2 = l2->data;
486       int vtot = m1->totvert;
487 
488       for (j = 0; j < vtot; j++, v1++, v2++) {
489         if (len_squared_v3v3(v1->co, v2->co) > thresh_sq) {
490           return MESHCMP_VERTCOMISMATCH;
491         }
492         /* I don't care about normals, let's just do coordinates */
493       }
494     }
495 
496     /*we're order-agnostic for edges here*/
497     if (l1->type == CD_MEDGE) {
498       MEdge *e1 = l1->data;
499       MEdge *e2 = l2->data;
500       int etot = m1->totedge;
501       EdgeHash *eh = BLI_edgehash_new_ex(__func__, etot);
502 
503       for (j = 0; j < etot; j++, e1++) {
504         BLI_edgehash_insert(eh, e1->v1, e1->v2, e1);
505       }
506 
507       for (j = 0; j < etot; j++, e2++) {
508         if (!BLI_edgehash_lookup(eh, e2->v1, e2->v2)) {
509           return MESHCMP_EDGEUNKNOWN;
510         }
511       }
512       BLI_edgehash_free(eh, NULL);
513     }
514 
515     if (l1->type == CD_MPOLY) {
516       MPoly *p1 = l1->data;
517       MPoly *p2 = l2->data;
518       int ptot = m1->totpoly;
519 
520       for (j = 0; j < ptot; j++, p1++, p2++) {
521         MLoop *lp1, *lp2;
522         int k;
523 
524         if (p1->totloop != p2->totloop) {
525           return MESHCMP_POLYMISMATCH;
526         }
527 
528         lp1 = m1->mloop + p1->loopstart;
529         lp2 = m2->mloop + p2->loopstart;
530 
531         for (k = 0; k < p1->totloop; k++, lp1++, lp2++) {
532           if (lp1->v != lp2->v) {
533             return MESHCMP_POLYVERTMISMATCH;
534           }
535         }
536       }
537     }
538     if (l1->type == CD_MLOOP) {
539       MLoop *lp1 = l1->data;
540       MLoop *lp2 = l2->data;
541       int ltot = m1->totloop;
542 
543       for (j = 0; j < ltot; j++, lp1++, lp2++) {
544         if (lp1->v != lp2->v) {
545           return MESHCMP_LOOPMISMATCH;
546         }
547       }
548     }
549     if (l1->type == CD_MLOOPUV) {
550       MLoopUV *lp1 = l1->data;
551       MLoopUV *lp2 = l2->data;
552       int ltot = m1->totloop;
553 
554       for (j = 0; j < ltot; j++, lp1++, lp2++) {
555         if (len_squared_v2v2(lp1->uv, lp2->uv) > thresh_sq) {
556           return MESHCMP_LOOPUVMISMATCH;
557         }
558       }
559     }
560 
561     if (l1->type == CD_MLOOPCOL) {
562       MLoopCol *lp1 = l1->data;
563       MLoopCol *lp2 = l2->data;
564       int ltot = m1->totloop;
565 
566       for (j = 0; j < ltot; j++, lp1++, lp2++) {
567         if (abs(lp1->r - lp2->r) > thresh || abs(lp1->g - lp2->g) > thresh ||
568             abs(lp1->b - lp2->b) > thresh || abs(lp1->a - lp2->a) > thresh) {
569           return MESHCMP_LOOPCOLMISMATCH;
570         }
571       }
572     }
573 
574     if (l1->type == CD_MDEFORMVERT) {
575       MDeformVert *dv1 = l1->data;
576       MDeformVert *dv2 = l2->data;
577       int dvtot = m1->totvert;
578 
579       for (j = 0; j < dvtot; j++, dv1++, dv2++) {
580         int k;
581         MDeformWeight *dw1 = dv1->dw, *dw2 = dv2->dw;
582 
583         if (dv1->totweight != dv2->totweight) {
584           return MESHCMP_DVERT_TOTGROUPMISMATCH;
585         }
586 
587         for (k = 0; k < dv1->totweight; k++, dw1++, dw2++) {
588           if (dw1->def_nr != dw2->def_nr) {
589             return MESHCMP_DVERT_GROUPMISMATCH;
590           }
591           if (fabsf(dw1->weight - dw2->weight) > thresh) {
592             return MESHCMP_DVERT_WEIGHTMISMATCH;
593           }
594         }
595       }
596     }
597   }
598 
599   return 0;
600 }
601 
602 /**
603  * Used for unit testing; compares two meshes, checking only
604  * differences we care about.  should be usable with leaf's
605  * testing framework I get RNA work done, will use hackish
606  * testing code for now.
607  */
BKE_mesh_cmp(Mesh * me1,Mesh * me2,float thresh)608 const char *BKE_mesh_cmp(Mesh *me1, Mesh *me2, float thresh)
609 {
610   int c;
611 
612   if (!me1 || !me2) {
613     return "Requires two input meshes";
614   }
615 
616   if (me1->totvert != me2->totvert) {
617     return "Number of verts don't match";
618   }
619 
620   if (me1->totedge != me2->totedge) {
621     return "Number of edges don't match";
622   }
623 
624   if (me1->totpoly != me2->totpoly) {
625     return "Number of faces don't match";
626   }
627 
628   if (me1->totloop != me2->totloop) {
629     return "Number of loops don't match";
630   }
631 
632   if ((c = customdata_compare(&me1->vdata, &me2->vdata, me1, me2, thresh))) {
633     return cmpcode_to_str(c);
634   }
635 
636   if ((c = customdata_compare(&me1->edata, &me2->edata, me1, me2, thresh))) {
637     return cmpcode_to_str(c);
638   }
639 
640   if ((c = customdata_compare(&me1->ldata, &me2->ldata, me1, me2, thresh))) {
641     return cmpcode_to_str(c);
642   }
643 
644   if ((c = customdata_compare(&me1->pdata, &me2->pdata, me1, me2, thresh))) {
645     return cmpcode_to_str(c);
646   }
647 
648   return NULL;
649 }
650 
mesh_ensure_tessellation_customdata(Mesh * me)651 static void mesh_ensure_tessellation_customdata(Mesh *me)
652 {
653   if (UNLIKELY((me->totface != 0) && (me->totpoly == 0))) {
654     /* Pass, otherwise this function  clears 'mface' before
655      * versioning 'mface -> mpoly' code kicks in T30583.
656      *
657      * Callers could also check but safer to do here - campbell */
658   }
659   else {
660     const int tottex_original = CustomData_number_of_layers(&me->ldata, CD_MLOOPUV);
661     const int totcol_original = CustomData_number_of_layers(&me->ldata, CD_MLOOPCOL);
662 
663     const int tottex_tessface = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
664     const int totcol_tessface = CustomData_number_of_layers(&me->fdata, CD_MCOL);
665 
666     if (tottex_tessface != tottex_original || totcol_tessface != totcol_original) {
667       BKE_mesh_tessface_clear(me);
668 
669       CustomData_from_bmeshpoly(&me->fdata, &me->ldata, me->totface);
670 
671       /* TODO - add some --debug-mesh option */
672       if (G.debug & G_DEBUG) {
673         /* note: this warning may be un-called for if we are initializing the mesh for the
674          * first time from bmesh, rather than giving a warning about this we could be smarter
675          * and check if there was any data to begin with, for now just print the warning with
676          * some info to help troubleshoot what's going on - campbell */
677         printf(
678             "%s: warning! Tessellation uvs or vcol data got out of sync, "
679             "had to reset!\n    CD_MTFACE: %d != CD_MLOOPUV: %d || CD_MCOL: %d != CD_MLOOPCOL: "
680             "%d\n",
681             __func__,
682             tottex_tessface,
683             tottex_original,
684             totcol_tessface,
685             totcol_original);
686       }
687     }
688   }
689 }
690 
BKE_mesh_ensure_skin_customdata(Mesh * me)691 void BKE_mesh_ensure_skin_customdata(Mesh *me)
692 {
693   BMesh *bm = me->edit_mesh ? me->edit_mesh->bm : NULL;
694   MVertSkin *vs;
695 
696   if (bm) {
697     if (!CustomData_has_layer(&bm->vdata, CD_MVERT_SKIN)) {
698       BMVert *v;
699       BMIter iter;
700 
701       BM_data_layer_add(bm, &bm->vdata, CD_MVERT_SKIN);
702 
703       /* Mark an arbitrary vertex as root */
704       BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
705         vs = CustomData_bmesh_get(&bm->vdata, v->head.data, CD_MVERT_SKIN);
706         vs->flag |= MVERT_SKIN_ROOT;
707         break;
708       }
709     }
710   }
711   else {
712     if (!CustomData_has_layer(&me->vdata, CD_MVERT_SKIN)) {
713       vs = CustomData_add_layer(&me->vdata, CD_MVERT_SKIN, CD_DEFAULT, NULL, me->totvert);
714 
715       /* Mark an arbitrary vertex as root */
716       if (vs) {
717         vs->flag |= MVERT_SKIN_ROOT;
718       }
719     }
720   }
721 }
722 
BKE_mesh_ensure_facemap_customdata(struct Mesh * me)723 bool BKE_mesh_ensure_facemap_customdata(struct Mesh *me)
724 {
725   BMesh *bm = me->edit_mesh ? me->edit_mesh->bm : NULL;
726   bool changed = false;
727   if (bm) {
728     if (!CustomData_has_layer(&bm->pdata, CD_FACEMAP)) {
729       BM_data_layer_add(bm, &bm->pdata, CD_FACEMAP);
730       changed = true;
731     }
732   }
733   else {
734     if (!CustomData_has_layer(&me->pdata, CD_FACEMAP)) {
735       CustomData_add_layer(&me->pdata, CD_FACEMAP, CD_DEFAULT, NULL, me->totpoly);
736       changed = true;
737     }
738   }
739   return changed;
740 }
741 
BKE_mesh_clear_facemap_customdata(struct Mesh * me)742 bool BKE_mesh_clear_facemap_customdata(struct Mesh *me)
743 {
744   BMesh *bm = me->edit_mesh ? me->edit_mesh->bm : NULL;
745   bool changed = false;
746   if (bm) {
747     if (CustomData_has_layer(&bm->pdata, CD_FACEMAP)) {
748       BM_data_layer_free(bm, &bm->pdata, CD_FACEMAP);
749       changed = true;
750     }
751   }
752   else {
753     if (CustomData_has_layer(&me->pdata, CD_FACEMAP)) {
754       CustomData_free_layers(&me->pdata, CD_FACEMAP, me->totpoly);
755       changed = true;
756     }
757   }
758   return changed;
759 }
760 
761 /* this ensures grouped customdata (e.g. mtexpoly and mloopuv and mtface, or
762  * mloopcol and mcol) have the same relative active/render/clone/mask indices.
763  *
764  * note that for undo mesh data we want to skip 'ensure_tess_cd' call since
765  * we don't want to store memory for tessface when its only used for older
766  * versions of the mesh. - campbell*/
mesh_update_linked_customdata(Mesh * me,const bool do_ensure_tess_cd)767 static void mesh_update_linked_customdata(Mesh *me, const bool do_ensure_tess_cd)
768 {
769   if (do_ensure_tess_cd) {
770     mesh_ensure_tessellation_customdata(me);
771   }
772 
773   CustomData_bmesh_update_active_layers(&me->fdata, &me->ldata);
774 }
775 
BKE_mesh_update_customdata_pointers(Mesh * me,const bool do_ensure_tess_cd)776 void BKE_mesh_update_customdata_pointers(Mesh *me, const bool do_ensure_tess_cd)
777 {
778   mesh_update_linked_customdata(me, do_ensure_tess_cd);
779 
780   me->mvert = CustomData_get_layer(&me->vdata, CD_MVERT);
781   me->dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT);
782 
783   me->medge = CustomData_get_layer(&me->edata, CD_MEDGE);
784 
785   me->mface = CustomData_get_layer(&me->fdata, CD_MFACE);
786   me->mcol = CustomData_get_layer(&me->fdata, CD_MCOL);
787   me->mtface = CustomData_get_layer(&me->fdata, CD_MTFACE);
788 
789   me->mpoly = CustomData_get_layer(&me->pdata, CD_MPOLY);
790   me->mloop = CustomData_get_layer(&me->ldata, CD_MLOOP);
791 
792   me->mloopcol = CustomData_get_layer(&me->ldata, CD_MLOOPCOL);
793   me->mloopuv = CustomData_get_layer(&me->ldata, CD_MLOOPUV);
794 }
795 
BKE_mesh_has_custom_loop_normals(Mesh * me)796 bool BKE_mesh_has_custom_loop_normals(Mesh *me)
797 {
798   if (me->edit_mesh) {
799     return CustomData_has_layer(&me->edit_mesh->bm->ldata, CD_CUSTOMLOOPNORMAL);
800   }
801 
802   return CustomData_has_layer(&me->ldata, CD_CUSTOMLOOPNORMAL);
803 }
804 
805 /** Free (or release) any data used by this mesh (does not free the mesh itself). */
BKE_mesh_free(Mesh * me)806 void BKE_mesh_free(Mesh *me)
807 {
808   mesh_free_data(&me->id);
809 }
810 
mesh_clear_geometry(Mesh * mesh)811 static void mesh_clear_geometry(Mesh *mesh)
812 {
813   CustomData_free(&mesh->vdata, mesh->totvert);
814   CustomData_free(&mesh->edata, mesh->totedge);
815   CustomData_free(&mesh->fdata, mesh->totface);
816   CustomData_free(&mesh->ldata, mesh->totloop);
817   CustomData_free(&mesh->pdata, mesh->totpoly);
818 
819   MEM_SAFE_FREE(mesh->mselect);
820   MEM_SAFE_FREE(mesh->edit_mesh);
821 
822   /* Note that materials and shape keys are not freed here. This is intentional, as freeing
823    * shape keys requires tagging the depsgraph for updated relations, which is expensive.
824    * Material slots should be kept in sync with the object.*/
825 
826   mesh->totvert = 0;
827   mesh->totedge = 0;
828   mesh->totface = 0;
829   mesh->totloop = 0;
830   mesh->totpoly = 0;
831   mesh->act_face = -1;
832   mesh->totselect = 0;
833 
834   BKE_mesh_update_customdata_pointers(mesh, false);
835 }
836 
BKE_mesh_clear_geometry(Mesh * mesh)837 void BKE_mesh_clear_geometry(Mesh *mesh)
838 {
839   BKE_animdata_free(&mesh->id, false);
840   BKE_mesh_runtime_clear_cache(mesh);
841   mesh_clear_geometry(mesh);
842 }
843 
mesh_tessface_clear_intern(Mesh * mesh,int free_customdata)844 static void mesh_tessface_clear_intern(Mesh *mesh, int free_customdata)
845 {
846   if (free_customdata) {
847     CustomData_free(&mesh->fdata, mesh->totface);
848   }
849   else {
850     CustomData_reset(&mesh->fdata);
851   }
852 
853   mesh->mface = NULL;
854   mesh->mtface = NULL;
855   mesh->mcol = NULL;
856   mesh->totface = 0;
857 }
858 
BKE_mesh_add(Main * bmain,const char * name)859 Mesh *BKE_mesh_add(Main *bmain, const char *name)
860 {
861   Mesh *me;
862 
863   me = BKE_id_new(bmain, ID_ME, name);
864 
865   return me;
866 }
867 
868 /* Custom data layer functions; those assume that totXXX are set correctly. */
mesh_ensure_cdlayers_primary(Mesh * mesh,bool do_tessface)869 static void mesh_ensure_cdlayers_primary(Mesh *mesh, bool do_tessface)
870 {
871   if (!CustomData_get_layer(&mesh->vdata, CD_MVERT)) {
872     CustomData_add_layer(&mesh->vdata, CD_MVERT, CD_CALLOC, NULL, mesh->totvert);
873   }
874   if (!CustomData_get_layer(&mesh->edata, CD_MEDGE)) {
875     CustomData_add_layer(&mesh->edata, CD_MEDGE, CD_CALLOC, NULL, mesh->totedge);
876   }
877   if (!CustomData_get_layer(&mesh->ldata, CD_MLOOP)) {
878     CustomData_add_layer(&mesh->ldata, CD_MLOOP, CD_CALLOC, NULL, mesh->totloop);
879   }
880   if (!CustomData_get_layer(&mesh->pdata, CD_MPOLY)) {
881     CustomData_add_layer(&mesh->pdata, CD_MPOLY, CD_CALLOC, NULL, mesh->totpoly);
882   }
883 
884   if (do_tessface && !CustomData_get_layer(&mesh->fdata, CD_MFACE)) {
885     CustomData_add_layer(&mesh->fdata, CD_MFACE, CD_CALLOC, NULL, mesh->totface);
886   }
887 }
888 
BKE_mesh_new_nomain(int verts_len,int edges_len,int tessface_len,int loops_len,int polys_len)889 Mesh *BKE_mesh_new_nomain(
890     int verts_len, int edges_len, int tessface_len, int loops_len, int polys_len)
891 {
892   Mesh *mesh = BKE_libblock_alloc(
893       NULL, ID_ME, BKE_idtype_idcode_to_name(ID_ME), LIB_ID_CREATE_LOCALIZE);
894   BKE_libblock_init_empty(&mesh->id);
895 
896   /* don't use CustomData_reset(...); because we dont want to touch customdata */
897   copy_vn_i(mesh->vdata.typemap, CD_NUMTYPES, -1);
898   copy_vn_i(mesh->edata.typemap, CD_NUMTYPES, -1);
899   copy_vn_i(mesh->fdata.typemap, CD_NUMTYPES, -1);
900   copy_vn_i(mesh->ldata.typemap, CD_NUMTYPES, -1);
901   copy_vn_i(mesh->pdata.typemap, CD_NUMTYPES, -1);
902 
903   mesh->totvert = verts_len;
904   mesh->totedge = edges_len;
905   mesh->totface = tessface_len;
906   mesh->totloop = loops_len;
907   mesh->totpoly = polys_len;
908 
909   mesh_ensure_cdlayers_primary(mesh, true);
910   BKE_mesh_update_customdata_pointers(mesh, false);
911 
912   return mesh;
913 }
914 
915 /* Copy user editable settings that we want to preserve through the modifier stack
916  * or operations where a mesh with new topology is created based on another mesh. */
BKE_mesh_copy_settings(Mesh * me_dst,const Mesh * me_src)917 void BKE_mesh_copy_settings(Mesh *me_dst, const Mesh *me_src)
918 {
919   /* Copy general settings. */
920   me_dst->editflag = me_src->editflag;
921   me_dst->flag = me_src->flag;
922   me_dst->smoothresh = me_src->smoothresh;
923   me_dst->remesh_voxel_size = me_src->remesh_voxel_size;
924   me_dst->remesh_voxel_adaptivity = me_src->remesh_voxel_adaptivity;
925   me_dst->remesh_mode = me_src->remesh_mode;
926   me_dst->symmetry = me_src->symmetry;
927 
928   me_dst->face_sets_color_seed = me_src->face_sets_color_seed;
929   me_dst->face_sets_color_default = me_src->face_sets_color_default;
930 
931   /* Copy texture space. */
932   me_dst->texflag = me_src->texflag;
933   copy_v3_v3(me_dst->loc, me_src->loc);
934   copy_v3_v3(me_dst->size, me_src->size);
935 
936   /* Copy materials. */
937   if (me_dst->mat != NULL) {
938     MEM_freeN(me_dst->mat);
939   }
940   me_dst->mat = MEM_dupallocN(me_src->mat);
941   me_dst->totcol = me_src->totcol;
942 }
943 
BKE_mesh_new_nomain_from_template_ex(const Mesh * me_src,int verts_len,int edges_len,int tessface_len,int loops_len,int polys_len,CustomData_MeshMasks mask)944 Mesh *BKE_mesh_new_nomain_from_template_ex(const Mesh *me_src,
945                                            int verts_len,
946                                            int edges_len,
947                                            int tessface_len,
948                                            int loops_len,
949                                            int polys_len,
950                                            CustomData_MeshMasks mask)
951 {
952   /* Only do tessface if we are creating tessfaces or copying from mesh with only tessfaces. */
953   const bool do_tessface = (tessface_len || ((me_src->totface != 0) && (me_src->totpoly == 0)));
954 
955   Mesh *me_dst = BKE_id_new_nomain(ID_ME, NULL);
956 
957   me_dst->mselect = MEM_dupallocN(me_dst->mselect);
958 
959   me_dst->totvert = verts_len;
960   me_dst->totedge = edges_len;
961   me_dst->totface = tessface_len;
962   me_dst->totloop = loops_len;
963   me_dst->totpoly = polys_len;
964 
965   me_dst->cd_flag = me_src->cd_flag;
966   BKE_mesh_copy_settings(me_dst, me_src);
967 
968   CustomData_copy(&me_src->vdata, &me_dst->vdata, mask.vmask, CD_CALLOC, verts_len);
969   CustomData_copy(&me_src->edata, &me_dst->edata, mask.emask, CD_CALLOC, edges_len);
970   CustomData_copy(&me_src->ldata, &me_dst->ldata, mask.lmask, CD_CALLOC, loops_len);
971   CustomData_copy(&me_src->pdata, &me_dst->pdata, mask.pmask, CD_CALLOC, polys_len);
972   if (do_tessface) {
973     CustomData_copy(&me_src->fdata, &me_dst->fdata, mask.fmask, CD_CALLOC, tessface_len);
974   }
975   else {
976     mesh_tessface_clear_intern(me_dst, false);
977   }
978 
979   /* The destination mesh should at least have valid primary CD layers,
980    * even in cases where the source mesh does not. */
981   mesh_ensure_cdlayers_primary(me_dst, do_tessface);
982   BKE_mesh_update_customdata_pointers(me_dst, false);
983 
984   return me_dst;
985 }
986 
BKE_mesh_new_nomain_from_template(const Mesh * me_src,int verts_len,int edges_len,int tessface_len,int loops_len,int polys_len)987 Mesh *BKE_mesh_new_nomain_from_template(const Mesh *me_src,
988                                         int verts_len,
989                                         int edges_len,
990                                         int tessface_len,
991                                         int loops_len,
992                                         int polys_len)
993 {
994   return BKE_mesh_new_nomain_from_template_ex(
995       me_src, verts_len, edges_len, tessface_len, loops_len, polys_len, CD_MASK_EVERYTHING);
996 }
997 
BKE_mesh_eval_delete(struct Mesh * mesh_eval)998 void BKE_mesh_eval_delete(struct Mesh *mesh_eval)
999 {
1000   /* Evaluated mesh may point to edit mesh, but never owns it. */
1001   mesh_eval->edit_mesh = NULL;
1002   BKE_mesh_free(mesh_eval);
1003   BKE_libblock_free_data(&mesh_eval->id, false);
1004   MEM_freeN(mesh_eval);
1005 }
1006 
BKE_mesh_copy_for_eval(struct Mesh * source,bool reference)1007 Mesh *BKE_mesh_copy_for_eval(struct Mesh *source, bool reference)
1008 {
1009   int flags = LIB_ID_COPY_LOCALIZE;
1010 
1011   if (reference) {
1012     flags |= LIB_ID_COPY_CD_REFERENCE;
1013   }
1014 
1015   Mesh *result = (Mesh *)BKE_id_copy_ex(NULL, &source->id, NULL, flags);
1016   return result;
1017 }
1018 
BKE_mesh_to_bmesh_ex(const Mesh * me,const struct BMeshCreateParams * create_params,const struct BMeshFromMeshParams * convert_params)1019 BMesh *BKE_mesh_to_bmesh_ex(const Mesh *me,
1020                             const struct BMeshCreateParams *create_params,
1021                             const struct BMeshFromMeshParams *convert_params)
1022 {
1023   BMesh *bm;
1024   const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_ME(me);
1025 
1026   bm = BM_mesh_create(&allocsize, create_params);
1027   BM_mesh_bm_from_me(bm, me, convert_params);
1028 
1029   return bm;
1030 }
1031 
BKE_mesh_to_bmesh(Mesh * me,Object * ob,const bool add_key_index,const struct BMeshCreateParams * params)1032 BMesh *BKE_mesh_to_bmesh(Mesh *me,
1033                          Object *ob,
1034                          const bool add_key_index,
1035                          const struct BMeshCreateParams *params)
1036 {
1037   return BKE_mesh_to_bmesh_ex(me,
1038                               params,
1039                               &(struct BMeshFromMeshParams){
1040                                   .calc_face_normal = false,
1041                                   .add_key_index = add_key_index,
1042                                   .use_shapekey = true,
1043                                   .active_shapekey = ob->shapenr,
1044                               });
1045 }
1046 
BKE_mesh_from_bmesh_nomain(BMesh * bm,const struct BMeshToMeshParams * params,const Mesh * me_settings)1047 Mesh *BKE_mesh_from_bmesh_nomain(BMesh *bm,
1048                                  const struct BMeshToMeshParams *params,
1049                                  const Mesh *me_settings)
1050 {
1051   BLI_assert(params->calc_object_remap == false);
1052   Mesh *mesh = BKE_id_new_nomain(ID_ME, NULL);
1053   BM_mesh_bm_to_me(NULL, bm, mesh, params);
1054   BKE_mesh_copy_settings(mesh, me_settings);
1055   return mesh;
1056 }
1057 
BKE_mesh_from_bmesh_for_eval_nomain(BMesh * bm,const CustomData_MeshMasks * cd_mask_extra,const Mesh * me_settings)1058 Mesh *BKE_mesh_from_bmesh_for_eval_nomain(BMesh *bm,
1059                                           const CustomData_MeshMasks *cd_mask_extra,
1060                                           const Mesh *me_settings)
1061 {
1062   Mesh *mesh = BKE_id_new_nomain(ID_ME, NULL);
1063   BM_mesh_bm_to_me_for_eval(bm, mesh, cd_mask_extra);
1064   BKE_mesh_copy_settings(mesh, me_settings);
1065   return mesh;
1066 }
1067 
BKE_mesh_boundbox_get(Object * ob)1068 BoundBox *BKE_mesh_boundbox_get(Object *ob)
1069 {
1070   /* This is Object-level data access,
1071    * DO NOT touch to Mesh's bb, would be totally thread-unsafe. */
1072   if (ob->runtime.bb == NULL || ob->runtime.bb->flag & BOUNDBOX_DIRTY) {
1073     Mesh *me = ob->data;
1074     float min[3], max[3];
1075 
1076     INIT_MINMAX(min, max);
1077     if (!BKE_mesh_wrapper_minmax(me, min, max)) {
1078       min[0] = min[1] = min[2] = -1.0f;
1079       max[0] = max[1] = max[2] = 1.0f;
1080     }
1081 
1082     if (ob->runtime.bb == NULL) {
1083       ob->runtime.bb = MEM_mallocN(sizeof(*ob->runtime.bb), __func__);
1084     }
1085     BKE_boundbox_init_from_minmax(ob->runtime.bb, min, max);
1086     ob->runtime.bb->flag &= ~BOUNDBOX_DIRTY;
1087   }
1088 
1089   return ob->runtime.bb;
1090 }
1091 
BKE_mesh_texspace_calc(Mesh * me)1092 void BKE_mesh_texspace_calc(Mesh *me)
1093 {
1094   if (me->texflag & ME_AUTOSPACE) {
1095     float min[3], max[3];
1096 
1097     INIT_MINMAX(min, max);
1098     if (!BKE_mesh_wrapper_minmax(me, min, max)) {
1099       min[0] = min[1] = min[2] = -1.0f;
1100       max[0] = max[1] = max[2] = 1.0f;
1101     }
1102 
1103     float loc[3], size[3];
1104     mid_v3_v3v3(loc, min, max);
1105 
1106     size[0] = (max[0] - min[0]) / 2.0f;
1107     size[1] = (max[1] - min[1]) / 2.0f;
1108     size[2] = (max[2] - min[2]) / 2.0f;
1109 
1110     for (int a = 0; a < 3; a++) {
1111       if (size[a] == 0.0f) {
1112         size[a] = 1.0f;
1113       }
1114       else if (size[a] > 0.0f && size[a] < 0.00001f) {
1115         size[a] = 0.00001f;
1116       }
1117       else if (size[a] < 0.0f && size[a] > -0.00001f) {
1118         size[a] = -0.00001f;
1119       }
1120     }
1121 
1122     copy_v3_v3(me->loc, loc);
1123     copy_v3_v3(me->size, size);
1124 
1125     me->texflag |= ME_AUTOSPACE_EVALUATED;
1126   }
1127 }
1128 
BKE_mesh_texspace_ensure(Mesh * me)1129 void BKE_mesh_texspace_ensure(Mesh *me)
1130 {
1131   if ((me->texflag & ME_AUTOSPACE) && !(me->texflag & ME_AUTOSPACE_EVALUATED)) {
1132     BKE_mesh_texspace_calc(me);
1133   }
1134 }
1135 
BKE_mesh_texspace_get(Mesh * me,float r_loc[3],float r_size[3])1136 void BKE_mesh_texspace_get(Mesh *me, float r_loc[3], float r_size[3])
1137 {
1138   BKE_mesh_texspace_ensure(me);
1139 
1140   if (r_loc) {
1141     copy_v3_v3(r_loc, me->loc);
1142   }
1143   if (r_size) {
1144     copy_v3_v3(r_size, me->size);
1145   }
1146 }
1147 
BKE_mesh_texspace_get_reference(Mesh * me,short ** r_texflag,float ** r_loc,float ** r_size)1148 void BKE_mesh_texspace_get_reference(Mesh *me, short **r_texflag, float **r_loc, float **r_size)
1149 {
1150   BKE_mesh_texspace_ensure(me);
1151 
1152   if (r_texflag != NULL) {
1153     *r_texflag = &me->texflag;
1154   }
1155   if (r_loc != NULL) {
1156     *r_loc = me->loc;
1157   }
1158   if (r_size != NULL) {
1159     *r_size = me->size;
1160   }
1161 }
1162 
BKE_mesh_texspace_copy_from_object(Mesh * me,Object * ob)1163 void BKE_mesh_texspace_copy_from_object(Mesh *me, Object *ob)
1164 {
1165   float *texloc, *texsize;
1166   short *texflag;
1167 
1168   if (BKE_object_obdata_texspace_get(ob, &texflag, &texloc, &texsize)) {
1169     me->texflag = *texflag;
1170     copy_v3_v3(me->loc, texloc);
1171     copy_v3_v3(me->size, texsize);
1172   }
1173 }
1174 
BKE_mesh_orco_verts_get(Object * ob)1175 float (*BKE_mesh_orco_verts_get(Object *ob))[3]
1176 {
1177   Mesh *me = ob->data;
1178   MVert *mvert = NULL;
1179   Mesh *tme = me->texcomesh ? me->texcomesh : me;
1180   int a, totvert;
1181   float(*vcos)[3] = NULL;
1182 
1183   /* Get appropriate vertex coordinates */
1184   vcos = MEM_calloc_arrayN(me->totvert, sizeof(*vcos), "orco mesh");
1185   mvert = tme->mvert;
1186   totvert = min_ii(tme->totvert, me->totvert);
1187 
1188   for (a = 0; a < totvert; a++, mvert++) {
1189     copy_v3_v3(vcos[a], mvert->co);
1190   }
1191 
1192   return vcos;
1193 }
1194 
BKE_mesh_orco_verts_transform(Mesh * me,float (* orco)[3],int totvert,int invert)1195 void BKE_mesh_orco_verts_transform(Mesh *me, float (*orco)[3], int totvert, int invert)
1196 {
1197   float loc[3], size[3];
1198   int a;
1199 
1200   BKE_mesh_texspace_get(me->texcomesh ? me->texcomesh : me, loc, size);
1201 
1202   if (invert) {
1203     for (a = 0; a < totvert; a++) {
1204       float *co = orco[a];
1205       madd_v3_v3v3v3(co, loc, co, size);
1206     }
1207   }
1208   else {
1209     for (a = 0; a < totvert; a++) {
1210       float *co = orco[a];
1211       co[0] = (co[0] - loc[0]) / size[0];
1212       co[1] = (co[1] - loc[1]) / size[1];
1213       co[2] = (co[2] - loc[2]) / size[2];
1214     }
1215   }
1216 }
1217 
1218 /* rotates the vertices of a face in case v[2] or v[3] (vertex index) is = 0.
1219  * this is necessary to make the if (mface->v4) check for quads work */
test_index_face(MFace * mface,CustomData * fdata,int mfindex,int nr)1220 int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
1221 {
1222   /* first test if the face is legal */
1223   if ((mface->v3 || nr == 4) && mface->v3 == mface->v4) {
1224     mface->v4 = 0;
1225     nr--;
1226   }
1227   if ((mface->v2 || mface->v4) && mface->v2 == mface->v3) {
1228     mface->v3 = mface->v4;
1229     mface->v4 = 0;
1230     nr--;
1231   }
1232   if (mface->v1 == mface->v2) {
1233     mface->v2 = mface->v3;
1234     mface->v3 = mface->v4;
1235     mface->v4 = 0;
1236     nr--;
1237   }
1238 
1239   /* Check corrupt cases, bow-tie geometry,
1240    * cant handle these because edge data wont exist so just return 0. */
1241   if (nr == 3) {
1242     if (
1243         /* real edges */
1244         mface->v1 == mface->v2 || mface->v2 == mface->v3 || mface->v3 == mface->v1) {
1245       return 0;
1246     }
1247   }
1248   else if (nr == 4) {
1249     if (
1250         /* real edges */
1251         mface->v1 == mface->v2 || mface->v2 == mface->v3 || mface->v3 == mface->v4 ||
1252         mface->v4 == mface->v1 ||
1253         /* across the face */
1254         mface->v1 == mface->v3 || mface->v2 == mface->v4) {
1255       return 0;
1256     }
1257   }
1258 
1259   /* prevent a zero at wrong index location */
1260   if (nr == 3) {
1261     if (mface->v3 == 0) {
1262       static int corner_indices[4] = {1, 2, 0, 3};
1263 
1264       SWAP(unsigned int, mface->v1, mface->v2);
1265       SWAP(unsigned int, mface->v2, mface->v3);
1266 
1267       if (fdata) {
1268         CustomData_swap_corners(fdata, mfindex, corner_indices);
1269       }
1270     }
1271   }
1272   else if (nr == 4) {
1273     if (mface->v3 == 0 || mface->v4 == 0) {
1274       static int corner_indices[4] = {2, 3, 0, 1};
1275 
1276       SWAP(unsigned int, mface->v1, mface->v3);
1277       SWAP(unsigned int, mface->v2, mface->v4);
1278 
1279       if (fdata) {
1280         CustomData_swap_corners(fdata, mfindex, corner_indices);
1281       }
1282     }
1283   }
1284 
1285   return nr;
1286 }
1287 
BKE_mesh_from_object(Object * ob)1288 Mesh *BKE_mesh_from_object(Object *ob)
1289 {
1290 
1291   if (ob == NULL) {
1292     return NULL;
1293   }
1294   if (ob->type == OB_MESH) {
1295     return ob->data;
1296   }
1297 
1298   return NULL;
1299 }
1300 
BKE_mesh_assign_object(Main * bmain,Object * ob,Mesh * me)1301 void BKE_mesh_assign_object(Main *bmain, Object *ob, Mesh *me)
1302 {
1303   Mesh *old = NULL;
1304 
1305   if (ob == NULL) {
1306     return;
1307   }
1308 
1309   multires_force_sculpt_rebuild(ob);
1310 
1311   if (ob->type == OB_MESH) {
1312     old = ob->data;
1313     if (old) {
1314       id_us_min(&old->id);
1315     }
1316     ob->data = me;
1317     id_us_plus((ID *)me);
1318   }
1319 
1320   BKE_object_materials_test(bmain, ob, (ID *)me);
1321 
1322   BKE_modifiers_test_object(ob);
1323 }
1324 
BKE_mesh_material_index_remove(Mesh * me,short index)1325 void BKE_mesh_material_index_remove(Mesh *me, short index)
1326 {
1327   MPoly *mp;
1328   MFace *mf;
1329   int i;
1330 
1331   for (mp = me->mpoly, i = 0; i < me->totpoly; i++, mp++) {
1332     if (mp->mat_nr && mp->mat_nr >= index) {
1333       mp->mat_nr--;
1334     }
1335   }
1336 
1337   for (mf = me->mface, i = 0; i < me->totface; i++, mf++) {
1338     if (mf->mat_nr && mf->mat_nr >= index) {
1339       mf->mat_nr--;
1340     }
1341   }
1342 }
1343 
BKE_mesh_material_index_used(Mesh * me,short index)1344 bool BKE_mesh_material_index_used(Mesh *me, short index)
1345 {
1346   MPoly *mp;
1347   MFace *mf;
1348   int i;
1349 
1350   for (mp = me->mpoly, i = 0; i < me->totpoly; i++, mp++) {
1351     if (mp->mat_nr == index) {
1352       return true;
1353     }
1354   }
1355 
1356   for (mf = me->mface, i = 0; i < me->totface; i++, mf++) {
1357     if (mf->mat_nr == index) {
1358       return true;
1359     }
1360   }
1361 
1362   return false;
1363 }
1364 
BKE_mesh_material_index_clear(Mesh * me)1365 void BKE_mesh_material_index_clear(Mesh *me)
1366 {
1367   MPoly *mp;
1368   MFace *mf;
1369   int i;
1370 
1371   for (mp = me->mpoly, i = 0; i < me->totpoly; i++, mp++) {
1372     mp->mat_nr = 0;
1373   }
1374 
1375   for (mf = me->mface, i = 0; i < me->totface; i++, mf++) {
1376     mf->mat_nr = 0;
1377   }
1378 }
1379 
BKE_mesh_material_remap(Mesh * me,const unsigned int * remap,unsigned int remap_len)1380 void BKE_mesh_material_remap(Mesh *me, const unsigned int *remap, unsigned int remap_len)
1381 {
1382   const short remap_len_short = (short)remap_len;
1383 
1384 #define MAT_NR_REMAP(n) \
1385   if (n < remap_len_short) { \
1386     BLI_assert(n >= 0 && remap[n] < remap_len_short); \
1387     n = remap[n]; \
1388   } \
1389   ((void)0)
1390 
1391   if (me->edit_mesh) {
1392     BMEditMesh *em = me->edit_mesh;
1393     BMIter iter;
1394     BMFace *efa;
1395 
1396     BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1397       MAT_NR_REMAP(efa->mat_nr);
1398     }
1399   }
1400   else {
1401     int i;
1402     for (i = 0; i < me->totpoly; i++) {
1403       MAT_NR_REMAP(me->mpoly[i].mat_nr);
1404     }
1405   }
1406 
1407 #undef MAT_NR_REMAP
1408 }
1409 
BKE_mesh_smooth_flag_set(Mesh * me,const bool use_smooth)1410 void BKE_mesh_smooth_flag_set(Mesh *me, const bool use_smooth)
1411 {
1412   if (use_smooth) {
1413     for (int i = 0; i < me->totpoly; i++) {
1414       me->mpoly[i].flag |= ME_SMOOTH;
1415     }
1416   }
1417   else {
1418     for (int i = 0; i < me->totpoly; i++) {
1419       me->mpoly[i].flag &= ~ME_SMOOTH;
1420     }
1421   }
1422 }
1423 
1424 /**
1425  * Find the index of the loop in 'poly' which references vertex,
1426  * returns -1 if not found
1427  */
poly_find_loop_from_vert(const MPoly * poly,const MLoop * loopstart,uint vert)1428 int poly_find_loop_from_vert(const MPoly *poly, const MLoop *loopstart, uint vert)
1429 {
1430   int j;
1431   for (j = 0; j < poly->totloop; j++, loopstart++) {
1432     if (loopstart->v == vert) {
1433       return j;
1434     }
1435   }
1436 
1437   return -1;
1438 }
1439 
1440 /**
1441  * Fill \a r_adj with the loop indices in \a poly adjacent to the
1442  * vertex. Returns the index of the loop matching vertex, or -1 if the
1443  * vertex is not in \a poly
1444  */
poly_get_adj_loops_from_vert(const MPoly * poly,const MLoop * mloop,unsigned int vert,unsigned int r_adj[2])1445 int poly_get_adj_loops_from_vert(const MPoly *poly,
1446                                  const MLoop *mloop,
1447                                  unsigned int vert,
1448                                  unsigned int r_adj[2])
1449 {
1450   int corner = poly_find_loop_from_vert(poly, &mloop[poly->loopstart], vert);
1451 
1452   if (corner != -1) {
1453     /* vertex was found */
1454     r_adj[0] = ME_POLY_LOOP_PREV(mloop, poly, corner)->v;
1455     r_adj[1] = ME_POLY_LOOP_NEXT(mloop, poly, corner)->v;
1456   }
1457 
1458   return corner;
1459 }
1460 
1461 /**
1462  * Return the index of the edge vert that is not equal to \a v. If
1463  * neither edge vertex is equal to \a v, returns -1.
1464  */
BKE_mesh_edge_other_vert(const MEdge * e,int v)1465 int BKE_mesh_edge_other_vert(const MEdge *e, int v)
1466 {
1467   if (e->v1 == v) {
1468     return e->v2;
1469   }
1470   if (e->v2 == v) {
1471     return e->v1;
1472   }
1473 
1474   return -1;
1475 }
1476 
1477 /**
1478  * Sets each output array element to the edge index if it is a real edge, or -1.
1479  */
BKE_mesh_looptri_get_real_edges(const Mesh * mesh,const MLoopTri * looptri,int r_edges[3])1480 void BKE_mesh_looptri_get_real_edges(const Mesh *mesh, const MLoopTri *looptri, int r_edges[3])
1481 {
1482   for (int i = 2, i_next = 0; i_next < 3; i = i_next++) {
1483     const MLoop *l1 = &mesh->mloop[looptri->tri[i]], *l2 = &mesh->mloop[looptri->tri[i_next]];
1484     const MEdge *e = &mesh->medge[l1->e];
1485 
1486     bool is_real = (l1->v == e->v1 && l2->v == e->v2) || (l1->v == e->v2 && l2->v == e->v1);
1487 
1488     r_edges[i] = is_real ? l1->e : -1;
1489   }
1490 }
1491 
1492 /* basic vertex data functions */
BKE_mesh_minmax(const Mesh * me,float r_min[3],float r_max[3])1493 bool BKE_mesh_minmax(const Mesh *me, float r_min[3], float r_max[3])
1494 {
1495   int i = me->totvert;
1496   MVert *mvert;
1497   for (mvert = me->mvert; i--; mvert++) {
1498     minmax_v3v3_v3(r_min, r_max, mvert->co);
1499   }
1500 
1501   return (me->totvert != 0);
1502 }
1503 
BKE_mesh_transform(Mesh * me,const float mat[4][4],bool do_keys)1504 void BKE_mesh_transform(Mesh *me, const float mat[4][4], bool do_keys)
1505 {
1506   int i;
1507   MVert *mvert = CustomData_duplicate_referenced_layer(&me->vdata, CD_MVERT, me->totvert);
1508   float(*lnors)[3] = CustomData_duplicate_referenced_layer(&me->ldata, CD_NORMAL, me->totloop);
1509 
1510   /* If the referenced l;ayer has been re-allocated need to update pointers stored in the mesh. */
1511   BKE_mesh_update_customdata_pointers(me, false);
1512 
1513   for (i = 0; i < me->totvert; i++, mvert++) {
1514     mul_m4_v3(mat, mvert->co);
1515   }
1516 
1517   if (do_keys && me->key) {
1518     KeyBlock *kb;
1519     for (kb = me->key->block.first; kb; kb = kb->next) {
1520       float *fp = kb->data;
1521       for (i = kb->totelem; i--; fp += 3) {
1522         mul_m4_v3(mat, fp);
1523       }
1524     }
1525   }
1526 
1527   /* don't update normals, caller can do this explicitly.
1528    * We do update loop normals though, those may not be auto-generated
1529    * (see e.g. STL import script)! */
1530   if (lnors) {
1531     float m3[3][3];
1532 
1533     copy_m3_m4(m3, mat);
1534     normalize_m3(m3);
1535     for (i = 0; i < me->totloop; i++, lnors++) {
1536       mul_m3_v3(m3, *lnors);
1537     }
1538   }
1539 }
1540 
BKE_mesh_translate(Mesh * me,const float offset[3],const bool do_keys)1541 void BKE_mesh_translate(Mesh *me, const float offset[3], const bool do_keys)
1542 {
1543   int i = me->totvert;
1544   MVert *mvert;
1545   for (mvert = me->mvert; i--; mvert++) {
1546     add_v3_v3(mvert->co, offset);
1547   }
1548 
1549   if (do_keys && me->key) {
1550     KeyBlock *kb;
1551     for (kb = me->key->block.first; kb; kb = kb->next) {
1552       float *fp = kb->data;
1553       for (i = kb->totelem; i--; fp += 3) {
1554         add_v3_v3(fp, offset);
1555       }
1556     }
1557   }
1558 }
1559 
BKE_mesh_tessface_calc(Mesh * mesh)1560 void BKE_mesh_tessface_calc(Mesh *mesh)
1561 {
1562   mesh->totface = BKE_mesh_tessface_calc_ex(
1563       &mesh->fdata,
1564       &mesh->ldata,
1565       &mesh->pdata,
1566       mesh->mvert,
1567       mesh->totface,
1568       mesh->totloop,
1569       mesh->totpoly,
1570       /* calc normals right after, don't copy from polys here */
1571       false);
1572 
1573   BKE_mesh_update_customdata_pointers(mesh, true);
1574 }
1575 
BKE_mesh_tessface_ensure(Mesh * mesh)1576 void BKE_mesh_tessface_ensure(Mesh *mesh)
1577 {
1578   if (mesh->totpoly && mesh->totface == 0) {
1579     BKE_mesh_tessface_calc(mesh);
1580   }
1581 }
1582 
BKE_mesh_tessface_clear(Mesh * mesh)1583 void BKE_mesh_tessface_clear(Mesh *mesh)
1584 {
1585   mesh_tessface_clear_intern(mesh, true);
1586 }
1587 
BKE_mesh_do_versions_cd_flag_init(Mesh * mesh)1588 void BKE_mesh_do_versions_cd_flag_init(Mesh *mesh)
1589 {
1590   if (UNLIKELY(mesh->cd_flag)) {
1591     return;
1592   }
1593 
1594   MVert *mv;
1595   MEdge *med;
1596   int i;
1597 
1598   for (mv = mesh->mvert, i = 0; i < mesh->totvert; mv++, i++) {
1599     if (mv->bweight != 0) {
1600       mesh->cd_flag |= ME_CDFLAG_VERT_BWEIGHT;
1601       break;
1602     }
1603   }
1604 
1605   for (med = mesh->medge, i = 0; i < mesh->totedge; med++, i++) {
1606     if (med->bweight != 0) {
1607       mesh->cd_flag |= ME_CDFLAG_EDGE_BWEIGHT;
1608       if (mesh->cd_flag & ME_CDFLAG_EDGE_CREASE) {
1609         break;
1610       }
1611     }
1612     if (med->crease != 0) {
1613       mesh->cd_flag |= ME_CDFLAG_EDGE_CREASE;
1614       if (mesh->cd_flag & ME_CDFLAG_EDGE_BWEIGHT) {
1615         break;
1616       }
1617     }
1618   }
1619 }
1620 
1621 /* -------------------------------------------------------------------- */
1622 /* MSelect functions (currently used in weight paint mode) */
1623 
BKE_mesh_mselect_clear(Mesh * me)1624 void BKE_mesh_mselect_clear(Mesh *me)
1625 {
1626   if (me->mselect) {
1627     MEM_freeN(me->mselect);
1628     me->mselect = NULL;
1629   }
1630   me->totselect = 0;
1631 }
1632 
BKE_mesh_mselect_validate(Mesh * me)1633 void BKE_mesh_mselect_validate(Mesh *me)
1634 {
1635   MSelect *mselect_src, *mselect_dst;
1636   int i_src, i_dst;
1637 
1638   if (me->totselect == 0) {
1639     return;
1640   }
1641 
1642   mselect_src = me->mselect;
1643   mselect_dst = MEM_malloc_arrayN((me->totselect), sizeof(MSelect), "Mesh selection history");
1644 
1645   for (i_src = 0, i_dst = 0; i_src < me->totselect; i_src++) {
1646     int index = mselect_src[i_src].index;
1647     switch (mselect_src[i_src].type) {
1648       case ME_VSEL: {
1649         if (me->mvert[index].flag & SELECT) {
1650           mselect_dst[i_dst] = mselect_src[i_src];
1651           i_dst++;
1652         }
1653         break;
1654       }
1655       case ME_ESEL: {
1656         if (me->medge[index].flag & SELECT) {
1657           mselect_dst[i_dst] = mselect_src[i_src];
1658           i_dst++;
1659         }
1660         break;
1661       }
1662       case ME_FSEL: {
1663         if (me->mpoly[index].flag & SELECT) {
1664           mselect_dst[i_dst] = mselect_src[i_src];
1665           i_dst++;
1666         }
1667         break;
1668       }
1669       default: {
1670         BLI_assert(0);
1671         break;
1672       }
1673     }
1674   }
1675 
1676   MEM_freeN(mselect_src);
1677 
1678   if (i_dst == 0) {
1679     MEM_freeN(mselect_dst);
1680     mselect_dst = NULL;
1681   }
1682   else if (i_dst != me->totselect) {
1683     mselect_dst = MEM_reallocN(mselect_dst, sizeof(MSelect) * i_dst);
1684   }
1685 
1686   me->totselect = i_dst;
1687   me->mselect = mselect_dst;
1688 }
1689 
1690 /**
1691  * Return the index within me->mselect, or -1
1692  */
BKE_mesh_mselect_find(Mesh * me,int index,int type)1693 int BKE_mesh_mselect_find(Mesh *me, int index, int type)
1694 {
1695   int i;
1696 
1697   BLI_assert(ELEM(type, ME_VSEL, ME_ESEL, ME_FSEL));
1698 
1699   for (i = 0; i < me->totselect; i++) {
1700     if ((me->mselect[i].index == index) && (me->mselect[i].type == type)) {
1701       return i;
1702     }
1703   }
1704 
1705   return -1;
1706 }
1707 
1708 /**
1709  * Return The index of the active element.
1710  */
BKE_mesh_mselect_active_get(Mesh * me,int type)1711 int BKE_mesh_mselect_active_get(Mesh *me, int type)
1712 {
1713   BLI_assert(ELEM(type, ME_VSEL, ME_ESEL, ME_FSEL));
1714 
1715   if (me->totselect) {
1716     if (me->mselect[me->totselect - 1].type == type) {
1717       return me->mselect[me->totselect - 1].index;
1718     }
1719   }
1720   return -1;
1721 }
1722 
BKE_mesh_mselect_active_set(Mesh * me,int index,int type)1723 void BKE_mesh_mselect_active_set(Mesh *me, int index, int type)
1724 {
1725   const int msel_index = BKE_mesh_mselect_find(me, index, type);
1726 
1727   if (msel_index == -1) {
1728     /* add to the end */
1729     me->mselect = MEM_reallocN(me->mselect, sizeof(MSelect) * (me->totselect + 1));
1730     me->mselect[me->totselect].index = index;
1731     me->mselect[me->totselect].type = type;
1732     me->totselect++;
1733   }
1734   else if (msel_index != me->totselect - 1) {
1735     /* move to the end */
1736     SWAP(MSelect, me->mselect[msel_index], me->mselect[me->totselect - 1]);
1737   }
1738 
1739   BLI_assert((me->mselect[me->totselect - 1].index == index) &&
1740              (me->mselect[me->totselect - 1].type == type));
1741 }
1742 
BKE_mesh_count_selected_items(const Mesh * mesh,int r_count[3])1743 void BKE_mesh_count_selected_items(const Mesh *mesh, int r_count[3])
1744 {
1745   r_count[0] = r_count[1] = r_count[2] = 0;
1746   if (mesh->edit_mesh) {
1747     BMesh *bm = mesh->edit_mesh->bm;
1748     r_count[0] = bm->totvertsel;
1749     r_count[1] = bm->totedgesel;
1750     r_count[2] = bm->totfacesel;
1751   }
1752   /* We could support faces in paint modes. */
1753 }
1754 
BKE_mesh_vert_coords_get(const Mesh * mesh,float (* vert_coords)[3])1755 void BKE_mesh_vert_coords_get(const Mesh *mesh, float (*vert_coords)[3])
1756 {
1757   const MVert *mv = mesh->mvert;
1758   for (int i = 0; i < mesh->totvert; i++, mv++) {
1759     copy_v3_v3(vert_coords[i], mv->co);
1760   }
1761 }
1762 
BKE_mesh_vert_coords_alloc(const Mesh * mesh,int * r_vert_len)1763 float (*BKE_mesh_vert_coords_alloc(const Mesh *mesh, int *r_vert_len))[3]
1764 {
1765   float(*vert_coords)[3] = MEM_mallocN(sizeof(float[3]) * mesh->totvert, __func__);
1766   BKE_mesh_vert_coords_get(mesh, vert_coords);
1767   if (r_vert_len) {
1768     *r_vert_len = mesh->totvert;
1769   }
1770   return vert_coords;
1771 }
1772 
BKE_mesh_vert_coords_apply(Mesh * mesh,const float (* vert_coords)[3])1773 void BKE_mesh_vert_coords_apply(Mesh *mesh, const float (*vert_coords)[3])
1774 {
1775   /* This will just return the pointer if it wasn't a referenced layer. */
1776   MVert *mv = CustomData_duplicate_referenced_layer(&mesh->vdata, CD_MVERT, mesh->totvert);
1777   mesh->mvert = mv;
1778   for (int i = 0; i < mesh->totvert; i++, mv++) {
1779     copy_v3_v3(mv->co, vert_coords[i]);
1780   }
1781   mesh->runtime.cd_dirty_vert |= CD_MASK_NORMAL;
1782 }
1783 
BKE_mesh_vert_coords_apply_with_mat4(Mesh * mesh,const float (* vert_coords)[3],const float mat[4][4])1784 void BKE_mesh_vert_coords_apply_with_mat4(Mesh *mesh,
1785                                           const float (*vert_coords)[3],
1786                                           const float mat[4][4])
1787 {
1788   /* This will just return the pointer if it wasn't a referenced layer. */
1789   MVert *mv = CustomData_duplicate_referenced_layer(&mesh->vdata, CD_MVERT, mesh->totvert);
1790   mesh->mvert = mv;
1791   for (int i = 0; i < mesh->totvert; i++, mv++) {
1792     mul_v3_m4v3(mv->co, mat, vert_coords[i]);
1793   }
1794   mesh->runtime.cd_dirty_vert |= CD_MASK_NORMAL;
1795 }
1796 
BKE_mesh_vert_normals_apply(Mesh * mesh,const short (* vert_normals)[3])1797 void BKE_mesh_vert_normals_apply(Mesh *mesh, const short (*vert_normals)[3])
1798 {
1799   /* This will just return the pointer if it wasn't a referenced layer. */
1800   MVert *mv = CustomData_duplicate_referenced_layer(&mesh->vdata, CD_MVERT, mesh->totvert);
1801   mesh->mvert = mv;
1802   for (int i = 0; i < mesh->totvert; i++, mv++) {
1803     copy_v3_v3_short(mv->no, vert_normals[i]);
1804   }
1805   mesh->runtime.cd_dirty_vert &= ~CD_MASK_NORMAL;
1806 }
1807 
1808 /**
1809  * Compute 'split' (aka loop, or per face corner's) normals.
1810  *
1811  * \param r_lnors_spacearr: Allows to get computed loop normal space array.
1812  * That data, among other things, contains 'smooth fan' info, useful e.g.
1813  * to split geometry along sharp edges...
1814  */
BKE_mesh_calc_normals_split_ex(Mesh * mesh,MLoopNorSpaceArray * r_lnors_spacearr)1815 void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spacearr)
1816 {
1817   float(*r_loopnors)[3];
1818   float(*polynors)[3];
1819   short(*clnors)[2] = NULL;
1820   bool free_polynors = false;
1821 
1822   /* Note that we enforce computing clnors when the clnor space array is requested by caller here.
1823    * However, we obviously only use the autosmooth angle threshold
1824    * only in case autosmooth is enabled. */
1825   const bool use_split_normals = (r_lnors_spacearr != NULL) || ((mesh->flag & ME_AUTOSMOOTH) != 0);
1826   const float split_angle = (mesh->flag & ME_AUTOSMOOTH) != 0 ? mesh->smoothresh : (float)M_PI;
1827 
1828   if (CustomData_has_layer(&mesh->ldata, CD_NORMAL)) {
1829     r_loopnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL);
1830     memset(r_loopnors, 0, sizeof(float[3]) * mesh->totloop);
1831   }
1832   else {
1833     r_loopnors = CustomData_add_layer(&mesh->ldata, CD_NORMAL, CD_CALLOC, NULL, mesh->totloop);
1834     CustomData_set_layer_flag(&mesh->ldata, CD_NORMAL, CD_FLAG_TEMPORARY);
1835   }
1836 
1837   /* may be NULL */
1838   clnors = CustomData_get_layer(&mesh->ldata, CD_CUSTOMLOOPNORMAL);
1839 
1840   if (CustomData_has_layer(&mesh->pdata, CD_NORMAL)) {
1841     /* This assume that layer is always up to date, not sure this is the case
1842      * (esp. in Edit mode?)... */
1843     polynors = CustomData_get_layer(&mesh->pdata, CD_NORMAL);
1844     free_polynors = false;
1845   }
1846   else {
1847     polynors = MEM_malloc_arrayN(mesh->totpoly, sizeof(float[3]), __func__);
1848     BKE_mesh_calc_normals_poly(mesh->mvert,
1849                                NULL,
1850                                mesh->totvert,
1851                                mesh->mloop,
1852                                mesh->mpoly,
1853                                mesh->totloop,
1854                                mesh->totpoly,
1855                                polynors,
1856                                false);
1857     free_polynors = true;
1858   }
1859 
1860   BKE_mesh_normals_loop_split(mesh->mvert,
1861                               mesh->totvert,
1862                               mesh->medge,
1863                               mesh->totedge,
1864                               mesh->mloop,
1865                               r_loopnors,
1866                               mesh->totloop,
1867                               mesh->mpoly,
1868                               (const float(*)[3])polynors,
1869                               mesh->totpoly,
1870                               use_split_normals,
1871                               split_angle,
1872                               r_lnors_spacearr,
1873                               clnors,
1874                               NULL);
1875 
1876   if (free_polynors) {
1877     MEM_freeN(polynors);
1878   }
1879 
1880   mesh->runtime.cd_dirty_vert &= ~CD_MASK_NORMAL;
1881 }
1882 
BKE_mesh_calc_normals_split(Mesh * mesh)1883 void BKE_mesh_calc_normals_split(Mesh *mesh)
1884 {
1885   BKE_mesh_calc_normals_split_ex(mesh, NULL);
1886 }
1887 
1888 /* Split faces helper functions. */
1889 
1890 typedef struct SplitFaceNewVert {
1891   struct SplitFaceNewVert *next;
1892   int new_index;
1893   int orig_index;
1894   float *vnor;
1895 } SplitFaceNewVert;
1896 
1897 typedef struct SplitFaceNewEdge {
1898   struct SplitFaceNewEdge *next;
1899   int new_index;
1900   int orig_index;
1901   int v1;
1902   int v2;
1903 } SplitFaceNewEdge;
1904 
1905 /* Detect needed new vertices, and update accordingly loops' vertex indices.
1906  * WARNING! Leaves mesh in invalid state. */
split_faces_prepare_new_verts(const Mesh * mesh,MLoopNorSpaceArray * lnors_spacearr,SplitFaceNewVert ** new_verts,MemArena * memarena)1907 static int split_faces_prepare_new_verts(const Mesh *mesh,
1908                                          MLoopNorSpaceArray *lnors_spacearr,
1909                                          SplitFaceNewVert **new_verts,
1910                                          MemArena *memarena)
1911 {
1912   /* This is now mandatory, trying to do the job in simple way without that data is doomed to fail,
1913    * even when only dealing with smooth/flat faces one can find cases that no simple algorithm
1914    * can handle properly. */
1915   BLI_assert(lnors_spacearr != NULL);
1916 
1917   const int loops_len = mesh->totloop;
1918   int verts_len = mesh->totvert;
1919   MVert *mvert = mesh->mvert;
1920   MLoop *mloop = mesh->mloop;
1921 
1922   BLI_bitmap *verts_used = BLI_BITMAP_NEW(verts_len, __func__);
1923   BLI_bitmap *done_loops = BLI_BITMAP_NEW(loops_len, __func__);
1924 
1925   MLoop *ml = mloop;
1926   MLoopNorSpace **lnor_space = lnors_spacearr->lspacearr;
1927 
1928   BLI_assert(lnors_spacearr->data_type == MLNOR_SPACEARR_LOOP_INDEX);
1929 
1930   for (int loop_idx = 0; loop_idx < loops_len; loop_idx++, ml++, lnor_space++) {
1931     if (!BLI_BITMAP_TEST(done_loops, loop_idx)) {
1932       const int vert_idx = ml->v;
1933       const bool vert_used = BLI_BITMAP_TEST_BOOL(verts_used, vert_idx);
1934       /* If vert is already used by another smooth fan, we need a new vert for this one. */
1935       const int new_vert_idx = vert_used ? verts_len++ : vert_idx;
1936 
1937       BLI_assert(*lnor_space);
1938 
1939       if ((*lnor_space)->flags & MLNOR_SPACE_IS_SINGLE) {
1940         /* Single loop in this fan... */
1941         BLI_assert(POINTER_AS_INT((*lnor_space)->loops) == loop_idx);
1942         BLI_BITMAP_ENABLE(done_loops, loop_idx);
1943         if (vert_used) {
1944           ml->v = new_vert_idx;
1945         }
1946       }
1947       else {
1948         for (LinkNode *lnode = (*lnor_space)->loops; lnode; lnode = lnode->next) {
1949           const int ml_fan_idx = POINTER_AS_INT(lnode->link);
1950           BLI_BITMAP_ENABLE(done_loops, ml_fan_idx);
1951           if (vert_used) {
1952             mloop[ml_fan_idx].v = new_vert_idx;
1953           }
1954         }
1955       }
1956 
1957       if (!vert_used) {
1958         BLI_BITMAP_ENABLE(verts_used, vert_idx);
1959         /* We need to update that vertex's normal here, we won't go over it again. */
1960         /* This is important! *DO NOT* set vnor to final computed lnor,
1961          * vnor should always be defined to 'automatic normal' value computed from its polys,
1962          * not some custom normal.
1963          * Fortunately, that's the loop normal space's 'lnor' reference vector. ;) */
1964         normal_float_to_short_v3(mvert[vert_idx].no, (*lnor_space)->vec_lnor);
1965       }
1966       else {
1967         /* Add new vert to list. */
1968         SplitFaceNewVert *new_vert = BLI_memarena_alloc(memarena, sizeof(*new_vert));
1969         new_vert->orig_index = vert_idx;
1970         new_vert->new_index = new_vert_idx;
1971         new_vert->vnor = (*lnor_space)->vec_lnor; /* See note above. */
1972         new_vert->next = *new_verts;
1973         *new_verts = new_vert;
1974       }
1975     }
1976   }
1977 
1978   MEM_freeN(done_loops);
1979   MEM_freeN(verts_used);
1980 
1981   return verts_len - mesh->totvert;
1982 }
1983 
1984 /* Detect needed new edges, and update accordingly loops' edge indices.
1985  * WARNING! Leaves mesh in invalid state. */
split_faces_prepare_new_edges(const Mesh * mesh,SplitFaceNewEdge ** new_edges,MemArena * memarena)1986 static int split_faces_prepare_new_edges(const Mesh *mesh,
1987                                          SplitFaceNewEdge **new_edges,
1988                                          MemArena *memarena)
1989 {
1990   const int num_polys = mesh->totpoly;
1991   int num_edges = mesh->totedge;
1992   MEdge *medge = mesh->medge;
1993   MLoop *mloop = mesh->mloop;
1994   const MPoly *mpoly = mesh->mpoly;
1995 
1996   BLI_bitmap *edges_used = BLI_BITMAP_NEW(num_edges, __func__);
1997   EdgeHash *edges_hash = BLI_edgehash_new_ex(__func__, num_edges);
1998 
1999   const MPoly *mp = mpoly;
2000   for (int poly_idx = 0; poly_idx < num_polys; poly_idx++, mp++) {
2001     MLoop *ml_prev = &mloop[mp->loopstart + mp->totloop - 1];
2002     MLoop *ml = &mloop[mp->loopstart];
2003     for (int loop_idx = 0; loop_idx < mp->totloop; loop_idx++, ml++) {
2004       void **eval;
2005       if (!BLI_edgehash_ensure_p(edges_hash, ml_prev->v, ml->v, &eval)) {
2006         const int edge_idx = ml_prev->e;
2007 
2008         /* That edge has not been encountered yet, define it. */
2009         if (BLI_BITMAP_TEST(edges_used, edge_idx)) {
2010           /* Original edge has already been used, we need to define a new one. */
2011           const int new_edge_idx = num_edges++;
2012           *eval = POINTER_FROM_INT(new_edge_idx);
2013           ml_prev->e = new_edge_idx;
2014 
2015           SplitFaceNewEdge *new_edge = BLI_memarena_alloc(memarena, sizeof(*new_edge));
2016           new_edge->orig_index = edge_idx;
2017           new_edge->new_index = new_edge_idx;
2018           new_edge->v1 = ml_prev->v;
2019           new_edge->v2 = ml->v;
2020           new_edge->next = *new_edges;
2021           *new_edges = new_edge;
2022         }
2023         else {
2024           /* We can re-use original edge. */
2025           medge[edge_idx].v1 = ml_prev->v;
2026           medge[edge_idx].v2 = ml->v;
2027           *eval = POINTER_FROM_INT(edge_idx);
2028           BLI_BITMAP_ENABLE(edges_used, edge_idx);
2029         }
2030       }
2031       else {
2032         /* Edge already known, just update loop's edge index. */
2033         ml_prev->e = POINTER_AS_INT(*eval);
2034       }
2035 
2036       ml_prev = ml;
2037     }
2038   }
2039 
2040   MEM_freeN(edges_used);
2041   BLI_edgehash_free(edges_hash, NULL);
2042 
2043   return num_edges - mesh->totedge;
2044 }
2045 
2046 /* Perform actual split of vertices. */
split_faces_split_new_verts(Mesh * mesh,SplitFaceNewVert * new_verts,const int num_new_verts)2047 static void split_faces_split_new_verts(Mesh *mesh,
2048                                         SplitFaceNewVert *new_verts,
2049                                         const int num_new_verts)
2050 {
2051   const int verts_len = mesh->totvert - num_new_verts;
2052   MVert *mvert = mesh->mvert;
2053 
2054   /* Remember new_verts is a single linklist, so its items are in reversed order... */
2055   MVert *new_mv = &mvert[mesh->totvert - 1];
2056   for (int i = mesh->totvert - 1; i >= verts_len; i--, new_mv--, new_verts = new_verts->next) {
2057     BLI_assert(new_verts->new_index == i);
2058     BLI_assert(new_verts->new_index != new_verts->orig_index);
2059     CustomData_copy_data(&mesh->vdata, &mesh->vdata, new_verts->orig_index, i, 1);
2060     if (new_verts->vnor) {
2061       normal_float_to_short_v3(new_mv->no, new_verts->vnor);
2062     }
2063   }
2064 }
2065 
2066 /* Perform actual split of edges. */
split_faces_split_new_edges(Mesh * mesh,SplitFaceNewEdge * new_edges,const int num_new_edges)2067 static void split_faces_split_new_edges(Mesh *mesh,
2068                                         SplitFaceNewEdge *new_edges,
2069                                         const int num_new_edges)
2070 {
2071   const int num_edges = mesh->totedge - num_new_edges;
2072   MEdge *medge = mesh->medge;
2073 
2074   /* Remember new_edges is a single linklist, so its items are in reversed order... */
2075   MEdge *new_med = &medge[mesh->totedge - 1];
2076   for (int i = mesh->totedge - 1; i >= num_edges; i--, new_med--, new_edges = new_edges->next) {
2077     BLI_assert(new_edges->new_index == i);
2078     BLI_assert(new_edges->new_index != new_edges->orig_index);
2079     CustomData_copy_data(&mesh->edata, &mesh->edata, new_edges->orig_index, i, 1);
2080     new_med->v1 = new_edges->v1;
2081     new_med->v2 = new_edges->v2;
2082   }
2083 }
2084 
2085 /* Split faces based on the edge angle and loop normals.
2086  * Matches behavior of face splitting in render engines.
2087  *
2088  * NOTE: Will leave CD_NORMAL loop data layer which is
2089  * used by render engines to set shading up.
2090  */
BKE_mesh_split_faces(Mesh * mesh,bool free_loop_normals)2091 void BKE_mesh_split_faces(Mesh *mesh, bool free_loop_normals)
2092 {
2093   const int num_polys = mesh->totpoly;
2094 
2095   if (num_polys == 0) {
2096     return;
2097   }
2098   BKE_mesh_tessface_clear(mesh);
2099 
2100   MLoopNorSpaceArray lnors_spacearr = {NULL};
2101   /* Compute loop normals and loop normal spaces (a.k.a. smooth fans of faces around vertices). */
2102   BKE_mesh_calc_normals_split_ex(mesh, &lnors_spacearr);
2103   /* Stealing memarena from loop normals space array. */
2104   MemArena *memarena = lnors_spacearr.mem;
2105 
2106   SplitFaceNewVert *new_verts = NULL;
2107   SplitFaceNewEdge *new_edges = NULL;
2108 
2109   /* Detect loop normal spaces (a.k.a. smooth fans) that will need a new vert. */
2110   const int num_new_verts = split_faces_prepare_new_verts(
2111       mesh, &lnors_spacearr, &new_verts, memarena);
2112 
2113   if (num_new_verts > 0) {
2114     /* Reminder: beyond this point, there is no way out, mesh is in invalid state
2115      * (due to early-reassignment of loops' vertex and edge indices to new,
2116      * to-be-created split ones). */
2117 
2118     const int num_new_edges = split_faces_prepare_new_edges(mesh, &new_edges, memarena);
2119     /* We can have to split a vertex without having to add a single new edge... */
2120     const bool do_edges = (num_new_edges > 0);
2121 
2122     /* Reallocate all vert and edge related data. */
2123     mesh->totvert += num_new_verts;
2124     CustomData_realloc(&mesh->vdata, mesh->totvert);
2125     if (do_edges) {
2126       mesh->totedge += num_new_edges;
2127       CustomData_realloc(&mesh->edata, mesh->totedge);
2128     }
2129     /* Update pointers to a newly allocated memory. */
2130     BKE_mesh_update_customdata_pointers(mesh, false);
2131 
2132     /* Perform actual split of vertices and edges. */
2133     split_faces_split_new_verts(mesh, new_verts, num_new_verts);
2134     if (do_edges) {
2135       split_faces_split_new_edges(mesh, new_edges, num_new_edges);
2136     }
2137   }
2138 
2139   /* Note: after this point mesh is expected to be valid again. */
2140 
2141   /* CD_NORMAL is expected to be temporary only. */
2142   if (free_loop_normals) {
2143     CustomData_free_layers(&mesh->ldata, CD_NORMAL, mesh->totloop);
2144   }
2145 
2146   /* Also frees new_verts/edges temp data, since we used its memarena to allocate them. */
2147   BKE_lnor_spacearr_free(&lnors_spacearr);
2148 
2149 #ifdef VALIDATE_MESH
2150   BKE_mesh_validate(mesh, true, true);
2151 #endif
2152 }
2153 
2154 /* **** Depsgraph evaluation **** */
2155 
BKE_mesh_eval_geometry(Depsgraph * depsgraph,Mesh * mesh)2156 void BKE_mesh_eval_geometry(Depsgraph *depsgraph, Mesh *mesh)
2157 {
2158   DEG_debug_print_eval(depsgraph, __func__, mesh->id.name, mesh);
2159   BKE_mesh_texspace_calc(mesh);
2160   /* We are here because something did change in the mesh. This means we can not trust the existing
2161    * evaluated mesh, and we don't know what parts of the mesh did change. So we simply delete the
2162    * evaluated mesh and let objects to re-create it with updated settings. */
2163   if (mesh->runtime.mesh_eval != NULL) {
2164     mesh->runtime.mesh_eval->edit_mesh = NULL;
2165     BKE_id_free(NULL, mesh->runtime.mesh_eval);
2166     mesh->runtime.mesh_eval = NULL;
2167   }
2168   if (DEG_is_active(depsgraph)) {
2169     Mesh *mesh_orig = (Mesh *)DEG_get_original_id(&mesh->id);
2170     if (mesh->texflag & ME_AUTOSPACE_EVALUATED) {
2171       mesh_orig->texflag |= ME_AUTOSPACE_EVALUATED;
2172       copy_v3_v3(mesh_orig->loc, mesh->loc);
2173       copy_v3_v3(mesh_orig->size, mesh->size);
2174     }
2175   }
2176 }
2177