2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * Contributor(s): Blender Foundation
23 * ***** END GPL LICENSE BLOCK *****
26 /** \file blender/blenkernel/intern/mesh.c
30 #include "MEM_guardedalloc.h"
32 #include "DNA_scene_types.h"
33 #include "DNA_material_types.h"
34 #include "DNA_object_types.h"
35 #include "DNA_key_types.h"
36 #include "DNA_mesh_types.h"
37 #include "DNA_ipo_types.h"
39 #include "BLI_utildefines.h"
41 #include "BLI_listbase.h"
42 #include "BLI_edgehash.h"
43 #include "BLI_string.h"
45 #include "BKE_animsys.h"
47 #include "BKE_DerivedMesh.h"
48 #include "BKE_global.h"
50 #include "BKE_displist.h"
51 #include "BKE_library.h"
52 #include "BKE_material.h"
53 #include "BKE_modifier.h"
54 #include "BKE_multires.h"
56 #include "BKE_mball.h"
57 #include "BKE_depsgraph.h"
58 /* these 2 are only used by conversion functions */
59 #include "BKE_curve.h"
61 #include "BKE_object.h"
62 #include "BKE_editmesh.h"
66 MESHCMP_DVERT_WEIGHTMISMATCH = 1,
67 MESHCMP_DVERT_GROUPMISMATCH,
68 MESHCMP_DVERT_TOTGROUPMISMATCH,
69 MESHCMP_LOOPCOLMISMATCH,
70 MESHCMP_LOOPUVMISMATCH,
72 MESHCMP_POLYVERTMISMATCH,
75 MESHCMP_VERTCOMISMATCH,
76 MESHCMP_CDLAYERS_MISMATCH
79 static const char *cmpcode_to_str(int code)
82 case MESHCMP_DVERT_WEIGHTMISMATCH:
83 return "Vertex Weight Mismatch";
84 case MESHCMP_DVERT_GROUPMISMATCH:
85 return "Vertex Group Mismatch";
86 case MESHCMP_DVERT_TOTGROUPMISMATCH:
87 return "Vertex Doesn't Belong To Same Number Of Groups";
88 case MESHCMP_LOOPCOLMISMATCH:
89 return "Vertex Color Mismatch";
90 case MESHCMP_LOOPUVMISMATCH:
92 case MESHCMP_LOOPMISMATCH:
93 return "Loop Mismatch";
94 case MESHCMP_POLYVERTMISMATCH:
95 return "Loop Vert Mismatch In Poly Test";
96 case MESHCMP_POLYMISMATCH:
97 return "Loop Vert Mismatch";
98 case MESHCMP_EDGEUNKNOWN:
99 return "Edge Mismatch";
100 case MESHCMP_VERTCOMISMATCH:
101 return "Vertex Coordinate Mismatch";
102 case MESHCMP_CDLAYERS_MISMATCH:
103 return "CustomData Layer Count Mismatch";
105 return "Mesh Comparison Code Unknown";
109 /* thresh is threshold for comparing vertices, uvs, vertex colors,
111 static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2, const float thresh)
113 const float thresh_sq = thresh * thresh;
114 CustomDataLayer *l1, *l2;
115 int i, i1 = 0, i2 = 0, tot, j;
117 for (i = 0; i < c1->totlayer; i++) {
118 if (ELEM(c1->layers[i].type, CD_MVERT, CD_MEDGE, CD_MPOLY,
119 CD_MLOOPUV, CD_MLOOPCOL, CD_MTEXPOLY, CD_MDEFORMVERT))
125 for (i = 0; i < c2->totlayer; i++) {
126 if (ELEM(c2->layers[i].type, CD_MVERT, CD_MEDGE, CD_MPOLY,
127 CD_MLOOPUV, CD_MLOOPCOL, CD_MTEXPOLY, CD_MDEFORMVERT))
134 return MESHCMP_CDLAYERS_MISMATCH;
136 l1 = c1->layers; l2 = c2->layers;
139 for (i = 0; i < tot; i++) {
140 while (i1 < c1->totlayer && !ELEM(l1->type, CD_MVERT, CD_MEDGE, CD_MPOLY,
141 CD_MLOOPUV, CD_MLOOPCOL, CD_MTEXPOLY, CD_MDEFORMVERT))
146 while (i2 < c2->totlayer && !ELEM(l2->type, CD_MVERT, CD_MEDGE, CD_MPOLY,
147 CD_MLOOPUV, CD_MLOOPCOL, CD_MTEXPOLY, CD_MDEFORMVERT))
152 if (l1->type == CD_MVERT) {
153 MVert *v1 = l1->data;
154 MVert *v2 = l2->data;
155 int vtot = m1->totvert;
157 for (j = 0; j < vtot; j++, v1++, v2++) {
158 if (len_squared_v3v3(v1->co, v2->co) > thresh_sq)
159 return MESHCMP_VERTCOMISMATCH;
160 /* I don't care about normals, let's just do coodinates */
164 /*we're order-agnostic for edges here*/
165 if (l1->type == CD_MEDGE) {
166 MEdge *e1 = l1->data;
167 MEdge *e2 = l2->data;
168 int etot = m1->totedge;
169 EdgeHash *eh = BLI_edgehash_new_ex(__func__, etot);
171 for (j = 0; j < etot; j++, e1++) {
172 BLI_edgehash_insert(eh, e1->v1, e1->v2, e1);
175 for (j = 0; j < etot; j++, e2++) {
176 if (!BLI_edgehash_lookup(eh, e2->v1, e2->v2))
177 return MESHCMP_EDGEUNKNOWN;
179 BLI_edgehash_free(eh, NULL);
182 if (l1->type == CD_MPOLY) {
183 MPoly *p1 = l1->data;
184 MPoly *p2 = l2->data;
185 int ptot = m1->totpoly;
187 for (j = 0; j < ptot; j++, p1++, p2++) {
191 if (p1->totloop != p2->totloop)
192 return MESHCMP_POLYMISMATCH;
194 lp1 = m1->mloop + p1->loopstart;
195 lp2 = m2->mloop + p2->loopstart;
197 for (k = 0; k < p1->totloop; k++, lp1++, lp2++) {
198 if (lp1->v != lp2->v)
199 return MESHCMP_POLYVERTMISMATCH;
203 if (l1->type == CD_MLOOP) {
204 MLoop *lp1 = l1->data;
205 MLoop *lp2 = l2->data;
206 int ltot = m1->totloop;
208 for (j = 0; j < ltot; j++, lp1++, lp2++) {
209 if (lp1->v != lp2->v)
210 return MESHCMP_LOOPMISMATCH;
213 if (l1->type == CD_MLOOPUV) {
214 MLoopUV *lp1 = l1->data;
215 MLoopUV *lp2 = l2->data;
216 int ltot = m1->totloop;
218 for (j = 0; j < ltot; j++, lp1++, lp2++) {
219 if (len_squared_v2v2(lp1->uv, lp2->uv) > thresh_sq)
220 return MESHCMP_LOOPUVMISMATCH;
224 if (l1->type == CD_MLOOPCOL) {
225 MLoopCol *lp1 = l1->data;
226 MLoopCol *lp2 = l2->data;
227 int ltot = m1->totloop;
229 for (j = 0; j < ltot; j++, lp1++, lp2++) {
230 if (ABS(lp1->r - lp2->r) > thresh ||
231 ABS(lp1->g - lp2->g) > thresh ||
232 ABS(lp1->b - lp2->b) > thresh ||
233 ABS(lp1->a - lp2->a) > thresh)
235 return MESHCMP_LOOPCOLMISMATCH;
240 if (l1->type == CD_MDEFORMVERT) {
241 MDeformVert *dv1 = l1->data;
242 MDeformVert *dv2 = l2->data;
243 int dvtot = m1->totvert;
245 for (j = 0; j < dvtot; j++, dv1++, dv2++) {
247 MDeformWeight *dw1 = dv1->dw, *dw2 = dv2->dw;
249 if (dv1->totweight != dv2->totweight)
250 return MESHCMP_DVERT_TOTGROUPMISMATCH;
252 for (k = 0; k < dv1->totweight; k++, dw1++, dw2++) {
253 if (dw1->def_nr != dw2->def_nr)
254 return MESHCMP_DVERT_GROUPMISMATCH;
255 if (fabsf(dw1->weight - dw2->weight) > thresh)
256 return MESHCMP_DVERT_WEIGHTMISMATCH;
266 * Used for unit testing; compares two meshes, checking only
267 * differences we care about. should be usable with leaf's
268 * testing framework I get RNA work done, will use hackish
269 * testing code for now.
271 const char *BKE_mesh_cmp(Mesh *me1, Mesh *me2, float thresh)
276 return "Requires two input meshes";
278 if (me1->totvert != me2->totvert)
279 return "Number of verts don't match";
281 if (me1->totedge != me2->totedge)
282 return "Number of edges don't match";
284 if (me1->totpoly != me2->totpoly)
285 return "Number of faces don't match";
287 if (me1->totloop != me2->totloop)
288 return "Number of loops don't match";
290 if ((c = customdata_compare(&me1->vdata, &me2->vdata, me1, me2, thresh)))
291 return cmpcode_to_str(c);
293 if ((c = customdata_compare(&me1->edata, &me2->edata, me1, me2, thresh)))
294 return cmpcode_to_str(c);
296 if ((c = customdata_compare(&me1->ldata, &me2->ldata, me1, me2, thresh)))
297 return cmpcode_to_str(c);
299 if ((c = customdata_compare(&me1->pdata, &me2->pdata, me1, me2, thresh)))
300 return cmpcode_to_str(c);
305 static void mesh_ensure_tessellation_customdata(Mesh *me)
307 if (UNLIKELY((me->totface != 0) && (me->totpoly == 0))) {
308 /* Pass, otherwise this function clears 'mface' before
309 * versioning 'mface -> mpoly' code kicks in [#30583]
311 * Callers could also check but safer to do here - campbell */
314 const int tottex_original = CustomData_number_of_layers(&me->pdata, CD_MTEXPOLY);
315 const int totcol_original = CustomData_number_of_layers(&me->ldata, CD_MLOOPCOL);
317 const int tottex_tessface = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
318 const int totcol_tessface = CustomData_number_of_layers(&me->fdata, CD_MCOL);
320 if (tottex_tessface != tottex_original ||
321 totcol_tessface != totcol_original)
323 BKE_mesh_tessface_clear(me);
325 CustomData_from_bmeshpoly(&me->fdata, &me->pdata, &me->ldata, me->totface);
327 /* TODO - add some --debug-mesh option */
328 if (G.debug & G_DEBUG) {
329 /* note: this warning may be un-called for if we are initializing the mesh for the
330 * first time from bmesh, rather then giving a warning about this we could be smarter
331 * and check if there was any data to begin with, for now just print the warning with
332 * some info to help troubleshoot whats going on - campbell */
333 printf("%s: warning! Tessellation uvs or vcol data got out of sync, "
334 "had to reset!\n CD_MTFACE: %d != CD_MTEXPOLY: %d || CD_MCOL: %d != CD_MLOOPCOL: %d\n",
335 __func__, tottex_tessface, tottex_original, totcol_tessface, totcol_original);
341 void BKE_mesh_ensure_skin_customdata(Mesh *me)
343 BMesh *bm = me->edit_btmesh ? me->edit_btmesh->bm : NULL;
347 if (!CustomData_has_layer(&bm->vdata, CD_MVERT_SKIN)) {
351 BM_data_layer_add(bm, &bm->vdata, CD_MVERT_SKIN);
353 /* Mark an arbitrary vertex as root */
354 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
355 vs = CustomData_bmesh_get(&bm->vdata, v->head.data,
357 vs->flag |= MVERT_SKIN_ROOT;
363 if (!CustomData_has_layer(&me->vdata, CD_MVERT_SKIN)) {
364 vs = CustomData_add_layer(&me->vdata,
370 /* Mark an arbitrary vertex as root */
372 vs->flag |= MVERT_SKIN_ROOT;
378 /* this ensures grouped customdata (e.g. mtexpoly and mloopuv and mtface, or
379 * mloopcol and mcol) have the same relative active/render/clone/mask indices.
381 * note that for undo mesh data we want to skip 'ensure_tess_cd' call since
382 * we don't want to store memory for tessface when its only used for older
383 * versions of the mesh. - campbell*/
384 static void mesh_update_linked_customdata(Mesh *me, const bool do_ensure_tess_cd)
387 BKE_editmesh_update_linked_customdata(me->edit_btmesh);
389 if (do_ensure_tess_cd) {
390 mesh_ensure_tessellation_customdata(me);
393 CustomData_bmesh_update_active_layers(&me->fdata, &me->pdata, &me->ldata);
396 void BKE_mesh_update_customdata_pointers(Mesh *me, const bool do_ensure_tess_cd)
398 mesh_update_linked_customdata(me, do_ensure_tess_cd);
400 me->mvert = CustomData_get_layer(&me->vdata, CD_MVERT);
401 me->dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT);
403 me->medge = CustomData_get_layer(&me->edata, CD_MEDGE);
405 me->mface = CustomData_get_layer(&me->fdata, CD_MFACE);
406 me->mcol = CustomData_get_layer(&me->fdata, CD_MCOL);
407 me->mtface = CustomData_get_layer(&me->fdata, CD_MTFACE);
409 me->mpoly = CustomData_get_layer(&me->pdata, CD_MPOLY);
410 me->mloop = CustomData_get_layer(&me->ldata, CD_MLOOP);
412 me->mtpoly = CustomData_get_layer(&me->pdata, CD_MTEXPOLY);
413 me->mloopcol = CustomData_get_layer(&me->ldata, CD_MLOOPCOL);
414 me->mloopuv = CustomData_get_layer(&me->ldata, CD_MLOOPUV);
417 bool BKE_mesh_has_custom_loop_normals(Mesh *me)
419 if (me->edit_btmesh) {
420 return CustomData_has_layer(&me->edit_btmesh->bm->ldata, CD_CUSTOMLOOPNORMAL);
423 return CustomData_has_layer(&me->ldata, CD_CUSTOMLOOPNORMAL);
427 /* Note: unlinking is called when me->id.us is 0, question remains how
428 * much unlinking of Library data in Mesh should be done... probably
429 * we need a more generic method, like the expand() functions in
432 void BKE_mesh_unlink(Mesh *me)
436 if (me == NULL) return;
439 for (a = 0; a < me->totcol; a++) {
440 if (me->mat[a]) me->mat[a]->id.us--;
450 if (me->texcomesh) me->texcomesh = NULL;
453 /* do not free mesh itself */
454 void BKE_mesh_free(Mesh *me, int unlink)
459 CustomData_free(&me->vdata, me->totvert);
460 CustomData_free(&me->edata, me->totedge);
461 CustomData_free(&me->fdata, me->totface);
462 CustomData_free(&me->ldata, me->totloop);
463 CustomData_free(&me->pdata, me->totpoly);
466 BKE_animdata_free(&me->id);
470 if (me->mat) MEM_freeN(me->mat);
472 if (me->bb) MEM_freeN(me->bb);
473 if (me->mselect) MEM_freeN(me->mselect);
474 if (me->edit_btmesh) MEM_freeN(me->edit_btmesh);
477 static void mesh_tessface_clear_intern(Mesh *mesh, int free_customdata)
479 if (free_customdata) {
480 CustomData_free(&mesh->fdata, mesh->totface);
483 CustomData_reset(&mesh->fdata);
492 Mesh *BKE_mesh_add(Main *bmain, const char *name)
496 me = BKE_libblock_alloc(bmain, ID_ME, name);
498 me->size[0] = me->size[1] = me->size[2] = 1.0;
500 me->texflag = ME_AUTOSPACE;
502 /* disable because its slow on many GPU's, see [#37518] */
504 me->flag = ME_TWOSIDED;
506 me->drawflag = ME_DRAWEDGES | ME_DRAWFACES | ME_DRAWCREASES;
508 CustomData_reset(&me->vdata);
509 CustomData_reset(&me->edata);
510 CustomData_reset(&me->fdata);
511 CustomData_reset(&me->pdata);
512 CustomData_reset(&me->ldata);
517 Mesh *BKE_mesh_copy_ex(Main *bmain, Mesh *me)
523 const int do_tessface = ((me->totface != 0) && (me->totpoly == 0)); /* only do tessface if we have no polys */
525 men = BKE_libblock_copy_ex(bmain, &me->id);
527 men->mat = MEM_dupallocN(me->mat);
528 for (a = 0; a < men->totcol; a++) {
529 id_us_plus((ID *)men->mat[a]);
531 id_us_plus((ID *)men->texcomesh);
533 CustomData_copy(&me->vdata, &men->vdata, CD_MASK_MESH, CD_DUPLICATE, men->totvert);
534 CustomData_copy(&me->edata, &men->edata, CD_MASK_MESH, CD_DUPLICATE, men->totedge);
535 CustomData_copy(&me->ldata, &men->ldata, CD_MASK_MESH, CD_DUPLICATE, men->totloop);
536 CustomData_copy(&me->pdata, &men->pdata, CD_MASK_MESH, CD_DUPLICATE, men->totpoly);
538 CustomData_copy(&me->fdata, &men->fdata, CD_MASK_MESH, CD_DUPLICATE, men->totface);
541 mesh_tessface_clear_intern(men, false);
544 BKE_mesh_update_customdata_pointers(men, do_tessface);
546 /* ensure indirect linked data becomes lib-extern */
547 for (i = 0; i < me->fdata.totlayer; i++) {
548 if (me->fdata.layers[i].type == CD_MTFACE) {
549 tface = (MTFace *)me->fdata.layers[i].data;
551 for (a = 0; a < me->totface; a++, tface++)
553 id_lib_extern((ID *)tface->tpage);
557 for (i = 0; i < me->pdata.totlayer; i++) {
558 if (me->pdata.layers[i].type == CD_MTEXPOLY) {
559 txface = (MTexPoly *)me->pdata.layers[i].data;
561 for (a = 0; a < me->totpoly; a++, txface++)
563 id_lib_extern((ID *)txface->tpage);
567 men->edit_btmesh = NULL;
569 men->mselect = MEM_dupallocN(men->mselect);
570 men->bb = MEM_dupallocN(men->bb);
572 men->key = BKE_key_copy(me->key);
573 if (men->key) men->key->from = (ID *)men;
576 BKE_id_lib_local_paths(bmain, me->id.lib, &men->id);
582 Mesh *BKE_mesh_copy(Mesh *me)
584 return BKE_mesh_copy_ex(G.main, me);
587 BMesh *BKE_mesh_to_bmesh(Mesh *me, Object *ob)
590 const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_ME(me);
592 bm = BM_mesh_create(&allocsize);
594 BM_mesh_bm_from_me(bm, me, false, true, ob->shapenr);
599 static void expand_local_mesh(Mesh *me)
601 id_lib_extern((ID *)me->texcomesh);
603 if (me->mtface || me->mtpoly) {
606 for (i = 0; i < me->pdata.totlayer; i++) {
607 if (me->pdata.layers[i].type == CD_MTEXPOLY) {
608 MTexPoly *txface = (MTexPoly *)me->pdata.layers[i].data;
610 for (a = 0; a < me->totpoly; a++, txface++) {
611 /* special case: ima always local immediately */
613 id_lib_extern((ID *)txface->tpage);
619 for (i = 0; i < me->fdata.totlayer; i++) {
620 if (me->fdata.layers[i].type == CD_MTFACE) {
621 MTFace *tface = (MTFace *)me->fdata.layers[i].data;
623 for (a = 0; a < me->totface; a++, tface++) {
624 /* special case: ima always local immediately */
626 id_lib_extern((ID *)tface->tpage);
634 extern_local_matarar(me->mat, me->totcol);
638 void BKE_mesh_make_local(Mesh *me)
640 Main *bmain = G.main;
642 bool is_local = false, is_lib = false;
644 /* - only lib users: do nothing
645 * - only local users: set flag
649 if (me->id.lib == NULL) return;
650 if (me->id.us == 1) {
651 id_clear_lib_data(bmain, &me->id);
652 expand_local_mesh(me);
656 for (ob = bmain->object.first; ob && ELEM(0, is_lib, is_local); ob = ob->id.next) {
657 if (me == ob->data) {
658 if (ob->id.lib) is_lib = true;
659 else is_local = true;
663 if (is_local && is_lib == false) {
664 id_clear_lib_data(bmain, &me->id);
665 expand_local_mesh(me);
667 else if (is_local && is_lib) {
668 Mesh *me_new = BKE_mesh_copy(me);
672 /* Remap paths of new ID using old library as base. */
673 BKE_id_lib_local_paths(bmain, me->id.lib, &me_new->id);
675 for (ob = bmain->object.first; ob; ob = ob->id.next) {
676 if (me == ob->data) {
677 if (ob->id.lib == NULL) {
678 BKE_mesh_assign_object(ob, me_new);
685 bool BKE_mesh_uv_cdlayer_rename_index(Mesh *me, const int poly_index, const int loop_index, const int face_index,
686 const char *new_name, const bool do_tessface)
688 CustomData *pdata, *ldata, *fdata;
689 CustomDataLayer *cdlp, *cdlu, *cdlf;
690 const int step = do_tessface ? 3 : 2;
693 if (me->edit_btmesh) {
694 pdata = &me->edit_btmesh->bm->pdata;
695 ldata = &me->edit_btmesh->bm->ldata;
696 fdata = NULL; /* No tessellated data in BMesh! */
703 cdlp = &pdata->layers[poly_index];
704 cdlu = &ldata->layers[loop_index];
705 cdlf = fdata && do_tessface ? &fdata->layers[face_index] : NULL;
707 if (cdlp->name != new_name) {
708 /* Mesh validate passes a name from the CD layer as the new name,
709 * Avoid memcpy from self to self in this case.
711 BLI_strncpy(cdlp->name, new_name, sizeof(cdlp->name));
712 CustomData_set_layer_unique_name(pdata, cdlp - pdata->layers);
715 /* Loop until we do have exactly the same name for all layers! */
716 for (i = 1; !STREQ(cdlp->name, cdlu->name) || (cdlf && !STREQ(cdlp->name, cdlf->name)); i++) {
719 BLI_strncpy(cdlp->name, cdlu->name, sizeof(cdlp->name));
720 CustomData_set_layer_unique_name(pdata, cdlp - pdata->layers);
723 BLI_strncpy(cdlu->name, cdlp->name, sizeof(cdlu->name));
724 CustomData_set_layer_unique_name(ldata, cdlu - ldata->layers);
728 BLI_strncpy(cdlf->name, cdlp->name, sizeof(cdlf->name));
729 CustomData_set_layer_unique_name(fdata, cdlf - fdata->layers);
738 bool BKE_mesh_uv_cdlayer_rename(Mesh *me, const char *old_name, const char *new_name, bool do_tessface)
740 CustomData *pdata, *ldata, *fdata;
741 if (me->edit_btmesh) {
742 pdata = &me->edit_btmesh->bm->pdata;
743 ldata = &me->edit_btmesh->bm->ldata;
744 /* No tessellated data in BMesh! */
752 do_tessface = (do_tessface && fdata->totlayer);
756 const int pidx_start = CustomData_get_layer_index(pdata, CD_MTEXPOLY);
757 const int lidx_start = CustomData_get_layer_index(ldata, CD_MLOOPUV);
758 const int fidx_start = do_tessface ? CustomData_get_layer_index(fdata, CD_MTFACE) : -1;
759 int pidx = CustomData_get_named_layer(pdata, CD_MTEXPOLY, old_name);
760 int lidx = CustomData_get_named_layer(ldata, CD_MLOOPUV, old_name);
761 int fidx = do_tessface ? CustomData_get_named_layer(fdata, CD_MTFACE, old_name) : -1;
763 /* None of those cases should happen, in theory!
764 * Note this assume we have the same number of mtexpoly, mloopuv and mtface layers!
769 /* No layer found with this name! */
782 if (fidx == -1 && do_tessface) {
787 /* For now, we do not consider mismatch in indices (i.e. same name leading to (relative) different indices). */
788 else if (pidx != lidx) {
793 /* Go back to absolute indices! */
799 return BKE_mesh_uv_cdlayer_rename_index(me, pidx, lidx, fidx, new_name, do_tessface);
803 void BKE_mesh_boundbox_calc(Mesh *me, float r_loc[3], float r_size[3])
806 float min[3], max[3];
807 float mloc[3], msize[3];
809 if (me->bb == NULL) me->bb = MEM_callocN(sizeof(BoundBox), "boundbox");
812 if (!r_loc) r_loc = mloc;
813 if (!r_size) r_size = msize;
815 INIT_MINMAX(min, max);
816 if (!BKE_mesh_minmax(me, min, max)) {
817 min[0] = min[1] = min[2] = -1.0f;
818 max[0] = max[1] = max[2] = 1.0f;
821 mid_v3_v3v3(r_loc, min, max);
823 r_size[0] = (max[0] - min[0]) / 2.0f;
824 r_size[1] = (max[1] - min[1]) / 2.0f;
825 r_size[2] = (max[2] - min[2]) / 2.0f;
827 BKE_boundbox_init_from_minmax(bb, min, max);
829 bb->flag &= ~BOUNDBOX_DIRTY;
832 void BKE_mesh_texspace_calc(Mesh *me)
834 float loc[3], size[3];
837 BKE_mesh_boundbox_calc(me, loc, size);
839 if (me->texflag & ME_AUTOSPACE) {
840 for (a = 0; a < 3; a++) {
841 if (size[a] == 0.0f) size[a] = 1.0f;
842 else if (size[a] > 0.0f && size[a] < 0.00001f) size[a] = 0.00001f;
843 else if (size[a] < 0.0f && size[a] > -0.00001f) size[a] = -0.00001f;
846 copy_v3_v3(me->loc, loc);
847 copy_v3_v3(me->size, size);
852 BoundBox *BKE_mesh_boundbox_get(Object *ob)
859 if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) {
860 BKE_mesh_texspace_calc(me);
866 void BKE_mesh_texspace_get(Mesh *me, float r_loc[3], float r_rot[3], float r_size[3])
868 if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) {
869 BKE_mesh_texspace_calc(me);
872 if (r_loc) copy_v3_v3(r_loc, me->loc);
873 if (r_rot) copy_v3_v3(r_rot, me->rot);
874 if (r_size) copy_v3_v3(r_size, me->size);
877 void BKE_mesh_texspace_copy_from_object(Mesh *me, Object *ob)
879 float *texloc, *texrot, *texsize;
882 if (BKE_object_obdata_texspace_get(ob, &texflag, &texloc, &texsize, &texrot)) {
883 me->texflag = *texflag;
884 copy_v3_v3(me->loc, texloc);
885 copy_v3_v3(me->size, texsize);
886 copy_v3_v3(me->rot, texrot);
890 float (*BKE_mesh_orco_verts_get(Object *ob))[3]
894 Mesh *tme = me->texcomesh ? me->texcomesh : me;
896 float (*vcos)[3] = NULL;
898 /* Get appropriate vertex coordinates */
899 vcos = MEM_callocN(sizeof(*vcos) * me->totvert, "orco mesh");
901 totvert = min_ii(tme->totvert, me->totvert);
903 for (a = 0; a < totvert; a++, mvert++) {
904 copy_v3_v3(vcos[a], mvert->co);
910 void BKE_mesh_orco_verts_transform(Mesh *me, float (*orco)[3], int totvert, int invert)
912 float loc[3], size[3];
915 BKE_mesh_texspace_get(me->texcomesh ? me->texcomesh : me, loc, NULL, size);
918 for (a = 0; a < totvert; a++) {
920 madd_v3_v3v3v3(co, loc, co, size);
924 for (a = 0; a < totvert; a++) {
926 co[0] = (co[0] - loc[0]) / size[0];
927 co[1] = (co[1] - loc[1]) / size[1];
928 co[2] = (co[2] - loc[2]) / size[2];
933 /* rotates the vertices of a face in case v[2] or v[3] (vertex index) is = 0.
934 * this is necessary to make the if (mface->v4) check for quads work */
935 int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
937 /* first test if the face is legal */
938 if ((mface->v3 || nr == 4) && mface->v3 == mface->v4) {
942 if ((mface->v2 || mface->v4) && mface->v2 == mface->v3) {
943 mface->v3 = mface->v4;
947 if (mface->v1 == mface->v2) {
948 mface->v2 = mface->v3;
949 mface->v3 = mface->v4;
954 /* check corrupt cases, bow-tie geometry, cant handle these because edge data wont exist so just return 0 */
958 mface->v1 == mface->v2 ||
959 mface->v2 == mface->v3 ||
960 mface->v3 == mface->v1)
968 mface->v1 == mface->v2 ||
969 mface->v2 == mface->v3 ||
970 mface->v3 == mface->v4 ||
971 mface->v4 == mface->v1 ||
972 /* across the face */
973 mface->v1 == mface->v3 ||
974 mface->v2 == mface->v4)
980 /* prevent a zero at wrong index location */
982 if (mface->v3 == 0) {
983 static int corner_indices[4] = {1, 2, 0, 3};
985 SWAP(unsigned int, mface->v1, mface->v2);
986 SWAP(unsigned int, mface->v2, mface->v3);
989 CustomData_swap(fdata, mfindex, corner_indices);
993 if (mface->v3 == 0 || mface->v4 == 0) {
994 static int corner_indices[4] = {2, 3, 0, 1};
996 SWAP(unsigned int, mface->v1, mface->v3);
997 SWAP(unsigned int, mface->v2, mface->v4);
1000 CustomData_swap(fdata, mfindex, corner_indices);
1007 Mesh *BKE_mesh_from_object(Object *ob)
1010 if (ob == NULL) return NULL;
1011 if (ob->type == OB_MESH) return ob->data;
1015 void BKE_mesh_assign_object(Object *ob, Mesh *me)
1019 multires_force_update(ob);
1021 if (ob == NULL) return;
1023 if (ob->type == OB_MESH) {
1028 id_us_plus((ID *)me);
1031 test_object_materials(G.main, (ID *)me);
1033 test_object_modifiers(ob);
1036 void BKE_mesh_from_metaball(ListBase *lb, Mesh *me)
1040 MLoop *mloop, *allloop;
1042 const float *nors, *verts;
1046 if (dl == NULL) return;
1048 if (dl->type == DL_INDEX4) {
1049 mvert = CustomData_add_layer(&me->vdata, CD_MVERT, CD_CALLOC, NULL, dl->nr);
1050 allloop = mloop = CustomData_add_layer(&me->ldata, CD_MLOOP, CD_CALLOC, NULL, dl->parts * 4);
1051 mpoly = CustomData_add_layer(&me->pdata, CD_MPOLY, CD_CALLOC, NULL, dl->parts);
1055 me->totvert = dl->nr;
1056 me->totpoly = dl->parts;
1062 copy_v3_v3(mvert->co, verts);
1063 normal_float_to_short_v3(mvert->no, nors);
1072 int count = index[2] != index[3] ? 4 : 3;
1074 mloop[0].v = index[0];
1075 mloop[1].v = index[1];
1076 mloop[2].v = index[2];
1078 mloop[3].v = index[3];
1080 mpoly->totloop = count;
1081 mpoly->loopstart = (int)(mloop - allloop);
1082 mpoly->flag = ME_SMOOTH;
1087 me->totloop += count;
1091 BKE_mesh_update_customdata_pointers(me, true);
1093 BKE_mesh_calc_normals(me);
1095 BKE_mesh_calc_edges(me, true, false);
1100 * Specialized function to use when we _know_ existing edges don't overlap with poly edges.
1102 static void make_edges_mdata_extend(MEdge **r_alledge, int *r_totedge,
1103 const MPoly *mpoly, MLoop *mloop,
1106 int totedge = *r_totedge;
1109 unsigned int eh_reserve;
1113 eh_reserve = max_ii(totedge, BLI_EDGEHASH_SIZE_GUESS_FROM_POLYS(totpoly));
1114 eh = BLI_edgehash_new_ex(__func__, eh_reserve);
1116 for (i = 0, mp = mpoly; i < totpoly; i++, mp++) {
1117 BKE_mesh_poly_edgehash_insert(eh, mp, mloop + mp->loopstart);
1120 totedge_new = BLI_edgehash_size(eh);
1123 /* ensure that theres no overlap! */
1125 MEdge *medge = *r_alledge;
1126 for (i = 0; i < totedge; i++, medge++) {
1127 BLI_assert(BLI_edgehash_haskey(eh, medge->v1, medge->v2) == false);
1133 EdgeHashIterator *ehi;
1135 unsigned int e_index = totedge;
1137 *r_alledge = medge = (*r_alledge ? MEM_reallocN(*r_alledge, sizeof(MEdge) * (totedge + totedge_new)) :
1138 MEM_callocN(sizeof(MEdge) * totedge_new, __func__));
1141 totedge += totedge_new;
1144 for (ehi = BLI_edgehashIterator_new(eh);
1145 BLI_edgehashIterator_isDone(ehi) == false;
1146 BLI_edgehashIterator_step(ehi), ++medge, e_index++)
1148 BLI_edgehashIterator_getKey(ehi, &medge->v1, &medge->v2);
1149 BLI_edgehashIterator_setValue(ehi, SET_UINT_IN_POINTER(e_index));
1151 medge->crease = medge->bweight = 0;
1152 medge->flag = ME_EDGEDRAW | ME_EDGERENDER;
1154 BLI_edgehashIterator_free(ehi);
1156 *r_totedge = totedge;
1159 for (i = 0, mp = mpoly; i < totpoly; i++, mp++) {
1160 MLoop *l = &mloop[mp->loopstart];
1161 MLoop *l_prev = (l + (mp->totloop - 1));
1163 for (j = 0; j < mp->totloop; j++, l++) {
1164 /* lookup hashed edge index */
1165 l_prev->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(eh, l_prev->v, l->v));
1171 BLI_edgehash_free(eh, NULL);
1175 /* Initialize mverts, medges and, faces for converting nurbs to mesh and derived mesh */
1176 /* return non-zero on error */
1177 int BKE_mesh_nurbs_to_mdata(Object *ob, MVert **allvert, int *totvert,
1178 MEdge **alledge, int *totedge, MLoop **allloop, MPoly **allpoly,
1179 int *totloop, int *totpoly)
1181 ListBase disp = {NULL, NULL};
1183 if (ob->curve_cache) {
1184 disp = ob->curve_cache->disp;
1187 return BKE_mesh_nurbs_displist_to_mdata(ob, &disp,
1190 allloop, allpoly, NULL,
1194 /* BMESH: this doesn't calculate all edges from polygons,
1195 * only free standing edges are calculated */
1197 /* Initialize mverts, medges and, faces for converting nurbs to mesh and derived mesh */
1198 /* use specified dispbase */
1199 int BKE_mesh_nurbs_displist_to_mdata(Object *ob, ListBase *dispbase,
1200 MVert **allvert, int *_totvert,
1201 MEdge **alledge, int *_totedge,
1202 MLoop **allloop, MPoly **allpoly,
1204 int *_totloop, int *_totpoly)
1206 Curve *cu = ob->data;
1211 MLoopUV *mloopuv = NULL;
1214 int a, b, ofs, vertcount, startvert, totvert = 0, totedge = 0, totloop = 0, totvlak = 0;
1215 int p1, p2, p3, p4, *index;
1216 const bool conv_polys = ((CU_DO_2DFILL(cu) == false) || /* 2d polys are filled with DL_INDEX3 displists */
1217 (ob->type == OB_SURF)); /* surf polys are never filled */
1220 dl = dispbase->first;
1222 if (dl->type == DL_SEGM) {
1223 totvert += dl->parts * dl->nr;
1224 totedge += dl->parts * (dl->nr - 1);
1226 else if (dl->type == DL_POLY) {
1228 totvert += dl->parts * dl->nr;
1229 totedge += dl->parts * dl->nr;
1232 else if (dl->type == DL_SURF) {
1234 totvert += dl->parts * dl->nr;
1235 tot = (dl->parts - 1 + ((dl->flag & DL_CYCL_V) == 2)) * (dl->nr - 1 + (dl->flag & DL_CYCL_U));
1239 else if (dl->type == DL_INDEX3) {
1250 /* error("can't convert"); */
1251 /* Make Sure you check ob->data is a curve */
1255 *allvert = mvert = MEM_callocN(sizeof(MVert) * totvert, "nurbs_init mvert");
1256 *alledge = medge = MEM_callocN(sizeof(MEdge) * totedge, "nurbs_init medge");
1257 *allloop = mloop = MEM_callocN(sizeof(MLoop) * totvlak * 4, "nurbs_init mloop"); // totloop
1258 *allpoly = mpoly = MEM_callocN(sizeof(MPoly) * totvlak, "nurbs_init mloop");
1261 *alluv = mloopuv = MEM_callocN(sizeof(MLoopUV) * totvlak * 4, "nurbs_init mloopuv");
1263 /* verts and faces */
1266 dl = dispbase->first;
1268 const bool is_smooth = (dl->rt & CU_SMOOTH) != 0;
1270 if (dl->type == DL_SEGM) {
1271 startvert = vertcount;
1272 a = dl->parts * dl->nr;
1275 copy_v3_v3(mvert->co, data);
1281 for (a = 0; a < dl->parts; a++) {
1283 for (b = 1; b < dl->nr; b++) {
1284 medge->v1 = startvert + ofs + b - 1;
1285 medge->v2 = startvert + ofs + b;
1286 medge->flag = ME_LOOSEEDGE | ME_EDGERENDER | ME_EDGEDRAW;
1293 else if (dl->type == DL_POLY) {
1295 startvert = vertcount;
1296 a = dl->parts * dl->nr;
1299 copy_v3_v3(mvert->co, data);
1305 for (a = 0; a < dl->parts; a++) {
1307 for (b = 0; b < dl->nr; b++) {
1308 medge->v1 = startvert + ofs + b;
1309 if (b == dl->nr - 1) medge->v2 = startvert + ofs;
1310 else medge->v2 = startvert + ofs + b + 1;
1311 medge->flag = ME_LOOSEEDGE | ME_EDGERENDER | ME_EDGEDRAW;
1317 else if (dl->type == DL_INDEX3) {
1318 startvert = vertcount;
1322 copy_v3_v3(mvert->co, data);
1331 mloop[0].v = startvert + index[0];
1332 mloop[1].v = startvert + index[2];
1333 mloop[2].v = startvert + index[1];
1334 mpoly->loopstart = (int)(mloop - (*allloop));
1336 mpoly->mat_nr = dl->col;
1341 for (i = 0; i < 3; i++, mloopuv++) {
1342 mloopuv->uv[0] = (mloop[i].v - startvert) / (float)(dl->nr - 1);
1343 mloopuv->uv[1] = 0.0f;
1347 if (is_smooth) mpoly->flag |= ME_SMOOTH;
1353 else if (dl->type == DL_SURF) {
1354 startvert = vertcount;
1355 a = dl->parts * dl->nr;
1358 copy_v3_v3(mvert->co, data);
1364 for (a = 0; a < dl->parts; a++) {
1366 if ( (dl->flag & DL_CYCL_V) == 0 && a == dl->parts - 1) break;
1368 if (dl->flag & DL_CYCL_U) { /* p2 -> p1 -> */
1369 p1 = startvert + dl->nr * a; /* p4 -> p3 -> */
1370 p2 = p1 + dl->nr - 1; /* -----> next row */
1376 p2 = startvert + dl->nr * a;
1382 if ( (dl->flag & DL_CYCL_V) && a == dl->parts - 1) {
1383 p3 -= dl->parts * dl->nr;
1384 p4 -= dl->parts * dl->nr;
1387 for (; b < dl->nr; b++) {
1392 mpoly->loopstart = (int)(mloop - (*allloop));
1394 mpoly->mat_nr = dl->col;
1397 int orco_sizeu = dl->nr - 1;
1398 int orco_sizev = dl->parts - 1;
1401 /* exception as handled in convertblender.c too */
1402 if (dl->flag & DL_CYCL_U) {
1404 if (dl->flag & DL_CYCL_V)
1407 else if (dl->flag & DL_CYCL_V) {
1411 for (i = 0; i < 4; i++, mloopuv++) {
1412 /* find uv based on vertex index into grid array */
1413 int v = mloop[i].v - startvert;
1415 mloopuv->uv[0] = (v / dl->nr) / (float)orco_sizev;
1416 mloopuv->uv[1] = (v % dl->nr) / (float)orco_sizeu;
1418 /* cyclic correction */
1419 if ((i == 1 || i == 2) && mloopuv->uv[0] == 0.0f)
1420 mloopuv->uv[0] = 1.0f;
1421 if ((i == 0 || i == 1) && mloopuv->uv[1] == 0.0f)
1422 mloopuv->uv[1] = 1.0f;
1426 if (is_smooth) mpoly->flag |= ME_SMOOTH;
1442 make_edges_mdata_extend(alledge, &totedge,
1443 *allpoly, *allloop, totvlak);
1446 *_totpoly = totvlak;
1447 *_totloop = totloop;
1448 *_totedge = totedge;
1449 *_totvert = totvert;
1455 /* this may fail replacing ob->data, be sure to check ob->type */
1456 void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use_orco_uv)
1458 Main *bmain = G.main;
1460 DerivedMesh *dm = ob->derivedFinal;
1463 MVert *allvert = NULL;
1464 MEdge *alledge = NULL;
1465 MLoop *allloop = NULL;
1466 MLoopUV *alluv = NULL;
1467 MPoly *allpoly = NULL;
1468 int totvert, totedge, totloop, totpoly;
1473 if (BKE_mesh_nurbs_displist_to_mdata(ob, dispbase, &allvert, &totvert,
1474 &alledge, &totedge, &allloop,
1475 &allpoly, (use_orco_uv) ? &alluv : NULL,
1476 &totloop, &totpoly) != 0)
1478 /* Error initializing */
1483 me = BKE_mesh_add(G.main, "Mesh");
1484 me->totvert = totvert;
1485 me->totedge = totedge;
1486 me->totloop = totloop;
1487 me->totpoly = totpoly;
1489 me->mvert = CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, allvert, me->totvert);
1490 me->medge = CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, alledge, me->totedge);
1491 me->mloop = CustomData_add_layer(&me->ldata, CD_MLOOP, CD_ASSIGN, allloop, me->totloop);
1492 me->mpoly = CustomData_add_layer(&me->pdata, CD_MPOLY, CD_ASSIGN, allpoly, me->totpoly);
1495 const char *uvname = "Orco";
1496 me->mtpoly = CustomData_add_layer_named(&me->pdata, CD_MTEXPOLY, CD_DEFAULT, NULL, me->totpoly, uvname);
1497 me->mloopuv = CustomData_add_layer_named(&me->ldata, CD_MLOOPUV, CD_ASSIGN, alluv, me->totloop, uvname);
1500 BKE_mesh_calc_normals(me);
1503 me = BKE_mesh_add(G.main, "Mesh");
1504 DM_to_mesh(dm, me, ob, CD_MASK_MESH, false);
1507 me->totcol = cu->totcol;
1510 BKE_mesh_texspace_calc(me);
1516 BKE_libblock_free(bmain, ob->data);
1522 ob1 = bmain->object.first;
1524 if (ob1->data == cu) {
1525 ob1->type = OB_MESH;
1527 ob1->data = ob->data;
1528 id_us_plus((ID *)ob->data);
1534 void BKE_mesh_from_nurbs(Object *ob)
1536 Curve *cu = (Curve *) ob->data;
1537 bool use_orco_uv = (cu->flag & CU_UV_ORCO) != 0;
1538 ListBase disp = {NULL, NULL};
1540 if (ob->curve_cache) {
1541 disp = ob->curve_cache->disp;
1544 BKE_mesh_from_nurbs_displist(ob, &disp, use_orco_uv);
1547 typedef struct EdgeLink {
1548 struct EdgeLink *next, *prev;
1552 typedef struct VertLink {
1557 static void prependPolyLineVert(ListBase *lb, unsigned int index)
1559 VertLink *vl = MEM_callocN(sizeof(VertLink), "VertLink");
1561 BLI_addhead(lb, vl);
1564 static void appendPolyLineVert(ListBase *lb, unsigned int index)
1566 VertLink *vl = MEM_callocN(sizeof(VertLink), "VertLink");
1568 BLI_addtail(lb, vl);
1571 void BKE_mesh_to_curve_nurblist(DerivedMesh *dm, ListBase *nurblist, const int edge_users_test)
1573 MVert *mvert = dm->getVertArray(dm);
1574 MEdge *med, *medge = dm->getEdgeArray(dm);
1575 MPoly *mp, *mpoly = dm->getPolyArray(dm);
1576 MLoop *mloop = dm->getLoopArray(dm);
1578 int dm_totedge = dm->getNumEdges(dm);
1579 int dm_totpoly = dm->getNumPolys(dm);
1583 /* only to detect edge polylines */
1586 ListBase edges = {NULL, NULL};
1588 /* get boundary edges */
1589 edge_users = MEM_callocN(sizeof(int) * dm_totedge, __func__);
1590 for (i = 0, mp = mpoly; i < dm_totpoly; i++, mp++) {
1591 MLoop *ml = &mloop[mp->loopstart];
1593 for (j = 0; j < mp->totloop; j++, ml++) {
1594 edge_users[ml->e]++;
1598 /* create edges from all faces (so as to find edges not in any faces) */
1600 for (i = 0; i < dm_totedge; i++, med++) {
1601 if (edge_users[i] == edge_users_test) {
1602 EdgeLink *edl = MEM_callocN(sizeof(EdgeLink), "EdgeLink");
1605 BLI_addtail(&edges, edl); totedges++;
1608 MEM_freeN(edge_users);
1611 while (edges.first) {
1612 /* each iteration find a polyline and add this as a nurbs poly spline */
1614 ListBase polyline = {NULL, NULL}; /* store a list of VertLink's */
1615 bool closed = false;
1617 MEdge *med_current = ((EdgeLink *)edges.last)->edge;
1618 unsigned int startVert = med_current->v1;
1619 unsigned int endVert = med_current->v2;
1622 appendPolyLineVert(&polyline, startVert); totpoly++;
1623 appendPolyLineVert(&polyline, endVert); totpoly++;
1624 BLI_freelinkN(&edges, edges.last); totedges--;
1626 while (ok) { /* while connected edges are found... */
1627 EdgeLink *edl = edges.last;
1630 EdgeLink *edl_prev = edl->prev;
1634 if (med->v1 == endVert) {
1636 appendPolyLineVert(&polyline, med->v2); totpoly++;
1637 BLI_freelinkN(&edges, edl); totedges--;
1640 else if (med->v2 == endVert) {
1642 appendPolyLineVert(&polyline, endVert); totpoly++;
1643 BLI_freelinkN(&edges, edl); totedges--;
1646 else if (med->v1 == startVert) {
1647 startVert = med->v2;
1648 prependPolyLineVert(&polyline, startVert); totpoly++;
1649 BLI_freelinkN(&edges, edl); totedges--;
1652 else if (med->v2 == startVert) {
1653 startVert = med->v1;
1654 prependPolyLineVert(&polyline, startVert); totpoly++;
1655 BLI_freelinkN(&edges, edl); totedges--;
1663 /* Now we have a polyline, make into a curve */
1664 if (startVert == endVert) {
1665 BLI_freelinkN(&polyline, polyline.last);
1676 /* create new 'nurb' within the curve */
1677 nu = (Nurb *)MEM_callocN(sizeof(Nurb), "MeshNurb");
1679 nu->pntsu = totpoly;
1682 nu->flagu = CU_NURB_ENDPOINT | (closed ? CU_NURB_CYCLIC : 0); /* endpoint */
1685 nu->bp = (BPoint *)MEM_callocN(sizeof(BPoint) * totpoly, "bpoints");
1688 vl = polyline.first;
1689 for (i = 0, bp = nu->bp; i < totpoly; i++, bp++, vl = (VertLink *)vl->next) {
1690 copy_v3_v3(bp->vec, mvert[vl->index].co);
1692 bp->radius = bp->weight = 1.0;
1694 BLI_freelistN(&polyline);
1696 /* add nurb to curve */
1697 BLI_addtail(nurblist, nu);
1699 /* --- done with nurbs --- */
1704 void BKE_mesh_to_curve(Scene *scene, Object *ob)
1706 /* make new mesh data from the original copy */
1707 DerivedMesh *dm = mesh_get_derived_final(scene, ob, CD_MASK_MESH);
1708 ListBase nurblist = {NULL, NULL};
1709 bool needsFree = false;
1711 BKE_mesh_to_curve_nurblist(dm, &nurblist, 0);
1712 BKE_mesh_to_curve_nurblist(dm, &nurblist, 1);
1714 if (nurblist.first) {
1715 Curve *cu = BKE_curve_add(G.main, ob->id.name + 2, OB_CURVE);
1718 cu->nurb = nurblist;
1720 ((Mesh *)ob->data)->id.us--;
1722 ob->type = OB_CURVE;
1724 /* curve objects can't contain DM in usual cases, we could free memory */
1728 dm->needsFree = needsFree;
1732 ob->derivedFinal = NULL;
1734 /* curve object could have got bounding box only in special cases */
1742 void BKE_mesh_material_index_remove(Mesh *me, short index)
1748 for (mp = me->mpoly, i = 0; i < me->totpoly; i++, mp++) {
1749 if (mp->mat_nr && mp->mat_nr >= index) {
1754 for (mf = me->mface, i = 0; i < me->totface; i++, mf++) {
1755 if (mf->mat_nr && mf->mat_nr >= index) {
1761 void BKE_mesh_material_index_clear(Mesh *me)
1767 for (mp = me->mpoly, i = 0; i < me->totpoly; i++, mp++) {
1771 for (mf = me->mface, i = 0; i < me->totface; i++, mf++) {
1776 void BKE_mesh_material_remap(Mesh *me, const unsigned int *remap, unsigned int remap_len)
1778 const short remap_len_short = (short)remap_len;
1780 #define MAT_NR_REMAP(n) \
1781 if (n < remap_len_short) { \
1782 BLI_assert(n >= 0 && remap[n] < remap_len_short); \
1786 if (me->edit_btmesh) {
1787 BMEditMesh *em = me->edit_btmesh;
1791 BM_ITER_MESH(efa, &iter, em->bm, BM_FACES_OF_MESH) {
1792 MAT_NR_REMAP(efa->mat_nr);
1797 for (i = 0; i < me->totpoly; i++) {
1798 MAT_NR_REMAP(me->mpoly[i].mat_nr);
1806 void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth)
1808 Mesh *me = meshOb->data;
1811 for (i = 0; i < me->totpoly; i++) {
1812 MPoly *mp = &((MPoly *) me->mpoly)[i];
1815 mp->flag |= ME_SMOOTH;
1818 mp->flag &= ~ME_SMOOTH;
1822 for (i = 0; i < me->totface; i++) {
1823 MFace *mf = &((MFace *) me->mface)[i];
1826 mf->flag |= ME_SMOOTH;
1829 mf->flag &= ~ME_SMOOTH;
1835 * Return a newly MEM_malloc'd array of all the mesh vertex locations
1836 * \note \a r_numVerts may be NULL
1838 float (*BKE_mesh_vertexCos_get(const Mesh *me, int *r_numVerts))[3]
1840 int i, numVerts = me->totvert;
1841 float (*cos)[3] = MEM_mallocN(sizeof(*cos) * numVerts, "vertexcos1");
1843 if (r_numVerts) *r_numVerts = numVerts;
1844 for (i = 0; i < numVerts; i++)
1845 copy_v3_v3(cos[i], me->mvert[i].co);
1851 * Find the index of the loop in 'poly' which references vertex,
1852 * returns -1 if not found
1854 int poly_find_loop_from_vert(
1855 const MPoly *poly, const MLoop *loopstart,
1859 for (j = 0; j < poly->totloop; j++, loopstart++) {
1860 if (loopstart->v == vert)
1868 * Fill \a r_adj with the loop indices in \a poly adjacent to the
1869 * vertex. Returns the index of the loop matching vertex, or -1 if the
1870 * vertex is not in \a poly
1872 int poly_get_adj_loops_from_vert(
1873 unsigned r_adj[2], const MPoly *poly,
1874 const MLoop *mloop, unsigned vert)
1876 int corner = poly_find_loop_from_vert(poly,
1877 &mloop[poly->loopstart],
1881 #if 0 /* unused - this loop */
1882 const MLoop *ml = &mloop[poly->loopstart + corner];
1885 /* vertex was found */
1886 r_adj[0] = ME_POLY_LOOP_PREV(mloop, poly, corner)->v;
1887 r_adj[1] = ME_POLY_LOOP_NEXT(mloop, poly, corner)->v;
1894 * Return the index of the edge vert that is not equal to \a v. If
1895 * neither edge vertex is equal to \a v, returns -1.
1897 int BKE_mesh_edge_other_vert(const MEdge *e, int v)
1901 else if (e->v2 == v)
1907 /* basic vertex data functions */
1908 bool BKE_mesh_minmax(Mesh *me, float r_min[3], float r_max[3])
1910 int i = me->totvert;
1912 for (mvert = me->mvert; i--; mvert++) {
1913 minmax_v3v3_v3(r_min, r_max, mvert->co);
1916 return (me->totvert != 0);
1919 void BKE_mesh_transform(Mesh *me, float mat[4][4], bool do_keys)
1922 MVert *mvert = me->mvert;
1924 for (i = 0; i < me->totvert; i++, mvert++)
1925 mul_m4_v3(mat, mvert->co);
1927 if (do_keys && me->key) {
1929 for (kb = me->key->block.first; kb; kb = kb->next) {
1930 float *fp = kb->data;
1931 for (i = kb->totelem; i--; fp += 3) {
1937 /* don't update normals, caller can do this explicitly */
1940 void BKE_mesh_translate(Mesh *me, const float offset[3], const bool do_keys)
1942 int i = me->totvert;
1944 for (mvert = me->mvert; i--; mvert++) {
1945 add_v3_v3(mvert->co, offset);
1948 if (do_keys && me->key) {
1950 for (kb = me->key->block.first; kb; kb = kb->next) {
1951 float *fp = kb->data;
1952 for (i = kb->totelem; i--; fp += 3) {
1953 add_v3_v3(fp, offset);
1959 void BKE_mesh_ensure_navmesh(Mesh *me)
1961 if (!CustomData_has_layer(&me->pdata, CD_RECAST)) {
1963 int numFaces = me->totpoly;
1965 recastData = (int *)MEM_mallocN(numFaces * sizeof(int), __func__);
1966 for (i = 0; i < numFaces; i++) {
1967 recastData[i] = i + 1;
1969 CustomData_add_layer_named(&me->pdata, CD_RECAST, CD_ASSIGN, recastData, numFaces, "recastData");
1973 void BKE_mesh_tessface_calc(Mesh *mesh)
1975 mesh->totface = BKE_mesh_recalc_tessellation(&mesh->fdata, &mesh->ldata, &mesh->pdata,
1977 mesh->totface, mesh->totloop, mesh->totpoly,
1978 /* calc normals right after, don't copy from polys here */
1981 BKE_mesh_update_customdata_pointers(mesh, true);
1984 void BKE_mesh_tessface_ensure(Mesh *mesh)
1986 if (mesh->totpoly && mesh->totface == 0) {
1987 BKE_mesh_tessface_calc(mesh);
1991 void BKE_mesh_tessface_clear(Mesh *mesh)
1993 mesh_tessface_clear_intern(mesh, true);
1996 void BKE_mesh_do_versions_cd_flag_init(Mesh *mesh)
1998 if (UNLIKELY(mesh->cd_flag)) {
2006 for (mv = mesh->mvert, i = 0; i < mesh->totvert; mv++, i++) {
2007 if (mv->bweight != 0) {
2008 mesh->cd_flag |= ME_CDFLAG_VERT_BWEIGHT;
2013 for (med = mesh->medge, i = 0; i < mesh->totedge; med++, i++) {
2014 if (med->bweight != 0) {
2015 mesh->cd_flag |= ME_CDFLAG_EDGE_BWEIGHT;
2016 if (mesh->cd_flag & ME_CDFLAG_EDGE_CREASE) {
2020 if (med->crease != 0) {
2021 mesh->cd_flag |= ME_CDFLAG_EDGE_CREASE;
2022 if (mesh->cd_flag & ME_CDFLAG_EDGE_BWEIGHT) {
2032 /* -------------------------------------------------------------------- */
2033 /* MSelect functions (currently used in weight paint mode) */
2035 void BKE_mesh_mselect_clear(Mesh *me)
2038 MEM_freeN(me->mselect);
2044 void BKE_mesh_mselect_validate(Mesh *me)
2046 MSelect *mselect_src, *mselect_dst;
2049 if (me->totselect == 0)
2052 mselect_src = me->mselect;
2053 mselect_dst = MEM_mallocN(sizeof(MSelect) * (me->totselect), "Mesh selection history");
2055 for (i_src = 0, i_dst = 0; i_src < me->totselect; i_src++) {
2056 int index = mselect_src[i_src].index;
2057 switch (mselect_src[i_src].type) {
2060 if (me->mvert[index].flag & SELECT) {
2061 mselect_dst[i_dst] = mselect_src[i_src];
2068 if (me->medge[index].flag & SELECT) {
2069 mselect_dst[i_dst] = mselect_src[i_src];
2076 if (me->mpoly[index].flag & SELECT) {
2077 mselect_dst[i_dst] = mselect_src[i_src];
2090 MEM_freeN(mselect_src);
2093 MEM_freeN(mselect_dst);
2096 else if (i_dst != me->totselect) {
2097 mselect_dst = MEM_reallocN(mselect_dst, sizeof(MSelect) * i_dst);
2100 me->totselect = i_dst;
2101 me->mselect = mselect_dst;
2106 * Return the index within me->mselect, or -1
2108 int BKE_mesh_mselect_find(Mesh *me, int index, int type)
2112 BLI_assert(ELEM(type, ME_VSEL, ME_ESEL, ME_FSEL));
2114 for (i = 0; i < me->totselect; i++) {
2115 if ((me->mselect[i].index == index) &&
2116 (me->mselect[i].type == type))
2126 * Return The index of the active element.
2128 int BKE_mesh_mselect_active_get(Mesh *me, int type)
2130 BLI_assert(ELEM(type, ME_VSEL, ME_ESEL, ME_FSEL));
2132 if (me->totselect) {
2133 if (me->mselect[me->totselect - 1].type == type) {
2134 return me->mselect[me->totselect - 1].index;
2140 void BKE_mesh_mselect_active_set(Mesh *me, int index, int type)
2142 const int msel_index = BKE_mesh_mselect_find(me, index, type);
2144 if (msel_index == -1) {
2145 /* add to the end */
2146 me->mselect = MEM_reallocN(me->mselect, sizeof(MSelect) * (me->totselect + 1));
2147 me->mselect[me->totselect].index = index;
2148 me->mselect[me->totselect].type = type;
2151 else if (msel_index != me->totselect - 1) {
2152 /* move to the end */
2153 SWAP(MSelect, me->mselect[msel_index], me->mselect[me->totselect - 1]);
2156 BLI_assert((me->mselect[me->totselect - 1].index == index) &&
2157 (me->mselect[me->totselect - 1].type == type));
2160 void BKE_mesh_calc_normals_split(Mesh *mesh)
2162 float (*r_loopnors)[3];
2163 float (*polynors)[3];
2164 short (*clnors)[2] = NULL;
2165 bool free_polynors = false;
2167 if (CustomData_has_layer(&mesh->ldata, CD_NORMAL)) {
2168 r_loopnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL);
2169 memset(r_loopnors, 0, sizeof(float[3]) * mesh->totloop);
2172 r_loopnors = CustomData_add_layer(&mesh->ldata, CD_NORMAL, CD_CALLOC, NULL, mesh->totloop);
2173 CustomData_set_layer_flag(&mesh->ldata, CD_NORMAL, CD_FLAG_TEMPORARY);
2177 clnors = CustomData_get_layer(&mesh->ldata, CD_CUSTOMLOOPNORMAL);
2179 if (CustomData_has_layer(&mesh->pdata, CD_NORMAL)) {
2180 /* This assume that layer is always up to date, not sure this is the case (esp. in Edit mode?)... */
2181 polynors = CustomData_get_layer(&mesh->pdata, CD_NORMAL);
2182 free_polynors = false;
2185 polynors = MEM_mallocN(sizeof(float[3]) * mesh->totpoly, __func__);
2186 BKE_mesh_calc_normals_poly(mesh->mvert, mesh->totvert, mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly,
2188 free_polynors = true;
2191 BKE_mesh_normals_loop_split(
2192 mesh->mvert, mesh->totvert, mesh->medge, mesh->totedge,
2193 mesh->mloop, r_loopnors, mesh->totloop, mesh->mpoly, (const float (*)[3])polynors, mesh->totpoly,
2194 (mesh->flag & ME_AUTOSMOOTH) != 0, mesh->smoothresh, NULL, clnors, NULL);
2196 if (free_polynors) {
2197 MEM_freeN(polynors);
2201 /* Spli faces based on the edge angle.
2202 * Matches behavior of face splitting in render engines.
2204 void BKE_mesh_split_faces(Mesh *mesh)
2206 const int num_verts = mesh->totvert;
2207 const int num_edges = mesh->totedge;
2208 const int num_polys = mesh->totpoly;
2209 MVert *mvert = mesh->mvert;
2210 MEdge *medge = mesh->medge;
2211 MLoop *mloop = mesh->mloop;
2212 MPoly *mpoly = mesh->mpoly;
2214 int poly, num_new_verts = 0;
2215 if ((mesh->flag & ME_AUTOSMOOTH) == 0) {
2218 BKE_mesh_tessface_clear(mesh);
2219 /* Compute loop normals if needed. */
2220 if (!CustomData_has_layer(&mesh->ldata, CD_NORMAL)) {
2221 BKE_mesh_calc_normals_split(mesh);
2223 lnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL);
2225 for (poly = 0; poly < num_polys; poly++) {
2226 MPoly *mp = &mpoly[poly];
2228 for (loop = 0; loop < mp->totloop; loop++) {
2229 MLoop *ml = &mloop[mp->loopstart + loop];
2230 MVert *mv = &mvert[ml->v];
2232 normal_short_to_float_v3(vn, mv->no);
2233 if (!equals_v3v3(vn, lnors[mp->loopstart + loop])) {
2238 if (num_new_verts == 0) {
2239 /* No new vertices are to be added, can do early exit. */
2243 mesh->totvert += num_new_verts;
2244 mesh->totedge += 2 * num_new_verts;
2245 mvert = mesh->mvert = MEM_reallocN(mesh->mvert,
2246 sizeof(MVert) * mesh->totvert);
2247 medge = mesh->medge = MEM_reallocN(mesh->medge,
2248 sizeof(MEdge) * mesh->totedge);
2249 CustomData_set_layer(&mesh->vdata, CD_MVERT, mesh->mvert);
2250 CustomData_set_layer(&mesh->edata, CD_MEDGE, mesh->medge);
2252 for (poly = 0; poly < num_polys; poly++) {
2253 MPoly *mp = &mpoly[poly];
2255 for (loop = 0; loop < mp->totloop; loop++) {
2256 int poly_loop = mp->loopstart + loop;
2257 MLoop *ml = &mloop[poly_loop];
2258 MVert *mv = &mvert[ml->v];
2260 normal_short_to_float_v3(vn, mv->no);
2261 if (!equals_v3v3(vn, lnors[mp->loopstart + loop])) {
2262 int poly_loop_prev = mp->loopstart + (loop + mp->totloop - 1) % mp->totloop;
2263 MLoop *ml_prev = &mloop[poly_loop_prev];
2264 int new_edge_prev, new_edge;
2265 /* Cretae new vertex. */
2266 int new_vert = num_verts + num_new_verts;
2267 CustomData_copy_data(&mesh->vdata, &mesh->vdata,
2268 ml->v, new_vert, 1);
2269 normal_float_to_short_v3(mvert[new_vert].no,
2271 /* Create new edges. */
2272 new_edge_prev = num_edges + 2 * num_new_verts;
2273 new_edge = num_edges + 2 * num_new_verts + 1;
2274 CustomData_copy_data(&mesh->edata, &mesh->edata,
2275 ml_prev->e, new_edge_prev, 1);
2276 CustomData_copy_data(&mesh->edata, &mesh->edata,
2277 ml->e, new_edge, 1);
2278 if (medge[new_edge_prev].v1 == ml->v) {
2279 medge[new_edge_prev].v1 = new_vert;
2282 medge[new_edge_prev].v2 = new_vert;
2284 if (medge[new_edge].v1 == ml->v) {
2285 medge[new_edge].v1 = new_vert;
2288 medge[new_edge].v2 = new_vert;
2292 ml_prev->e = new_edge_prev;
2300 /* settings: 1 - preview, 2 - render */
2301 Mesh *BKE_mesh_new_from_object(
2302 Main *bmain, Scene *sce, Object *ob,
2303 int apply_modifiers, int settings, int calc_tessface, int calc_undeformed)
2306 Curve *tmpcu = NULL, *copycu;
2307 Object *tmpobj = NULL;
2308 int render = settings == eModifierMode_Render, i;
2309 int cage = !apply_modifiers;
2311 /* perform the mesh extraction based on type */
2317 ListBase dispbase = {NULL, NULL};
2318 DerivedMesh *derivedFinal = NULL;
2321 /* copies object and modifiers (but not the data) */
2322 tmpobj = BKE_object_copy_ex(bmain, ob, true);
2323 tmpcu = (Curve *)tmpobj->data;
2326 /* if getting the original caged mesh, delete object modifiers */
2328 BKE_object_free_modifiers(tmpobj);
2330 /* copies the data */
2331 copycu = tmpobj->data = BKE_curve_copy((Curve *) ob->data);
2333 /* temporarily set edit so we get updates from edit mode, but
2334 * also because for text datablocks copying it while in edit
2335 * mode gives invalid data structures */
2336 copycu->editfont = tmpcu->editfont;
2337 copycu->editnurb = tmpcu->editnurb;
2339 /* get updated display list, and convert to a mesh */
2340 BKE_displist_make_curveTypes_forRender(sce, tmpobj, &dispbase, &derivedFinal, false, render);
2342 copycu->editfont = NULL;
2343 copycu->editnurb = NULL;
2345 tmpobj->derivedFinal = derivedFinal;
2347 /* convert object type to mesh */
2348 uv_from_orco = (tmpcu->flag & CU_UV_ORCO) != 0;
2349 BKE_mesh_from_nurbs_displist(tmpobj, &dispbase, uv_from_orco);
2351 tmpmesh = tmpobj->data;
2353 BKE_displist_free(&dispbase);
2355 /* BKE_mesh_from_nurbs changes the type to a mesh, check it worked.
2356 * if it didn't the curve did not have any segments or otherwise
2357 * would have generated an empty mesh */
2358 if (tmpobj->type != OB_MESH) {
2359 BKE_libblock_free_us(bmain, tmpobj);
2363 BKE_mesh_texspace_copy_from_object(tmpmesh, ob);
2365 BKE_libblock_free_us(bmain, tmpobj);
2371 /* metaballs don't have modifiers, so just convert to mesh */
2372 Object *basis_ob = BKE_mball_basis_find(sce, ob);
2373 /* todo, re-generatre for render-res */
2374 /* metaball_polygonize(scene, ob) */
2377 return NULL; /* only do basis metaball */
2379 tmpmesh = BKE_mesh_add(bmain, "Mesh");
2380 /* BKE_mesh_add gives us a user count we don't need */
2384 ListBase disp = {NULL, NULL};
2385 /* TODO(sergey): This is gonna to work for until EvaluationContext
2386 * only contains for_render flag. As soon as CoW is
2387 * implemented, this is to be rethinked.
2389 EvaluationContext eval_ctx = {0};
2390 eval_ctx.mode = DAG_EVAL_RENDER;
2391 BKE_displist_make_mball_forRender(&eval_ctx, sce, ob, &disp);
2392 BKE_mesh_from_metaball(&disp, tmpmesh);
2393 BKE_displist_free(&disp);
2396 ListBase disp = {NULL, NULL};
2397 if (ob->curve_cache) {
2398 disp = ob->curve_cache->disp;
2400 BKE_mesh_from_metaball(&disp, tmpmesh);
2403 BKE_mesh_texspace_copy_from_object(tmpmesh, ob);
2409 /* copies object and modifiers (but not the data) */
2411 /* copies the data */
2412 tmpmesh = BKE_mesh_copy_ex(bmain, ob->data);
2413 /* if not getting the original caged mesh, get final derived mesh */
2416 /* Make a dummy mesh, saves copying */
2418 /* CustomDataMask mask = CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL; */
2419 CustomDataMask mask = CD_MASK_MESH; /* this seems more suitable, exporter,
2420 * for example, needs CD_MASK_MDEFORMVERT */
2422 if (calc_undeformed)
2423 mask |= CD_MASK_ORCO;
2425 /* Write the display mesh into the dummy mesh */
2427 dm = mesh_create_derived_render(sce, ob, mask);
2429 dm = mesh_create_derived_view(sce, ob, mask);
2431 tmpmesh = BKE_mesh_add(bmain, "Mesh");
2432 DM_to_mesh(dm, tmpmesh, ob, mask, true);
2435 /* BKE_mesh_add/copy gives us a user count we don't need */
2440 /* "Object does not have geometry data") */
2444 /* Copy materials to new mesh */
2449 tmpmesh->totcol = tmpcu->totcol;
2451 /* free old material list (if it exists) and adjust user counts */
2453 for (i = tmpcu->totcol; i-- > 0; ) {
2454 /* are we an object material or data based? */
2456 tmpmesh->mat[i] = ob->matbits[i] ? ob->mat[i] : tmpcu->mat[i];
2458 if (tmpmesh->mat[i]) {
2459 tmpmesh->mat[i]->id.us++;
2466 /* Crashes when assigning the new material, not sure why */
2468 tmpmb = (MetaBall *)ob->data;
2469 tmpmesh->totcol = tmpmb->totcol;
2471 /* free old material list (if it exists) and adjust user counts */
2473 for (i = tmpmb->totcol; i-- > 0; ) {
2474 tmpmesh->mat[i] = tmpmb->mat[i]; /* CRASH HERE ??? */
2475 if (tmpmesh->mat[i]) {
2476 tmpmb->mat[i]->id.us++;
2485 Mesh *origmesh = ob->data;
2486 tmpmesh->flag = origmesh->flag;
2487 tmpmesh->mat = MEM_dupallocN(origmesh->mat);
2488 tmpmesh->totcol = origmesh->totcol;
2489 tmpmesh->smoothresh = origmesh->smoothresh;
2490 if (origmesh->mat) {
2491 for (i = origmesh->totcol; i-- > 0; ) {
2492 /* are we an object material or data based? */
2493 tmpmesh->mat[i] = ob->matbits[i] ? ob->mat[i] : origmesh->mat[i];
2495 if (tmpmesh->mat[i]) {
2496 tmpmesh->mat[i]->id.us++;
2502 } /* end copy materials */
2504 if (calc_tessface) {
2505 /* cycles and exporters rely on this still */
2506 BKE_mesh_tessface_ensure(tmpmesh);
2509 /* make sure materials get updated in objects */
2510 test_object_materials(bmain, &tmpmesh->id);