bb90a5b584e190e74cbaf025373610e48f52001f
[blender.git] / source / blender / draw / intern / draw_cache_impl_mesh.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2017 by Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, Mike Erwin, Dalai Felinto
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file draw_cache_impl_mesh.c
27  *  \ingroup draw
28  *
29  * \brief Mesh API for render engines
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_buffer.h"
35 #include "BLI_utildefines.h"
36 #include "BLI_math_vector.h"
37 #include "BLI_math_bits.h"
38 #include "BLI_math_color.h"
39 #include "BLI_string.h"
40 #include "BLI_alloca.h"
41 #include "BLI_edgehash.h"
42
43 #include "DNA_mesh_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_scene_types.h"
48
49 #include "BKE_customdata.h"
50 #include "BKE_deform.h"
51 #include "BKE_editmesh.h"
52 #include "BKE_editmesh_cache.h"
53 #include "BKE_editmesh_tangent.h"
54 #include "BKE_mesh.h"
55 #include "BKE_mesh_tangent.h"
56 #include "BKE_mesh_runtime.h"
57 #include "BKE_object.h"
58 #include "BKE_object_deform.h"
59 #include "BKE_colorband.h"
60 #include "BKE_cdderivedmesh.h"
61
62 #include "DEG_depsgraph_query.h"
63
64 #include "bmesh.h"
65
66 #include "GPU_batch.h"
67 #include "GPU_batch_presets.h"
68 #include "GPU_draw.h"
69 #include "GPU_material.h"
70
71 #include "DRW_render.h"
72
73 #include "ED_image.h"
74 #include "ED_mesh.h"
75 #include "ED_uvedit.h"
76
77 #include "draw_cache_impl.h"  /* own include */
78
79
80 static void mesh_batch_cache_clear(Mesh *me);
81
82 /* Vertex Group Selection and display options */
83 typedef struct DRW_MeshWeightState {
84         int defgroup_active;
85         int defgroup_len;
86
87         short flags;
88         char alert_mode;
89
90         /* Set of all selected bones for Multipaint. */
91         bool *defgroup_sel; /* [defgroup_len] */
92         int   defgroup_sel_count;
93 } DRW_MeshWeightState;
94
95 /* DRW_MeshWeightState.flags */
96 enum {
97         DRW_MESH_WEIGHT_STATE_MULTIPAINT          = (1 << 0),
98         DRW_MESH_WEIGHT_STATE_AUTO_NORMALIZE      = (1 << 1),
99 };
100
101 /* ---------------------------------------------------------------------- */
102
103 /** \name Mesh/BMesh Interface (direct access to basic data).
104  * \{ */
105
106 static int mesh_render_verts_len_get(Mesh *me)
107 {
108         return me->edit_btmesh ? me->edit_btmesh->bm->totvert : me->totvert;
109 }
110
111 static int mesh_render_edges_len_get(Mesh *me)
112 {
113         return me->edit_btmesh ? me->edit_btmesh->bm->totedge : me->totedge;
114 }
115
116 static int mesh_render_looptri_len_get(Mesh *me)
117 {
118         return me->edit_btmesh ? me->edit_btmesh->tottri : poly_to_tri_count(me->totpoly, me->totloop);
119 }
120
121 static int mesh_render_polys_len_get(Mesh *me)
122 {
123         return me->edit_btmesh ? me->edit_btmesh->bm->totface : me->totpoly;
124 }
125
126 static int mesh_render_mat_len_get(Mesh *me)
127 {
128         return MAX2(1, me->totcol);
129 }
130
131 static int UNUSED_FUNCTION(mesh_render_loops_len_get)(Mesh *me)
132 {
133         return me->edit_btmesh ? me->edit_btmesh->bm->totloop : me->totloop;
134 }
135
136 /** \} */
137
138
139 /* ---------------------------------------------------------------------- */
140
141 /** \name Mesh/BMesh Interface (indirect, partially cached access to complex data).
142  * \{ */
143
144 typedef struct EdgeAdjacentPolys {
145         int count;
146         int face_index[2];
147 } EdgeAdjacentPolys;
148
149 typedef struct EdgeAdjacentVerts {
150         int vert_index[2]; /* -1 if none */
151 } EdgeAdjacentVerts;
152
153 typedef struct EdgeDrawAttr {
154         uchar v_flag;
155         uchar e_flag;
156         uchar crease;
157         uchar bweight;
158 } EdgeDrawAttr;
159
160 typedef struct MeshRenderData {
161         int types;
162
163         int vert_len;
164         int edge_len;
165         int tri_len;
166         int loop_len;
167         int poly_len;
168         int mat_len;
169         int loose_vert_len;
170         int loose_edge_len;
171
172         /* Support for mapped mesh data. */
173         struct {
174                 /* Must be set if we want to get mapped data. */
175                 bool use;
176                 bool supported;
177
178                 Mesh *me_cage;
179
180                 int vert_len;
181                 int edge_len;
182                 int tri_len;
183                 int loop_len;
184                 int poly_len;
185
186                 int *loose_verts;
187                 int  loose_vert_len;
188
189                 int *loose_edges;
190                 int  loose_edge_len;
191
192                 /* origindex layers */
193                 int *v_origindex;
194                 int *e_origindex;
195                 int *l_origindex;
196                 int *p_origindex;
197         } mapped;
198
199         BMEditMesh *edit_bmesh;
200         struct EditMeshData *edit_data;
201
202         Mesh *me;
203
204         MVert *mvert;
205         const MEdge *medge;
206         const MLoop *mloop;
207         const MPoly *mpoly;
208         float (*orco)[3];  /* vertex coordinates normalized to bounding box */
209         bool is_orco_allocated;
210         MDeformVert *dvert;
211         MLoopUV *mloopuv;
212         MLoopCol *mloopcol;
213         float (*loop_normals)[3];
214
215         /* CustomData 'cd' cache for efficient access. */
216         struct {
217                 struct {
218                         MLoopUV **uv;
219                         int       uv_len;
220                         int       uv_active;
221
222                         MLoopCol **vcol;
223                         int        vcol_len;
224                         int        vcol_active;
225
226                         float (**tangent)[4];
227                         int      tangent_len;
228                         int      tangent_active;
229
230                         bool *auto_vcol;
231                 } layers;
232
233                 /* Custom-data offsets (only needed for BMesh access) */
234                 struct {
235                         int crease;
236                         int bweight;
237                         int *uv;
238                         int *vcol;
239 #ifdef WITH_FREESTYLE
240                         int freestyle_edge;
241                         int freestyle_face;
242 #endif
243                 } offset;
244
245                 struct {
246                         char (*auto_mix)[32];
247                         char (*uv)[32];
248                         char (*vcol)[32];
249                         char (*tangent)[32];
250                 } uuid;
251
252                 /* for certain cases we need an output loop-data storage (bmesh tangents) */
253                 struct {
254                         CustomData ldata;
255                         /* grr, special case variable (use in place of 'dm->tangent_mask') */
256                         short tangent_mask;
257                 } output;
258         } cd;
259
260         BMVert *eve_act;
261         BMEdge *eed_act;
262         BMFace *efa_act;
263
264         /* Data created on-demand (usually not for bmesh-based data). */
265         EdgeAdjacentPolys *edges_adjacent_polys;
266         MLoopTri *mlooptri;
267         int *loose_edges;
268         int *loose_verts;
269
270         float (*poly_normals)[3];
271         float (*vert_weight);
272         char (*vert_color)[3];
273         GPUPackedNormal *poly_normals_pack;
274         GPUPackedNormal *vert_normals_pack;
275         bool *edge_select_bool;
276         bool *edge_visible_bool;
277 } MeshRenderData;
278
279 enum {
280         MR_DATATYPE_VERT       = 1 << 0,
281         MR_DATATYPE_EDGE       = 1 << 1,
282         MR_DATATYPE_LOOPTRI    = 1 << 2,
283         MR_DATATYPE_LOOP       = 1 << 3,
284         MR_DATATYPE_POLY       = 1 << 4,
285         MR_DATATYPE_OVERLAY    = 1 << 5,
286         MR_DATATYPE_SHADING    = 1 << 6,
287         MR_DATATYPE_DVERT      = 1 << 7,
288         MR_DATATYPE_LOOPCOL    = 1 << 8,
289         MR_DATATYPE_LOOPUV     = 1 << 9,
290         MR_DATATYPE_LOOSE_VERT = 1 << 10,
291         MR_DATATYPE_LOOSE_EDGE = 1 << 11,
292 };
293
294 /**
295  * These functions look like they would be slow but they will typically return true on the first iteration.
296  * Only false when all attached elements are hidden.
297  */
298 static bool bm_vert_has_visible_edge(const BMVert *v)
299 {
300         const BMEdge *e_iter, *e_first;
301
302         e_iter = e_first = v->e;
303         do {
304                 if (!BM_elem_flag_test(e_iter, BM_ELEM_HIDDEN)) {
305                         return true;
306                 }
307         } while ((e_iter = BM_DISK_EDGE_NEXT(e_iter, v)) != e_first);
308         return false;
309 }
310
311 static bool bm_edge_has_visible_face(const BMEdge *e)
312 {
313         const BMLoop *l_iter, *l_first;
314         l_iter = l_first = e->l;
315         do {
316                 if (!BM_elem_flag_test(l_iter->f, BM_ELEM_HIDDEN)) {
317                         return true;
318                 }
319         } while ((l_iter = l_iter->radial_next) != l_first);
320         return false;
321 }
322
323 /* Return true is all layers in _b_ are inside _a_. */
324 static bool mesh_cd_layers_type_overlap(
325         const uchar av[CD_NUMTYPES], const ushort al[CD_NUMTYPES],
326         const uchar bv[CD_NUMTYPES], const ushort bl[CD_NUMTYPES])
327 {
328         for (int i = 0; i < CD_NUMTYPES; ++i) {
329                 if ((av[i] & bv[i]) != bv[i]) {
330                         return false;
331                 }
332                 if ((al[i] & bl[i]) != bl[i]) {
333                         return false;
334                 }
335         }
336         return true;
337 }
338
339 static void mesh_cd_layers_type_merge(
340         uchar av[CD_NUMTYPES], ushort al[CD_NUMTYPES],
341         uchar bv[CD_NUMTYPES], ushort bl[CD_NUMTYPES])
342 {
343         for (int i = 0; i < CD_NUMTYPES; ++i) {
344                 av[i] |= bv[i];
345                 al[i] |= bl[i];
346         }
347 }
348
349 static void mesh_cd_calc_active_uv_layer(
350         const Mesh *me, ushort cd_lused[CD_NUMTYPES])
351 {
352         const CustomData *cd_ldata = (me->edit_btmesh) ? &me->edit_btmesh->bm->ldata : &me->ldata;
353
354         int layer = CustomData_get_active_layer(cd_ldata, CD_MLOOPUV);
355         if (layer != -1) {
356                 cd_lused[CD_MLOOPUV] |= (1 << layer);
357         }
358 }
359
360 static void mesh_cd_calc_active_vcol_layer(
361         const Mesh *me, ushort cd_lused[CD_NUMTYPES])
362 {
363         const CustomData *cd_ldata = (me->edit_btmesh) ? &me->edit_btmesh->bm->ldata : &me->ldata;
364
365         int layer = CustomData_get_active_layer(cd_ldata, CD_MLOOPCOL);
366         if (layer != -1) {
367                 cd_lused[CD_MLOOPCOL] |= (1 << layer);
368         }
369 }
370
371 static void mesh_cd_calc_used_gpu_layers(
372         const Mesh *me, uchar cd_vused[CD_NUMTYPES], ushort cd_lused[CD_NUMTYPES],
373         struct GPUMaterial **gpumat_array, int gpumat_array_len)
374 {
375         const CustomData *cd_ldata = (me->edit_btmesh) ? &me->edit_btmesh->bm->ldata : &me->ldata;
376
377         /* See: DM_vertex_attributes_from_gpu for similar logic */
378         GPUVertexAttribs gattribs = {{{0}}};
379
380         for (int i = 0; i < gpumat_array_len; i++) {
381                 GPUMaterial *gpumat = gpumat_array[i];
382                 if (gpumat) {
383                         GPU_material_vertex_attributes(gpumat, &gattribs);
384                         for (int j = 0; j < gattribs.totlayer; j++) {
385                                 const char *name = gattribs.layer[j].name;
386                                 int type = gattribs.layer[j].type;
387                                 int layer = -1;
388
389                                 if (type == CD_AUTO_FROM_NAME) {
390                                         /* We need to deduct what exact layer is used.
391                                          *
392                                          * We do it based on the specified name.
393                                          */
394                                         if (name[0] != '\0') {
395                                                 layer = CustomData_get_named_layer(cd_ldata, CD_MLOOPUV, name);
396                                                 type = CD_MTFACE;
397
398                                                 if (layer == -1) {
399                                                         layer = CustomData_get_named_layer(cd_ldata, CD_MLOOPCOL, name);
400                                                         type = CD_MCOL;
401                                                 }
402 #if 0                                   /* Tangents are always from UV's - this will never happen. */
403                                                 if (layer == -1) {
404                                                         layer = CustomData_get_named_layer(cd_ldata, CD_TANGENT, name);
405                                                         type = CD_TANGENT;
406                                                 }
407 #endif
408                                                 if (layer == -1) {
409                                                         continue;
410                                                 }
411                                         }
412                                         else {
413                                                 /* Fall back to the UV layer, which matches old behavior. */
414                                                 type = CD_MTFACE;
415                                         }
416                                 }
417
418                                 switch (type) {
419                                         case CD_MTFACE:
420                                         {
421                                                 if (layer == -1) {
422                                                         layer = (name[0] != '\0') ?
423                                                                 CustomData_get_named_layer(cd_ldata, CD_MLOOPUV, name) :
424                                                                 CustomData_get_active_layer(cd_ldata, CD_MLOOPUV);
425                                                 }
426                                                 if (layer != -1) {
427                                                         cd_lused[CD_MLOOPUV] |= (1 << layer);
428                                                 }
429                                                 break;
430                                         }
431                                         case CD_TANGENT:
432                                         {
433                                                 if (layer == -1) {
434                                                         layer = (name[0] != '\0') ?
435                                                                 CustomData_get_named_layer(cd_ldata, CD_MLOOPUV, name) :
436                                                                 CustomData_get_active_layer(cd_ldata, CD_MLOOPUV);
437                                                 }
438                                                 if (layer != -1) {
439                                                         cd_lused[CD_TANGENT] |= (1 << layer);
440                                                 }
441                                                 else {
442                                                         /* no UV layers at all => requesting orco */
443                                                         cd_lused[CD_TANGENT] |= DM_TANGENT_MASK_ORCO;
444                                                         cd_vused[CD_ORCO] |= 1;
445                                                 }
446                                                 break;
447                                         }
448                                         case CD_MCOL:
449                                         {
450                                                 if (layer == -1) {
451                                                         layer = (name[0] != '\0') ?
452                                                                 CustomData_get_named_layer(cd_ldata, CD_MLOOPCOL, name) :
453                                                                 CustomData_get_active_layer(cd_ldata, CD_MLOOPCOL);
454                                                 }
455                                                 if (layer != -1) {
456                                                         cd_lused[CD_MLOOPCOL] |= (1 << layer);
457                                                 }
458                                                 break;
459                                         }
460                                         case CD_ORCO:
461                                         {
462                                                 cd_vused[CD_ORCO] |= 1;
463                                                 break;
464                                         }
465                                 }
466                         }
467                 }
468         }
469 }
470
471
472 static void mesh_render_calc_normals_loop_and_poly(const Mesh *me, const float split_angle, MeshRenderData *rdata)
473 {
474         BLI_assert((me->flag & ME_AUTOSMOOTH) != 0);
475
476         int totloop = me->totloop;
477         int totpoly = me->totpoly;
478         float (*loop_normals)[3] = MEM_mallocN(sizeof(*loop_normals) * totloop, __func__);
479         float (*poly_normals)[3] = MEM_mallocN(sizeof(*poly_normals) * totpoly, __func__);
480         short (*clnors)[2] = CustomData_get_layer(&me->ldata, CD_CUSTOMLOOPNORMAL);
481
482         BKE_mesh_calc_normals_poly(
483                 me->mvert, NULL, me->totvert,
484                 me->mloop, me->mpoly, totloop, totpoly, poly_normals, false);
485
486         BKE_mesh_normals_loop_split(
487                 me->mvert, me->totvert, me->medge, me->totedge,
488                 me->mloop, loop_normals, totloop, me->mpoly, poly_normals, totpoly,
489                 true, split_angle, NULL, clnors, NULL);
490
491         rdata->loop_len = totloop;
492         rdata->poly_len = totpoly;
493         rdata->loop_normals = loop_normals;
494         rdata->poly_normals = poly_normals;
495 }
496
497 static void mesh_cd_extract_auto_layers_names_and_srgb(
498         Mesh *me, const ushort cd_lused[CD_NUMTYPES],
499         char **r_auto_layers_names, int **r_auto_layers_srgb, int *r_auto_layers_len)
500 {
501         const CustomData *cd_ldata = (me->edit_btmesh) ? &me->edit_btmesh->bm->ldata : &me->ldata;
502
503         int uv_len_used = count_bits_i(cd_lused[CD_MLOOPUV]);
504         int vcol_len_used = count_bits_i(cd_lused[CD_MLOOPCOL]);
505         int uv_len = CustomData_number_of_layers(cd_ldata, CD_MLOOPUV);
506         int vcol_len = CustomData_number_of_layers(cd_ldata, CD_MLOOPCOL);
507
508         uint auto_names_len = 32 * (uv_len_used + vcol_len_used);
509         uint auto_ofs = 0;
510         /* Allocate max, resize later. */
511         char *auto_names = MEM_callocN(sizeof(char) * auto_names_len, __func__);
512         int *auto_is_srgb = MEM_callocN(sizeof(int) * (uv_len_used + vcol_len_used), __func__);
513
514         for (int i = 0; i < uv_len; i++) {
515                 if ((cd_lused[CD_MLOOPUV] & (1 << i)) != 0) {
516                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPUV, i);
517                         uint hash = BLI_ghashutil_strhash_p(name);
518                         /* +1 to include '\0' terminator. */
519                         auto_ofs += 1 + BLI_snprintf_rlen(auto_names + auto_ofs, auto_names_len - auto_ofs, "ba%u", hash);
520                 }
521         }
522
523         uint auto_is_srgb_ofs = uv_len_used;
524         for (int i = 0; i < vcol_len; i++) {
525                 if ((cd_lused[CD_MLOOPCOL] & (1 << i)) != 0) {
526                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPCOL, i);
527                         /* We only do vcols that are not overridden by a uv layer with same name. */
528                         if (CustomData_get_named_layer_index(cd_ldata, CD_MLOOPUV, name) == -1) {
529                                 uint hash = BLI_ghashutil_strhash_p(name);
530                                 /* +1 to include '\0' terminator. */
531                                 auto_ofs += 1 + BLI_snprintf_rlen(auto_names + auto_ofs, auto_names_len - auto_ofs, "ba%u", hash);
532                                 auto_is_srgb[auto_is_srgb_ofs] = true;
533                                 auto_is_srgb_ofs++;
534                         }
535                 }
536         }
537
538         auto_names = MEM_reallocN(auto_names, sizeof(char) * auto_ofs);
539         auto_is_srgb = MEM_reallocN(auto_is_srgb, sizeof(int) * auto_is_srgb_ofs);
540
541         *r_auto_layers_names = auto_names;
542         *r_auto_layers_srgb = auto_is_srgb;
543         *r_auto_layers_len = auto_is_srgb_ofs;
544 }
545
546 /**
547  * TODO(campbell): 'gpumat_array' may include materials linked to the object.
548  * While not default, object materials should be supported.
549  * Although this only impacts the data that's generated, not the materials that display.
550  */
551 static MeshRenderData *mesh_render_data_create_ex(
552         Mesh *me, const int types, const uchar cd_vused[CD_NUMTYPES], const ushort cd_lused[CD_NUMTYPES])
553 {
554         MeshRenderData *rdata = MEM_callocN(sizeof(*rdata), __func__);
555         rdata->types = types;
556         rdata->mat_len = mesh_render_mat_len_get(me);
557
558         CustomData_reset(&rdata->cd.output.ldata);
559
560         const bool is_auto_smooth = (me->flag & ME_AUTOSMOOTH) != 0;
561         const float split_angle = is_auto_smooth ? me->smoothresh : (float)M_PI;
562
563         if (me->edit_btmesh) {
564                 BMEditMesh *embm = me->edit_btmesh;
565                 BMesh *bm = embm->bm;
566
567                 rdata->edit_bmesh = embm;
568                 rdata->edit_data = me->runtime.edit_data;
569
570                 if (embm->mesh_eval_cage && (embm->mesh_eval_cage->runtime.is_original == false)) {
571                         Mesh *me_cage = embm->mesh_eval_cage;
572
573                         rdata->mapped.me_cage = me_cage;
574                         if (types & MR_DATATYPE_VERT) {
575                                 rdata->mapped.vert_len = me_cage->totvert;
576                         }
577                         if (types & MR_DATATYPE_EDGE) {
578                                 rdata->mapped.edge_len = me_cage->totedge;
579                         }
580                         if (types & MR_DATATYPE_LOOP) {
581                                 rdata->mapped.loop_len = me_cage->totloop;
582                         }
583                         if (types & MR_DATATYPE_POLY) {
584                                 rdata->mapped.poly_len = me_cage->totpoly;
585                         }
586                         if (types & MR_DATATYPE_LOOPTRI) {
587                                 rdata->mapped.tri_len = poly_to_tri_count(me_cage->totpoly, me_cage->totloop);
588                         }
589
590                         rdata->mapped.v_origindex = CustomData_get_layer(&me_cage->vdata, CD_ORIGINDEX);
591                         rdata->mapped.e_origindex = CustomData_get_layer(&me_cage->edata, CD_ORIGINDEX);
592                         rdata->mapped.l_origindex = CustomData_get_layer(&me_cage->ldata, CD_ORIGINDEX);
593                         rdata->mapped.p_origindex = CustomData_get_layer(&me_cage->pdata, CD_ORIGINDEX);
594                         rdata->mapped.supported = (
595                                 rdata->mapped.v_origindex &&
596                                 rdata->mapped.e_origindex &&
597                                 rdata->mapped.p_origindex);
598                 }
599
600                 int bm_ensure_types = 0;
601                 if (types & MR_DATATYPE_VERT) {
602                         rdata->vert_len = bm->totvert;
603                         bm_ensure_types |= BM_VERT;
604                 }
605                 if (types & MR_DATATYPE_EDGE) {
606                         rdata->edge_len = bm->totedge;
607                         bm_ensure_types |= BM_EDGE;
608                 }
609                 if (types & MR_DATATYPE_LOOPTRI) {
610                         bm_ensure_types |= BM_LOOP;
611                 }
612                 if (types & MR_DATATYPE_LOOP) {
613                         int totloop = bm->totloop;
614                         if (is_auto_smooth) {
615                                 rdata->loop_normals = MEM_mallocN(sizeof(*rdata->loop_normals) * totloop, __func__);
616                                 int cd_loop_clnors_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
617                                 BM_loops_calc_normal_vcos(
618                                         bm, NULL, NULL, NULL, true, split_angle, rdata->loop_normals, NULL, NULL,
619                                         cd_loop_clnors_offset, false);
620                         }
621                         rdata->loop_len = totloop;
622                         bm_ensure_types |= BM_LOOP;
623                 }
624                 if (types & MR_DATATYPE_POLY) {
625                         rdata->poly_len = bm->totface;
626                         bm_ensure_types |= BM_FACE;
627                 }
628                 if (types & MR_DATATYPE_OVERLAY) {
629                         rdata->efa_act = BM_mesh_active_face_get(bm, false, true);
630                         rdata->eed_act = BM_mesh_active_edge_get(bm);
631                         rdata->eve_act = BM_mesh_active_vert_get(bm);
632                         rdata->cd.offset.crease = CustomData_get_offset(&bm->edata, CD_CREASE);
633                         rdata->cd.offset.bweight = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
634
635 #ifdef WITH_FREESTYLE
636                         rdata->cd.offset.freestyle_edge = CustomData_get_offset(&bm->edata, CD_FREESTYLE_EDGE);
637                         rdata->cd.offset.freestyle_face = CustomData_get_offset(&bm->pdata, CD_FREESTYLE_FACE);
638 #endif
639                 }
640                 if (types & (MR_DATATYPE_DVERT)) {
641                         bm_ensure_types |= BM_VERT;
642                 }
643                 if (rdata->edit_data != NULL) {
644                         bm_ensure_types |= BM_VERT;
645                 }
646
647                 BM_mesh_elem_index_ensure(bm, bm_ensure_types);
648                 BM_mesh_elem_table_ensure(bm, bm_ensure_types & ~BM_LOOP);
649
650                 if (types & MR_DATATYPE_LOOPTRI) {
651                         /* Edit mode ensures this is valid, no need to calculate. */
652                         BLI_assert((bm->totloop == 0) || (embm->looptris != NULL));
653                         int tottri = embm->tottri;
654                         MLoopTri *mlooptri = MEM_mallocN(sizeof(*rdata->mlooptri) * embm->tottri, __func__);
655                         for (int index = 0; index < tottri ; index ++ ) {
656                                 BMLoop **bmtri = embm->looptris[index];
657                                 MLoopTri *mtri = &mlooptri[index];
658                                 mtri->tri[0] = BM_elem_index_get(bmtri[0]);
659                                 mtri->tri[1] = BM_elem_index_get(bmtri[1]);
660                                 mtri->tri[2] = BM_elem_index_get(bmtri[2]);
661                         }
662                         rdata->mlooptri = mlooptri;
663                         rdata->tri_len = tottri;
664                 }
665
666                 if (types & MR_DATATYPE_LOOSE_VERT) {
667                         BLI_assert(types & MR_DATATYPE_VERT);
668                         rdata->loose_vert_len = 0;
669
670                         {
671                                 int *lverts = MEM_mallocN(rdata->vert_len * sizeof(int), __func__);
672                                 BLI_assert((bm->elem_table_dirty & BM_VERT) == 0);
673                                 for (int i = 0; i < bm->totvert; i++) {
674                                         const BMVert *eve = BM_vert_at_index(bm, i);
675                                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
676                                                 /* Loose vert */
677                                                 if (eve->e == NULL || !bm_vert_has_visible_edge(eve)) {
678                                                         lverts[rdata->loose_vert_len++] = i;
679                                                 }
680                                         }
681                                 }
682                                 rdata->loose_verts = MEM_reallocN(lverts, rdata->loose_vert_len * sizeof(int));
683                         }
684
685                         if (rdata->mapped.supported) {
686                                 Mesh *me_cage = embm->mesh_eval_cage;
687                                 rdata->mapped.loose_vert_len = 0;
688
689                                 if (rdata->loose_vert_len) {
690                                         int *lverts = MEM_mallocN(me_cage->totvert * sizeof(int), __func__);
691                                         const int *v_origindex = rdata->mapped.v_origindex;
692                                         for (int i = 0; i < me_cage->totvert; i++) {
693                                                 const int v_orig = v_origindex[i];
694                                                 if (v_orig != ORIGINDEX_NONE) {
695                                                         BMVert *eve = BM_vert_at_index(bm, v_orig);
696                                                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
697                                                                 /* Loose vert */
698                                                                 if (eve->e == NULL || !bm_vert_has_visible_edge(eve)) {
699                                                                         lverts[rdata->mapped.loose_vert_len++] = i;
700                                                                 }
701                                                         }
702                                                 }
703                                         }
704                                         rdata->mapped.loose_verts = MEM_reallocN(lverts, rdata->mapped.loose_vert_len * sizeof(int));
705                                 }
706                         }
707                 }
708
709                 if (types & MR_DATATYPE_LOOSE_EDGE) {
710                         BLI_assert(types & MR_DATATYPE_EDGE);
711                         rdata->loose_edge_len = 0;
712
713                         {
714                                 int *ledges = MEM_mallocN(rdata->edge_len * sizeof(int), __func__);
715                                 BLI_assert((bm->elem_table_dirty & BM_EDGE) == 0);
716                                 for (int i = 0; i < bm->totedge; i++) {
717                                         const BMEdge *eed = BM_edge_at_index(bm, i);
718                                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
719                                                 /* Loose edge */
720                                                 if (eed->l == NULL || !bm_edge_has_visible_face(eed)) {
721                                                         ledges[rdata->loose_edge_len++] = i;
722                                                 }
723                                         }
724                                 }
725                                 rdata->loose_edges = MEM_reallocN(ledges, rdata->loose_edge_len * sizeof(int));
726                         }
727
728                         if (rdata->mapped.supported) {
729                                 Mesh *me_cage = embm->mesh_eval_cage;
730                                 rdata->mapped.loose_edge_len = 0;
731
732                                 if (rdata->loose_edge_len) {
733                                         int *ledges = MEM_mallocN(me_cage->totedge * sizeof(int), __func__);
734                                         const int *e_origindex = rdata->mapped.e_origindex;
735                                         for (int i = 0; i < me_cage->totedge; i++) {
736                                                 const int e_orig = e_origindex[i];
737                                                 if (e_orig != ORIGINDEX_NONE) {
738                                                         BMEdge *eed = BM_edge_at_index(bm, e_orig);
739                                                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
740                                                                 /* Loose edge */
741                                                                 if (eed->l == NULL || !bm_edge_has_visible_face(eed)) {
742                                                                         ledges[rdata->mapped.loose_edge_len++] = i;
743                                                                 }
744                                                         }
745                                                 }
746                                         }
747                                         rdata->mapped.loose_edges = MEM_reallocN(ledges, rdata->mapped.loose_edge_len * sizeof(int));
748                                 }
749                         }
750                 }
751         }
752         else {
753                 rdata->me = me;
754
755                 if (types & (MR_DATATYPE_VERT)) {
756                         rdata->vert_len = me->totvert;
757                         rdata->mvert = CustomData_get_layer(&me->vdata, CD_MVERT);
758                 }
759                 if (types & (MR_DATATYPE_EDGE)) {
760                         rdata->edge_len = me->totedge;
761                         rdata->medge = CustomData_get_layer(&me->edata, CD_MEDGE);
762                 }
763                 if (types & MR_DATATYPE_LOOPTRI) {
764                         const int tri_len = rdata->tri_len = poly_to_tri_count(me->totpoly, me->totloop);
765                         MLoopTri *mlooptri = MEM_mallocN(sizeof(*mlooptri) * tri_len, __func__);
766                         BKE_mesh_recalc_looptri(me->mloop, me->mpoly, me->mvert, me->totloop, me->totpoly, mlooptri);
767                         rdata->mlooptri = mlooptri;
768                 }
769                 if (types & MR_DATATYPE_LOOP) {
770                         rdata->loop_len = me->totloop;
771                         rdata->mloop = CustomData_get_layer(&me->ldata, CD_MLOOP);
772
773                         if (is_auto_smooth) {
774                                 mesh_render_calc_normals_loop_and_poly(me, split_angle, rdata);
775                         }
776                 }
777                 if (types & MR_DATATYPE_POLY) {
778                         rdata->poly_len = me->totpoly;
779                         rdata->mpoly = CustomData_get_layer(&me->pdata, CD_MPOLY);
780                 }
781                 if (types & MR_DATATYPE_DVERT) {
782                         rdata->vert_len = me->totvert;
783                         rdata->dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT);
784                 }
785                 if (types & MR_DATATYPE_LOOPCOL) {
786                         rdata->loop_len = me->totloop;
787                         rdata->mloopcol = CustomData_get_layer(&me->ldata, CD_MLOOPCOL);
788                 }
789                 if (types & MR_DATATYPE_LOOPUV) {
790                         rdata->loop_len = me->totloop;
791                         rdata->mloopuv = CustomData_get_layer(&me->ldata, CD_MLOOPUV);
792                 }
793         }
794
795         if (types & MR_DATATYPE_SHADING) {
796                 CustomData *cd_vdata, *cd_ldata;
797
798                 BLI_assert(cd_vused != NULL && cd_lused != NULL);
799
800                 if (me->edit_btmesh) {
801                         BMesh *bm = me->edit_btmesh->bm;
802                         cd_vdata = &bm->vdata;
803                         cd_ldata = &bm->ldata;
804                 }
805                 else {
806                         cd_vdata = &me->vdata;
807                         cd_ldata = &me->ldata;
808                 }
809
810                 rdata->cd.layers.uv_active = CustomData_get_active_layer(cd_ldata, CD_MLOOPUV);
811                 rdata->cd.layers.vcol_active = CustomData_get_active_layer(cd_ldata, CD_MLOOPCOL);
812                 rdata->cd.layers.tangent_active = rdata->cd.layers.uv_active;
813
814 #define CD_VALIDATE_ACTIVE_LAYER(active_index, used) \
815                 if ((active_index != -1) && (used & (1 << active_index)) == 0) { \
816                         active_index = -1; \
817                 } ((void)0)
818
819                 CD_VALIDATE_ACTIVE_LAYER(rdata->cd.layers.uv_active, cd_lused[CD_MLOOPUV]);
820                 CD_VALIDATE_ACTIVE_LAYER(rdata->cd.layers.tangent_active, cd_lused[CD_TANGENT]);
821                 CD_VALIDATE_ACTIVE_LAYER(rdata->cd.layers.vcol_active, cd_lused[CD_MLOOPCOL]);
822
823 #undef CD_VALIDATE_ACTIVE_LAYER
824
825                 rdata->is_orco_allocated = false;
826                 if (cd_vused[CD_ORCO] & 1) {
827                         rdata->orco = CustomData_get_layer(cd_vdata, CD_ORCO);
828                         /* If orco is not available compute it ourselves */
829                         if (!rdata->orco) {
830                                 rdata->is_orco_allocated = true;
831                                 if (me->edit_btmesh) {
832                                         BMesh *bm = me->edit_btmesh->bm;
833                                         rdata->orco = MEM_mallocN(sizeof(*rdata->orco) * rdata->vert_len, "orco mesh");
834                                         BLI_assert((bm->elem_table_dirty & BM_VERT) == 0);
835                                         for (int i = 0; i < bm->totvert; i++) {
836                                                 copy_v3_v3(rdata->orco[i], BM_vert_at_index(bm, i)->co);
837                                         }
838                                         BKE_mesh_orco_verts_transform(me, rdata->orco, rdata->vert_len, 0);
839                                 }
840                                 else {
841                                         rdata->orco = MEM_mallocN(sizeof(*rdata->orco) * rdata->vert_len, "orco mesh");
842                                         MVert *mvert = rdata->mvert;
843                                         for (int a = 0; a < rdata->vert_len; a++, mvert++) {
844                                                 copy_v3_v3(rdata->orco[a], mvert->co);
845                                         }
846                                         BKE_mesh_orco_verts_transform(me, rdata->orco, rdata->vert_len, 0);
847                                 }
848                         }
849                 }
850                 else {
851                         rdata->orco = NULL;
852                 }
853
854                 /* don't access mesh directly, instead use vars taken from BMesh or Mesh */
855 #define me DONT_USE_THIS
856 #ifdef  me /* quiet warning */
857 #endif
858                 struct {
859                         uint uv_len;
860                         uint vcol_len;
861                 } cd_layers_src = {
862                         .uv_len = CustomData_number_of_layers(cd_ldata, CD_MLOOPUV),
863                         .vcol_len = CustomData_number_of_layers(cd_ldata, CD_MLOOPCOL),
864                 };
865
866                 rdata->cd.layers.uv_len = count_bits_i(cd_lused[CD_MLOOPUV]);
867                 rdata->cd.layers.tangent_len = count_bits_i(cd_lused[CD_TANGENT]);
868                 rdata->cd.layers.vcol_len = count_bits_i(cd_lused[CD_MLOOPCOL]);
869
870                 rdata->cd.layers.uv = MEM_mallocN(sizeof(*rdata->cd.layers.uv) * rdata->cd.layers.uv_len, __func__);
871                 rdata->cd.layers.vcol = MEM_mallocN(sizeof(*rdata->cd.layers.vcol) * rdata->cd.layers.vcol_len, __func__);
872                 rdata->cd.layers.tangent = MEM_mallocN(sizeof(*rdata->cd.layers.tangent) * rdata->cd.layers.tangent_len, __func__);
873
874                 rdata->cd.uuid.uv = MEM_mallocN(sizeof(*rdata->cd.uuid.uv) * rdata->cd.layers.uv_len, __func__);
875                 rdata->cd.uuid.vcol = MEM_mallocN(sizeof(*rdata->cd.uuid.vcol) * rdata->cd.layers.vcol_len, __func__);
876                 rdata->cd.uuid.tangent = MEM_mallocN(sizeof(*rdata->cd.uuid.tangent) * rdata->cd.layers.tangent_len, __func__);
877
878                 rdata->cd.offset.uv = MEM_mallocN(sizeof(*rdata->cd.offset.uv) * rdata->cd.layers.uv_len, __func__);
879                 rdata->cd.offset.vcol = MEM_mallocN(sizeof(*rdata->cd.offset.vcol) * rdata->cd.layers.vcol_len, __func__);
880
881                 /* Allocate max */
882                 rdata->cd.layers.auto_vcol = MEM_callocN(
883                         sizeof(*rdata->cd.layers.auto_vcol) * rdata->cd.layers.vcol_len, __func__);
884                 rdata->cd.uuid.auto_mix = MEM_mallocN(
885                         sizeof(*rdata->cd.uuid.auto_mix) * (rdata->cd.layers.vcol_len + rdata->cd.layers.uv_len), __func__);
886
887                 /* XXX FIXME XXX */
888                 /* We use a hash to identify each data layer based on its name.
889                  * Gawain then search for this name in the current shader and bind if it exists.
890                  * NOTE : This is prone to hash collision.
891                  * One solution to hash collision would be to format the cd layer name
892                  * to a safe glsl var name, but without name clash.
893                  * NOTE 2 : Replicate changes to code_generate_vertex_new() in gpu_codegen.c */
894                 if (rdata->cd.layers.vcol_len != 0) {
895                         for (int i_src = 0, i_dst = 0; i_src < cd_layers_src.vcol_len; i_src++, i_dst++) {
896                                 if ((cd_lused[CD_MLOOPCOL] & (1 << i_src)) == 0) {
897                                         i_dst--;
898                                         if (rdata->cd.layers.vcol_active >= i_src) {
899                                                 rdata->cd.layers.vcol_active--;
900                                         }
901                                 }
902                                 else {
903                                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPCOL, i_src);
904                                         uint hash = BLI_ghashutil_strhash_p(name);
905                                         BLI_snprintf(rdata->cd.uuid.vcol[i_dst], sizeof(*rdata->cd.uuid.vcol), "c%u", hash);
906                                         rdata->cd.layers.vcol[i_dst] = CustomData_get_layer_n(cd_ldata, CD_MLOOPCOL, i_src);
907                                         if (rdata->edit_bmesh) {
908                                                 rdata->cd.offset.vcol[i_dst] = CustomData_get_n_offset(
909                                                         &rdata->edit_bmesh->bm->ldata, CD_MLOOPCOL, i_src);
910                                         }
911
912                                         /* Gather number of auto layers. */
913                                         /* We only do vcols that are not overridden by uvs */
914                                         if (CustomData_get_named_layer_index(cd_ldata, CD_MLOOPUV, name) == -1) {
915                                                 BLI_snprintf(
916                                                         rdata->cd.uuid.auto_mix[rdata->cd.layers.uv_len + i_dst],
917                                                         sizeof(*rdata->cd.uuid.auto_mix), "a%u", hash);
918                                                 rdata->cd.layers.auto_vcol[i_dst] = true;
919                                         }
920                                 }
921                         }
922                 }
923
924                 /* Start Fresh */
925                 CustomData_free_layers(cd_ldata, CD_TANGENT, rdata->loop_len);
926                 CustomData_free_layers(cd_ldata, CD_MLOOPTANGENT, rdata->loop_len);
927
928                 if (rdata->cd.layers.uv_len != 0) {
929                         for (int i_src = 0, i_dst = 0; i_src < cd_layers_src.uv_len; i_src++, i_dst++) {
930                                 if ((cd_lused[CD_MLOOPUV] & (1 << i_src)) == 0) {
931                                         i_dst--;
932                                         if (rdata->cd.layers.uv_active >= i_src) {
933                                                 rdata->cd.layers.uv_active--;
934                                         }
935                                 }
936                                 else {
937                                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPUV, i_src);
938                                         uint hash = BLI_ghashutil_strhash_p(name);
939
940                                         BLI_snprintf(rdata->cd.uuid.uv[i_dst], sizeof(*rdata->cd.uuid.uv), "u%u", hash);
941                                         rdata->cd.layers.uv[i_dst] = CustomData_get_layer_n(cd_ldata, CD_MLOOPUV, i_src);
942                                         if (rdata->edit_bmesh) {
943                                                 rdata->cd.offset.uv[i_dst] = CustomData_get_n_offset(
944                                                         &rdata->edit_bmesh->bm->ldata, CD_MLOOPUV, i_src);
945                                         }
946                                         BLI_snprintf(rdata->cd.uuid.auto_mix[i_dst], sizeof(*rdata->cd.uuid.auto_mix), "a%u", hash);
947                                 }
948                         }
949                 }
950
951                 if (rdata->cd.layers.tangent_len != 0) {
952
953                         /* -------------------------------------------------------------------- */
954                         /* Pre-calculate tangents into 'rdata->cd.output.ldata' */
955
956                         BLI_assert(!CustomData_has_layer(&rdata->cd.output.ldata, CD_TANGENT));
957
958                         /* Tangent Names */
959                         char tangent_names[MAX_MTFACE][MAX_NAME];
960                         for (int i_src = 0, i_dst = 0; i_src < cd_layers_src.uv_len; i_src++, i_dst++) {
961                                 if ((cd_lused[CD_TANGENT] & (1 << i_src)) == 0) {
962                                         i_dst--;
963                                 }
964                                 else {
965                                         BLI_strncpy(
966                                                 tangent_names[i_dst],
967                                                 CustomData_get_layer_name(cd_ldata, CD_MLOOPUV, i_src), MAX_NAME);
968                                 }
969                         }
970
971                         /* If tangent from orco is requested, decrement tangent_len */
972                         int actual_tangent_len = (cd_lused[CD_TANGENT] & DM_TANGENT_MASK_ORCO) ?
973                                 rdata->cd.layers.tangent_len - 1 : rdata->cd.layers.tangent_len;
974                         if (rdata->edit_bmesh) {
975                                 BMEditMesh *em = rdata->edit_bmesh;
976                                 BMesh *bm = em->bm;
977
978                                 if (is_auto_smooth && rdata->loop_normals == NULL) {
979                                         /* Should we store the previous array of `loop_normals` in somewhere? */
980                                         rdata->loop_len = bm->totloop;
981                                         rdata->loop_normals = MEM_mallocN(sizeof(*rdata->loop_normals) * rdata->loop_len, __func__);
982                                         BM_loops_calc_normal_vcos(bm, NULL, NULL, NULL, true, split_angle, rdata->loop_normals, NULL, NULL, -1, false);
983                                 }
984
985                                 bool calc_active_tangent = false;
986
987                                 BKE_editmesh_loop_tangent_calc(
988                                         em, calc_active_tangent,
989                                         tangent_names, actual_tangent_len,
990                                         rdata->poly_normals, rdata->loop_normals,
991                                         rdata->orco,
992                                         &rdata->cd.output.ldata, bm->totloop,
993                                         &rdata->cd.output.tangent_mask);
994                         }
995                         else {
996 #undef me
997
998                                 if (is_auto_smooth && rdata->loop_normals == NULL) {
999                                         /* Should we store the previous array of `loop_normals` in CustomData? */
1000                                         mesh_render_calc_normals_loop_and_poly(me, split_angle, rdata);
1001                                 }
1002
1003                                 bool calc_active_tangent = false;
1004
1005                                 BKE_mesh_calc_loop_tangent_ex(
1006                                         me->mvert,
1007                                         me->mpoly, me->totpoly,
1008                                         me->mloop,
1009                                         rdata->mlooptri, rdata->tri_len,
1010                                         cd_ldata,
1011                                         calc_active_tangent,
1012                                         tangent_names, actual_tangent_len,
1013                                         rdata->poly_normals, rdata->loop_normals,
1014                                         rdata->orco,
1015                                         &rdata->cd.output.ldata, me->totloop,
1016                                         &rdata->cd.output.tangent_mask);
1017
1018                                         /* If we store tangents in the mesh, set temporary. */
1019 #if 0
1020                                 CustomData_set_layer_flag(cd_ldata, CD_TANGENT, CD_FLAG_TEMPORARY);
1021 #endif
1022
1023 #define me DONT_USE_THIS
1024 #ifdef  me /* quiet warning */
1025 #endif
1026                         }
1027
1028                         /* End tangent calculation */
1029                         /* -------------------------------------------------------------------- */
1030
1031                         BLI_assert(CustomData_number_of_layers(&rdata->cd.output.ldata, CD_TANGENT) == rdata->cd.layers.tangent_len);
1032
1033                         int i_dst = 0;
1034                         for (int i_src = 0; i_src < cd_layers_src.uv_len; i_src++, i_dst++) {
1035                                 if ((cd_lused[CD_TANGENT] & (1 << i_src)) == 0) {
1036                                         i_dst--;
1037                                         if (rdata->cd.layers.tangent_active >= i_src) {
1038                                                 rdata->cd.layers.tangent_active--;
1039                                         }
1040                                 }
1041                                 else {
1042                                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPUV, i_src);
1043                                         uint hash = BLI_ghashutil_strhash_p(name);
1044
1045                                         BLI_snprintf(rdata->cd.uuid.tangent[i_dst], sizeof(*rdata->cd.uuid.tangent), "t%u", hash);
1046
1047                                         /* Done adding tangents. */
1048
1049                                         /* note: BKE_editmesh_loop_tangent_calc calculates 'CD_TANGENT',
1050                                          * not 'CD_MLOOPTANGENT' (as done below). It's OK, they're compatible. */
1051
1052                                         /* note: normally we'd use 'i_src' here, but 'i_dst' is in sync with 'rdata->cd.output' */
1053                                         rdata->cd.layers.tangent[i_dst] = CustomData_get_layer_n(&rdata->cd.output.ldata, CD_TANGENT, i_dst);
1054                                         if (rdata->tri_len != 0) {
1055                                                 BLI_assert(rdata->cd.layers.tangent[i_dst] != NULL);
1056                                         }
1057                                 }
1058                         }
1059                         if (cd_lused[CD_TANGENT] & DM_TANGENT_MASK_ORCO) {
1060                                 const char *name = CustomData_get_layer_name(&rdata->cd.output.ldata, CD_TANGENT, i_dst);
1061                                 uint hash = BLI_ghashutil_strhash_p(name);
1062                                 BLI_snprintf(rdata->cd.uuid.tangent[i_dst], sizeof(*rdata->cd.uuid.tangent), "t%u", hash);
1063
1064                                 rdata->cd.layers.tangent[i_dst] = CustomData_get_layer_n(&rdata->cd.output.ldata, CD_TANGENT, i_dst);
1065                         }
1066                 }
1067
1068 #undef me
1069         }
1070
1071         return rdata;
1072 }
1073
1074 /* Warning replace mesh pointer. */
1075 #define MBC_GET_FINAL_MESH(me) \
1076         /* Hack to show the final result. */ \
1077         const bool _use_em_final = ( \
1078                 (me)->edit_btmesh && \
1079                 (me)->edit_btmesh->mesh_eval_final && \
1080                 ((me)->edit_btmesh->mesh_eval_final->runtime.is_original == false)); \
1081         Mesh _me_fake; \
1082         if (_use_em_final) { \
1083                 _me_fake = *(me)->edit_btmesh->mesh_eval_final; \
1084                 _me_fake.mat = (me)->mat; \
1085                 _me_fake.totcol = (me)->totcol; \
1086                 (me) = &_me_fake; \
1087         } ((void)0)
1088
1089 static void mesh_render_data_free(MeshRenderData *rdata)
1090 {
1091         if (rdata->is_orco_allocated) {
1092                 MEM_SAFE_FREE(rdata->orco);
1093         }
1094         MEM_SAFE_FREE(rdata->cd.offset.uv);
1095         MEM_SAFE_FREE(rdata->cd.offset.vcol);
1096         MEM_SAFE_FREE(rdata->cd.uuid.auto_mix);
1097         MEM_SAFE_FREE(rdata->cd.uuid.uv);
1098         MEM_SAFE_FREE(rdata->cd.uuid.vcol);
1099         MEM_SAFE_FREE(rdata->cd.uuid.tangent);
1100         MEM_SAFE_FREE(rdata->cd.layers.uv);
1101         MEM_SAFE_FREE(rdata->cd.layers.vcol);
1102         MEM_SAFE_FREE(rdata->cd.layers.tangent);
1103         MEM_SAFE_FREE(rdata->cd.layers.auto_vcol);
1104         MEM_SAFE_FREE(rdata->loose_verts);
1105         MEM_SAFE_FREE(rdata->loose_edges);
1106         MEM_SAFE_FREE(rdata->edges_adjacent_polys);
1107         MEM_SAFE_FREE(rdata->mlooptri);
1108         MEM_SAFE_FREE(rdata->loop_normals);
1109         MEM_SAFE_FREE(rdata->poly_normals);
1110         MEM_SAFE_FREE(rdata->poly_normals_pack);
1111         MEM_SAFE_FREE(rdata->vert_normals_pack);
1112         MEM_SAFE_FREE(rdata->vert_weight);
1113         MEM_SAFE_FREE(rdata->edge_select_bool);
1114         MEM_SAFE_FREE(rdata->edge_visible_bool);
1115         MEM_SAFE_FREE(rdata->vert_color);
1116
1117         MEM_SAFE_FREE(rdata->mapped.loose_verts);
1118         MEM_SAFE_FREE(rdata->mapped.loose_edges);
1119
1120         CustomData_free(&rdata->cd.output.ldata, rdata->loop_len);
1121
1122         MEM_freeN(rdata);
1123 }
1124
1125 static MeshRenderData *mesh_render_data_create(Mesh *me, const int types)
1126 {
1127         return mesh_render_data_create_ex(me, types, NULL, NULL);
1128 }
1129
1130 /** \} */
1131
1132 /* ---------------------------------------------------------------------- */
1133
1134 /** \name Accessor Functions
1135  * \{ */
1136
1137 static const char *mesh_render_data_uv_auto_layer_uuid_get(const MeshRenderData *rdata, int layer)
1138 {
1139         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1140         return rdata->cd.uuid.auto_mix[layer];
1141 }
1142
1143 static const char *mesh_render_data_vcol_auto_layer_uuid_get(const MeshRenderData *rdata, int layer)
1144 {
1145         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1146         return rdata->cd.uuid.auto_mix[rdata->cd.layers.uv_len + layer];
1147 }
1148
1149 static const char *mesh_render_data_uv_layer_uuid_get(const MeshRenderData *rdata, int layer)
1150 {
1151         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1152         return rdata->cd.uuid.uv[layer];
1153 }
1154
1155 static const char *mesh_render_data_vcol_layer_uuid_get(const MeshRenderData *rdata, int layer)
1156 {
1157         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1158         return rdata->cd.uuid.vcol[layer];
1159 }
1160
1161 static const char *mesh_render_data_tangent_layer_uuid_get(const MeshRenderData *rdata, int layer)
1162 {
1163         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1164         return rdata->cd.uuid.tangent[layer];
1165 }
1166
1167 static int mesh_render_data_verts_len_get(const MeshRenderData *rdata)
1168 {
1169         BLI_assert(rdata->types & MR_DATATYPE_VERT);
1170         return rdata->vert_len;
1171 }
1172 static int mesh_render_data_verts_len_get_maybe_mapped(const MeshRenderData *rdata)
1173 {
1174         BLI_assert(rdata->types & MR_DATATYPE_VERT);
1175         return ((rdata->mapped.use == false) ? rdata->vert_len : rdata->mapped.vert_len);
1176 }
1177
1178 static int UNUSED_FUNCTION(mesh_render_data_loose_verts_len_get)(const MeshRenderData *rdata)
1179 {
1180         BLI_assert(rdata->types & MR_DATATYPE_OVERLAY);
1181         return rdata->loose_vert_len;
1182 }
1183 static int mesh_render_data_loose_verts_len_get_maybe_mapped(const MeshRenderData *rdata)
1184 {
1185         BLI_assert(rdata->types & MR_DATATYPE_OVERLAY);
1186         return ((rdata->mapped.use == false) ? rdata->loose_vert_len : rdata->mapped.loose_vert_len);
1187 }
1188
1189 static int mesh_render_data_edges_len_get(const MeshRenderData *rdata)
1190 {
1191         BLI_assert(rdata->types & MR_DATATYPE_EDGE);
1192         return rdata->edge_len;
1193 }
1194 static int mesh_render_data_edges_len_get_maybe_mapped(const MeshRenderData *rdata)
1195 {
1196         BLI_assert(rdata->types & MR_DATATYPE_EDGE);
1197         return ((rdata->mapped.use == false) ? rdata->edge_len : rdata->mapped.edge_len);
1198 }
1199
1200 static int UNUSED_FUNCTION(mesh_render_data_loose_edges_len_get)(const MeshRenderData *rdata)
1201 {
1202         BLI_assert(rdata->types & MR_DATATYPE_OVERLAY);
1203         return rdata->loose_edge_len;
1204 }
1205 static int mesh_render_data_loose_edges_len_get_maybe_mapped(const MeshRenderData *rdata)
1206 {
1207         BLI_assert(rdata->types & MR_DATATYPE_OVERLAY);
1208         return ((rdata->mapped.use == false) ? rdata->loose_edge_len : rdata->mapped.loose_edge_len);
1209 }
1210
1211 static int mesh_render_data_looptri_len_get(const MeshRenderData *rdata)
1212 {
1213         BLI_assert(rdata->types & MR_DATATYPE_LOOPTRI);
1214         return rdata->tri_len;
1215 }
1216 static int mesh_render_data_looptri_len_get_maybe_mapped(const MeshRenderData *rdata)
1217 {
1218         BLI_assert(rdata->types & MR_DATATYPE_LOOPTRI);
1219         return ((rdata->mapped.use == false) ? rdata->tri_len : rdata->mapped.tri_len);
1220 }
1221
1222 static int UNUSED_FUNCTION(mesh_render_data_mat_len_get)(const MeshRenderData *rdata)
1223 {
1224         BLI_assert(rdata->types & MR_DATATYPE_POLY);
1225         return rdata->mat_len;
1226 }
1227
1228 static int mesh_render_data_loops_len_get(const MeshRenderData *rdata)
1229 {
1230         BLI_assert(rdata->types & MR_DATATYPE_LOOP);
1231         return rdata->loop_len;
1232 }
1233
1234 static int mesh_render_data_polys_len_get(const MeshRenderData *rdata)
1235 {
1236         BLI_assert(rdata->types & MR_DATATYPE_POLY);
1237         return rdata->poly_len;
1238 }
1239 static int mesh_render_data_polys_len_get_maybe_mapped(const MeshRenderData *rdata)
1240 {
1241         BLI_assert(rdata->types & MR_DATATYPE_POLY);
1242         return ((rdata->mapped.use == false) ? rdata->poly_len : rdata->mapped.poly_len);
1243 }
1244
1245 /** \} */
1246
1247
1248 /* ---------------------------------------------------------------------- */
1249
1250 /* TODO remove prototype. */
1251 static void mesh_create_edit_facedots(MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor_data_facedots);
1252
1253 /** \name Internal Cache (Lazy Initialization)
1254  * \{ */
1255
1256 /** Ensure #MeshRenderData.poly_normals_pack */
1257 static void mesh_render_data_ensure_poly_normals_pack(MeshRenderData *rdata)
1258 {
1259         GPUPackedNormal *pnors_pack = rdata->poly_normals_pack;
1260         if (pnors_pack == NULL) {
1261                 if (rdata->edit_bmesh) {
1262                         BMesh *bm = rdata->edit_bmesh->bm;
1263                         BMIter fiter;
1264                         BMFace *efa;
1265                         int i;
1266
1267                         pnors_pack = rdata->poly_normals_pack = MEM_mallocN(sizeof(*pnors_pack) * rdata->poly_len, __func__);
1268                         if (rdata->edit_data && rdata->edit_data->vertexCos != NULL) {
1269                                 BKE_editmesh_cache_ensure_poly_normals(rdata->edit_bmesh, rdata->edit_data);
1270                                 const float (*pnors)[3] = rdata->edit_data->polyNos;
1271                                 for (i = 0; i < bm->totface; i++) {
1272                                         pnors_pack[i] = GPU_normal_convert_i10_v3(pnors[i]);
1273                                 }
1274                         }
1275                         else {
1276                                 BM_ITER_MESH_INDEX(efa, &fiter, bm, BM_FACES_OF_MESH, i) {
1277                                         pnors_pack[i] = GPU_normal_convert_i10_v3(efa->no);
1278                                 }
1279                         }
1280                 }
1281                 else {
1282                         float (*pnors)[3] = rdata->poly_normals;
1283
1284                         if (!pnors) {
1285                                 pnors = rdata->poly_normals = MEM_mallocN(sizeof(*pnors) * rdata->poly_len, __func__);
1286                                 BKE_mesh_calc_normals_poly(
1287                                         rdata->mvert, NULL, rdata->vert_len,
1288                                         rdata->mloop, rdata->mpoly, rdata->loop_len, rdata->poly_len, pnors, true);
1289                         }
1290
1291                         pnors_pack = rdata->poly_normals_pack = MEM_mallocN(sizeof(*pnors_pack) * rdata->poly_len, __func__);
1292                         for (int i = 0; i < rdata->poly_len; i++) {
1293                                 pnors_pack[i] = GPU_normal_convert_i10_v3(pnors[i]);
1294                         }
1295                 }
1296         }
1297 }
1298
1299 /** Ensure #MeshRenderData.vert_normals_pack */
1300 static void mesh_render_data_ensure_vert_normals_pack(MeshRenderData *rdata)
1301 {
1302         GPUPackedNormal *vnors_pack = rdata->vert_normals_pack;
1303         if (vnors_pack == NULL) {
1304                 if (rdata->edit_bmesh) {
1305                         BMesh *bm = rdata->edit_bmesh->bm;
1306                         BMIter viter;
1307                         BMVert *eve;
1308                         int i;
1309
1310                         vnors_pack = rdata->vert_normals_pack = MEM_mallocN(sizeof(*vnors_pack) * rdata->vert_len, __func__);
1311                         BM_ITER_MESH_INDEX(eve, &viter, bm, BM_VERT, i) {
1312                                 vnors_pack[i] = GPU_normal_convert_i10_v3(eve->no);
1313                         }
1314                 }
1315                 else {
1316                         /* data from mesh used directly */
1317                         BLI_assert(0);
1318                 }
1319         }
1320 }
1321
1322
1323 /** Ensure #MeshRenderData.vert_color */
1324 static void UNUSED_FUNCTION(mesh_render_data_ensure_vert_color)(MeshRenderData *rdata)
1325 {
1326         char (*vcol)[3] = rdata->vert_color;
1327         if (vcol == NULL) {
1328                 if (rdata->edit_bmesh) {
1329                         BMesh *bm = rdata->edit_bmesh->bm;
1330                         const int cd_loop_color_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPCOL);
1331                         if (cd_loop_color_offset == -1) {
1332                                 goto fallback;
1333                         }
1334
1335                         vcol = rdata->vert_color = MEM_mallocN(sizeof(*vcol) * rdata->loop_len, __func__);
1336
1337                         BMIter fiter;
1338                         BMFace *efa;
1339                         int i = 0;
1340
1341                         BM_ITER_MESH(efa, &fiter, bm, BM_FACES_OF_MESH) {
1342                                 BMLoop *l_iter, *l_first;
1343                                 l_iter = l_first = BM_FACE_FIRST_LOOP(efa);
1344                                 do {
1345                                         const MLoopCol *lcol = BM_ELEM_CD_GET_VOID_P(l_iter, cd_loop_color_offset);
1346                                         vcol[i][0] = lcol->r;
1347                                         vcol[i][1] = lcol->g;
1348                                         vcol[i][2] = lcol->b;
1349                                         i += 1;
1350                                 } while ((l_iter = l_iter->next) != l_first);
1351                         }
1352                         BLI_assert(i == rdata->loop_len);
1353                 }
1354                 else {
1355                         if (rdata->mloopcol == NULL) {
1356                                 goto fallback;
1357                         }
1358
1359                         vcol = rdata->vert_color = MEM_mallocN(sizeof(*vcol) * rdata->loop_len, __func__);
1360
1361                         for (int i = 0; i < rdata->loop_len; i++) {
1362                                 vcol[i][0] = rdata->mloopcol[i].r;
1363                                 vcol[i][1] = rdata->mloopcol[i].g;
1364                                 vcol[i][2] = rdata->mloopcol[i].b;
1365                         }
1366                 }
1367         }
1368         return;
1369
1370 fallback:
1371         vcol = rdata->vert_color = MEM_mallocN(sizeof(*vcol) * rdata->loop_len, __func__);
1372
1373         for (int i = 0; i < rdata->loop_len; i++) {
1374                 vcol[i][0] = 255;
1375                 vcol[i][1] = 255;
1376                 vcol[i][2] = 255;
1377         }
1378 }
1379
1380 static float evaluate_vertex_weight(const MDeformVert *dvert, const DRW_MeshWeightState *wstate)
1381 {
1382         float input = 0.0f;
1383         bool show_alert_color = false;
1384
1385         if (wstate->flags & DRW_MESH_WEIGHT_STATE_MULTIPAINT) {
1386                 /* Multi-Paint feature */
1387                 input = BKE_defvert_multipaint_collective_weight(
1388                         dvert, wstate->defgroup_len, wstate->defgroup_sel, wstate->defgroup_sel_count,
1389                         (wstate->flags & DRW_MESH_WEIGHT_STATE_AUTO_NORMALIZE) != 0);
1390
1391                 /* make it black if the selected groups have no weight on a vertex */
1392                 if (input == 0.0f) {
1393                         show_alert_color = true;
1394                 }
1395         }
1396         else {
1397                 /* default, non tricky behavior */
1398                 input = defvert_find_weight(dvert, wstate->defgroup_active);
1399
1400                 if (input == 0.0f) {
1401                         switch (wstate->alert_mode) {
1402                                 case OB_DRAW_GROUPUSER_ACTIVE:
1403                                         show_alert_color = true;
1404                                         break;
1405
1406                                 case OB_DRAW_GROUPUSER_ALL:
1407                                         show_alert_color = defvert_is_weight_zero(dvert, wstate->defgroup_len);
1408                                         break;
1409                         }
1410                 }
1411         }
1412
1413         if (show_alert_color) {
1414                 return -1.0f;
1415         }
1416         else {
1417                 CLAMP(input, 0.0f, 1.0f);
1418                 return input;
1419         }
1420 }
1421
1422 /** Ensure #MeshRenderData.vert_weight */
1423 static void mesh_render_data_ensure_vert_weight(MeshRenderData *rdata, const struct DRW_MeshWeightState *wstate)
1424 {
1425         float (*vweight) = rdata->vert_weight;
1426         if (vweight == NULL) {
1427                 if (wstate->defgroup_active == -1) {
1428                         goto fallback;
1429                 }
1430
1431                 if (rdata->edit_bmesh) {
1432                         BMesh *bm = rdata->edit_bmesh->bm;
1433                         const int cd_dvert_offset = CustomData_get_offset(&bm->vdata, CD_MDEFORMVERT);
1434                         if (cd_dvert_offset == -1) {
1435                                 goto fallback;
1436                         }
1437
1438                         BMIter viter;
1439                         BMVert *eve;
1440                         int i;
1441
1442                         vweight = rdata->vert_weight = MEM_mallocN(sizeof(*vweight) * rdata->vert_len, __func__);
1443                         BM_ITER_MESH_INDEX(eve, &viter, bm, BM_VERT, i) {
1444                                 const MDeformVert *dvert = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
1445                                 vweight[i] = evaluate_vertex_weight(dvert, wstate);
1446                         }
1447                 }
1448                 else {
1449                         if (rdata->dvert == NULL) {
1450                                 goto fallback;
1451                         }
1452
1453                         vweight = rdata->vert_weight = MEM_mallocN(sizeof(*vweight) * rdata->vert_len, __func__);
1454                         for (int i = 0; i < rdata->vert_len; i++) {
1455                                 vweight[i] = evaluate_vertex_weight(&rdata->dvert[i], wstate);
1456                         }
1457                 }
1458         }
1459         return;
1460
1461 fallback:
1462         vweight = rdata->vert_weight = MEM_callocN(sizeof(*vweight) * rdata->vert_len, __func__);
1463
1464         if ((wstate->defgroup_active < 0) && (wstate->defgroup_len > 0)) {
1465                 copy_vn_fl(vweight, rdata->vert_len, -2.0f);
1466         }
1467         else if (wstate->alert_mode != OB_DRAW_GROUPUSER_NONE) {
1468                 copy_vn_fl(vweight, rdata->vert_len, -1.0f);
1469         }
1470 }
1471
1472 /** \} */
1473
1474 /* ---------------------------------------------------------------------- */
1475
1476 /** \name Internal Cache Generation
1477  * \{ */
1478
1479 static bool mesh_render_data_edge_vcos_manifold_pnors(
1480         MeshRenderData *rdata, const int edge_index,
1481         float **r_vco1, float **r_vco2, float **r_pnor1, float **r_pnor2, bool *r_is_manifold)
1482 {
1483         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_EDGE | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
1484
1485         if (rdata->edit_bmesh) {
1486                 BMesh *bm = rdata->edit_bmesh->bm;
1487                 BMEdge *eed = BM_edge_at_index(bm, edge_index);
1488                 if (BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
1489                         return false;
1490                 }
1491                 *r_vco1 = eed->v1->co;
1492                 *r_vco2 = eed->v2->co;
1493                 if (BM_edge_is_manifold(eed)) {
1494                         *r_pnor1 = eed->l->f->no;
1495                         *r_pnor2 = eed->l->radial_next->f->no;
1496                         *r_is_manifold = true;
1497                 }
1498                 else if (eed->l != NULL) {
1499                         *r_pnor1 = eed->l->f->no;
1500                         *r_pnor2 = eed->l->f->no;
1501                         *r_is_manifold = false;
1502                 }
1503                 else {
1504                         *r_pnor1 = eed->v1->no;
1505                         *r_pnor2 = eed->v1->no;
1506                         *r_is_manifold = false;
1507                 }
1508         }
1509         else {
1510                 MVert *mvert = rdata->mvert;
1511                 const MEdge *medge = rdata->medge;
1512                 EdgeAdjacentPolys *eap = rdata->edges_adjacent_polys;
1513                 float (*pnors)[3] = rdata->poly_normals;
1514
1515                 if (!eap) {
1516                         const MLoop *mloop = rdata->mloop;
1517                         const MPoly *mpoly = rdata->mpoly;
1518                         const int poly_len = rdata->poly_len;
1519                         const bool do_pnors = (poly_len != 0 && pnors == NULL);
1520
1521                         eap = rdata->edges_adjacent_polys = MEM_mallocN(sizeof(*eap) * rdata->edge_len, __func__);
1522                         for (int i = 0; i < rdata->edge_len; i++) {
1523                                 eap[i].count = 0;
1524                                 eap[i].face_index[0] = -1;
1525                                 eap[i].face_index[1] = -1;
1526                         }
1527                         if (do_pnors) {
1528                                 pnors = rdata->poly_normals = MEM_mallocN(sizeof(*pnors) * poly_len, __func__);
1529                         }
1530
1531                         for (int i = 0; i < poly_len; i++, mpoly++) {
1532                                 if (do_pnors) {
1533                                         BKE_mesh_calc_poly_normal(mpoly, mloop + mpoly->loopstart, mvert, pnors[i]);
1534                                 }
1535
1536                                 const int loopend = mpoly->loopstart + mpoly->totloop;
1537                                 for (int j = mpoly->loopstart; j < loopend; j++) {
1538                                         const int edge_idx = mloop[j].e;
1539                                         if (eap[edge_idx].count < 2) {
1540                                                 eap[edge_idx].face_index[eap[edge_idx].count] = i;
1541                                         }
1542                                         eap[edge_idx].count++;
1543                                 }
1544                         }
1545                 }
1546                 BLI_assert(eap && (rdata->poly_len == 0 || pnors != NULL));
1547
1548                 *r_vco1 = mvert[medge[edge_index].v1].co;
1549                 *r_vco2 = mvert[medge[edge_index].v2].co;
1550                 if (eap[edge_index].face_index[0] == -1) {
1551                         /* Edge has no poly... */
1552                         *r_pnor1 = *r_pnor2 = mvert[medge[edge_index].v1].co; /* XXX mvert.no are shorts... :( */
1553                         *r_is_manifold = false;
1554                 }
1555                 else {
1556                         *r_pnor1 = pnors[eap[edge_index].face_index[0]];
1557
1558                         float nor[3], v1[3], v2[3], r_center[3];
1559                         const MPoly *mpoly = rdata->mpoly + eap[edge_index].face_index[0];
1560                         const MLoop *mloop = rdata->mloop + mpoly->loopstart;
1561
1562                         BKE_mesh_calc_poly_center(mpoly, mloop, mvert, r_center);
1563                         sub_v3_v3v3(v1, *r_vco2, *r_vco1);
1564                         sub_v3_v3v3(v2, r_center, *r_vco1);
1565                         cross_v3_v3v3(nor, v1, v2);
1566
1567                         if (dot_v3v3(nor, *r_pnor1) < 0.0) {
1568                                 SWAP(float *, *r_vco1, *r_vco2);
1569                         }
1570
1571                         if (eap[edge_index].count == 2) {
1572                                 BLI_assert(eap[edge_index].face_index[1] >= 0);
1573                                 *r_pnor2 = pnors[eap[edge_index].face_index[1]];
1574                                 *r_is_manifold = true;
1575                         }
1576                         else {
1577                                 *r_pnor2 = pnors[eap[edge_index].face_index[0]];
1578                                 *r_is_manifold = false;
1579                         }
1580                 }
1581         }
1582
1583         return true;
1584 }
1585
1586 static uchar mesh_render_data_looptri_flag(MeshRenderData *rdata, const BMFace *efa)
1587 {
1588         uchar fflag = 0;
1589
1590         if (efa == rdata->efa_act)
1591                 fflag |= VFLAG_FACE_ACTIVE;
1592
1593         if (BM_elem_flag_test(efa, BM_ELEM_SELECT))
1594                 fflag |= VFLAG_FACE_SELECTED;
1595
1596 #ifdef WITH_FREESTYLE
1597         if (rdata->cd.offset.freestyle_face != -1) {
1598                 const FreestyleFace *ffa = BM_ELEM_CD_GET_VOID_P(efa, rdata->cd.offset.freestyle_face);
1599                 if (ffa->flag & FREESTYLE_FACE_MARK) {
1600                         fflag |= VFLAG_FACE_FREESTYLE;
1601                 }
1602         }
1603 #endif
1604
1605         return fflag;
1606 }
1607
1608 static void mesh_render_data_edge_flag(
1609         const MeshRenderData *rdata, const BMEdge *eed,
1610         EdgeDrawAttr *eattr)
1611 {
1612         eattr->e_flag |= VFLAG_EDGE_EXISTS;
1613
1614         if (eed == rdata->eed_act)
1615                 eattr->e_flag |= VFLAG_EDGE_ACTIVE;
1616
1617         if (BM_elem_flag_test(eed, BM_ELEM_SELECT))
1618                 eattr->e_flag |= VFLAG_EDGE_SELECTED;
1619
1620         if (BM_elem_flag_test(eed, BM_ELEM_SEAM))
1621                 eattr->e_flag |= VFLAG_EDGE_SEAM;
1622
1623         if (!BM_elem_flag_test(eed, BM_ELEM_SMOOTH))
1624                 eattr->e_flag |= VFLAG_EDGE_SHARP;
1625
1626         /* Use a byte for value range */
1627         if (rdata->cd.offset.crease != -1) {
1628                 float crease = BM_ELEM_CD_GET_FLOAT(eed, rdata->cd.offset.crease);
1629                 if (crease > 0) {
1630                         eattr->crease = (uchar)(crease * 255.0f);
1631                 }
1632         }
1633
1634         /* Use a byte for value range */
1635         if (rdata->cd.offset.bweight != -1) {
1636                 float bweight = BM_ELEM_CD_GET_FLOAT(eed, rdata->cd.offset.bweight);
1637                 if (bweight > 0) {
1638                         eattr->bweight = (uchar)(bweight * 255.0f);
1639                 }
1640         }
1641
1642 #ifdef WITH_FREESTYLE
1643         if (rdata->cd.offset.freestyle_edge != -1) {
1644                 const FreestyleEdge *fed = BM_ELEM_CD_GET_VOID_P(eed, rdata->cd.offset.freestyle_edge);
1645                 if (fed->flag & FREESTYLE_EDGE_MARK) {
1646                         eattr->e_flag |= VFLAG_EDGE_FREESTYLE;
1647                 }
1648         }
1649 #endif
1650 }
1651
1652 static uchar mesh_render_data_vertex_flag(MeshRenderData *rdata, const BMVert *eve)
1653 {
1654         uchar vflag = VFLAG_VERTEX_EXISTS;
1655
1656         /* Current vertex */
1657         if (eve == rdata->eve_act)
1658                 vflag |= VFLAG_VERTEX_ACTIVE;
1659
1660         if (BM_elem_flag_test(eve, BM_ELEM_SELECT))
1661                 vflag |= VFLAG_VERTEX_SELECTED;
1662
1663         return vflag;
1664 }
1665
1666 static void add_edit_tri(
1667         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_lnor, GPUVertBuf *vbo_data, GPUIndexBufBuilder *elb,
1668         const uint pos_id, const uint vnor_id, const uint lnor_id, const uint data_id,
1669         const BMLoop **bm_looptri, const int base_vert_idx)
1670 {
1671         uchar fflag;
1672         uchar vflag;
1673
1674         /* Only draw vertices once. */
1675         if (elb) {
1676                 for (int i = 0; i < 3; ++i) {
1677                         if (!BM_elem_flag_test(bm_looptri[i]->v, BM_ELEM_TAG)) {
1678                                 BM_elem_flag_enable(bm_looptri[i]->v, BM_ELEM_TAG);
1679                                 GPU_indexbuf_add_generic_vert(elb, base_vert_idx + i);
1680                         }
1681                 }
1682         }
1683
1684         if (vbo_pos_nor) {
1685                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
1686                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
1687                         for (uint i = 0; i < 3; i++) {
1688                                 int vidx = BM_elem_index_get(bm_looptri[i]->v);
1689                                 const float *pos = rdata->edit_data->vertexCos[vidx];
1690                                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1691                         }
1692                 }
1693                 else {
1694                         for (uint i = 0; i < 3; i++) {
1695                                 const float *pos = bm_looptri[i]->v->co;
1696                                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1697                         }
1698                 }
1699
1700                 for (uint i = 0; i < 3; i++) {
1701                         GPUPackedNormal vnor = GPU_normal_convert_i10_v3(bm_looptri[i]->v->no);
1702                         GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx + i, &vnor);
1703                 }
1704         }
1705
1706         if (vbo_lnor) {
1707                 float (*lnors)[3] = rdata->loop_normals;
1708                 for (uint i = 0; i < 3; i++) {
1709                         const float *nor = (lnors) ? lnors[BM_elem_index_get(bm_looptri[i])] : bm_looptri[0]->f->no;
1710                         GPUPackedNormal lnor = GPU_normal_convert_i10_v3(nor);
1711                         GPU_vertbuf_attr_set(vbo_lnor, lnor_id, base_vert_idx + i, &lnor);
1712                 }
1713         }
1714
1715         if (vbo_data) {
1716                 fflag = mesh_render_data_looptri_flag(rdata, bm_looptri[0]->f);
1717                 for (uint i = 0; i < 3; i++) {
1718                         const int i_next = (i + 1) % 3;
1719                         const int i_prev = (i + 2) % 3;
1720                         vflag = mesh_render_data_vertex_flag(rdata, bm_looptri[i]->v);
1721                         /* Opposite edge to the vertex at 'i'. */
1722                         EdgeDrawAttr eattr = {0};
1723                         const bool is_edge_real = (bm_looptri[i_next] == bm_looptri[i_prev]->prev);
1724                         if (is_edge_real) {
1725                                 mesh_render_data_edge_flag(rdata, bm_looptri[i_next]->e, &eattr);
1726                         }
1727                         eattr.v_flag = fflag | vflag;
1728                         GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx + i, &eattr);
1729                 }
1730         }
1731 }
1732 static bool add_edit_tri_mapped(
1733         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_lnor, GPUVertBuf *vbo_data, GPUIndexBufBuilder *elb,
1734         const uint pos_id, const uint vnor_id, const uint lnor_id, const uint data_id,
1735         BMFace *efa, const MLoopTri *mlt, const float (*poly_normals)[3], const float (*loop_normals)[3], const int base_vert_idx)
1736 {
1737         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
1738                 return false;
1739         }
1740
1741         BMEditMesh *embm = rdata->edit_bmesh;
1742         BMesh *bm = embm->bm;
1743         Mesh *me_cage = embm->mesh_eval_cage;
1744
1745         const MVert *mvert = me_cage->mvert;
1746         const MEdge *medge = me_cage->medge;
1747         const MLoop *mloop = me_cage->mloop;
1748
1749         const int *v_origindex = rdata->mapped.v_origindex;
1750         const int *e_origindex = rdata->mapped.e_origindex;
1751
1752         if (elb) {
1753                 for (int i = 0; i < 3; ++i) {
1754                         const int v_orig = v_origindex[mloop[mlt->tri[i]].v];
1755                         if (v_orig == ORIGINDEX_NONE) {
1756                                 continue;
1757                         }
1758                         BMVert *v = BM_vert_at_index(bm, v_orig);
1759                         if (!BM_elem_flag_test(v, BM_ELEM_TAG)) {
1760                                 BM_elem_flag_enable(v, BM_ELEM_TAG);
1761                                 GPU_indexbuf_add_generic_vert(elb, base_vert_idx + i);
1762                         }
1763                 }
1764         }
1765
1766         if (vbo_pos_nor) {
1767                 for (uint i = 0; i < 3; i++) {
1768                         const float *pos = mvert[mloop[mlt->tri[i]].v].co;
1769                         GPUPackedNormal vnor = GPU_normal_convert_i10_s3(mvert[mloop[mlt->tri[i]].v].no);
1770                         GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1771                         GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx + i, &vnor);
1772                 }
1773         }
1774
1775         if (vbo_lnor) {
1776                 for (uint i = 0; i < 3; i++) {
1777                         const float *nor = loop_normals ? loop_normals[mlt->tri[i]] : poly_normals[mlt->poly];
1778                         GPUPackedNormal lnor = GPU_normal_convert_i10_v3(nor);
1779                         GPU_vertbuf_attr_set(vbo_lnor, lnor_id, base_vert_idx + i, &lnor);
1780                 }
1781         }
1782
1783         if (vbo_data) {
1784                 EdgeDrawAttr eattr[3] = {{0}}; /* Importantly VFLAG_VERTEX_EXISTS is not set. */
1785                 uchar fflag = mesh_render_data_looptri_flag(rdata, efa);
1786                 for (uint i = 0; i < 3; i++) {
1787                         const int i_next = (i + 1) % 3;
1788                         const int i_prev = (i + 2) % 3;
1789                         const int v_orig = v_origindex[mloop[mlt->tri[i]].v];
1790                         if (v_orig != ORIGINDEX_NONE) {
1791                                 BMVert *v = BM_vert_at_index(bm, v_orig);
1792                                 eattr[i].v_flag |= mesh_render_data_vertex_flag(rdata, v);
1793                         }
1794                         /* Opposite edge to the vertex at 'i'. */
1795                         const int e_idx = mloop[mlt->tri[i_next]].e;
1796                         const int e_orig = e_origindex[e_idx];
1797                         if (e_orig != ORIGINDEX_NONE) {
1798                                 const MEdge *ed = &medge[e_idx];
1799                                 const uint tri_edge[2]  = {mloop[mlt->tri[i_prev]].v, mloop[mlt->tri[i_next]].v};
1800                                 const bool is_edge_real = (
1801                                         ((ed->v1 == tri_edge[0]) && (ed->v2 == tri_edge[1])) ||
1802                                         ((ed->v1 == tri_edge[1]) && (ed->v2 == tri_edge[0])));
1803                                 if (is_edge_real) {
1804                                         BMEdge *eed = BM_edge_at_index(bm, e_orig);
1805                                         mesh_render_data_edge_flag(rdata, eed, &eattr[i]);
1806                                         /* Set vertex selected if both original verts are selected. */
1807                                         if (BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) &&
1808                                             BM_elem_flag_test(eed->v2, BM_ELEM_SELECT))
1809                                         {
1810                                                 eattr[i_next].v_flag |= VFLAG_VERTEX_SELECTED;
1811                                                 eattr[i_prev].v_flag |= VFLAG_VERTEX_SELECTED;
1812                                         }
1813                                 }
1814                         }
1815                 }
1816                 for (uint i = 0; i < 3; i++) {
1817                         eattr[i].v_flag |= fflag;
1818                         GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx + i, &eattr[i]);
1819                 }
1820         }
1821
1822         return true;
1823 }
1824
1825 static void add_edit_loose_edge(
1826         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_data,
1827         const uint pos_id, const uint vnor_id, const uint data_id,
1828         const BMEdge *eed, const int base_vert_idx)
1829 {
1830         if (vbo_pos_nor) {
1831                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
1832                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
1833                         for (uint i = 0; i < 2; i++) {
1834                                 int vidx = BM_elem_index_get((&eed->v1)[i]);
1835                                 const float *pos = rdata->edit_data->vertexCos[vidx];
1836                                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1837                         }
1838                 }
1839                 else {
1840                         for (int i = 0; i < 2; i++) {
1841                                 const float *pos = (&eed->v1)[i]->co;
1842                                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1843                         }
1844                 }
1845
1846                 for (int i = 0; i < 2; i++) {
1847                         GPUPackedNormal vnor = GPU_normal_convert_i10_v3((&eed->v1)[i]->no);
1848                         GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx + i, &vnor);
1849                 }
1850         }
1851
1852         if (vbo_data) {
1853                 EdgeDrawAttr eattr = {0};
1854                 mesh_render_data_edge_flag(rdata, eed, &eattr);
1855                 for (int i = 0; i < 2; i++) {
1856                         eattr.v_flag = mesh_render_data_vertex_flag(rdata, (&eed->v1)[i]);
1857                         GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx + i, &eattr);
1858                 }
1859         }
1860 }
1861 static void add_edit_loose_edge_mapped(
1862         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_data,
1863         const uint pos_id, const uint vnor_id, const uint data_id,
1864         BMEdge *eed, const MVert *mvert, const MEdge *ed, const int base_vert_idx)
1865 {
1866         if (vbo_pos_nor) {
1867                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
1868                 for (int i = 0; i < 2; i++) {
1869                         const float *pos = mvert[*(&ed->v1 + i)].co;
1870                         GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1871
1872                         GPUPackedNormal vnor = GPU_normal_convert_i10_s3(mvert[*(&ed->v1 + i)].no);
1873                         GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx + i, &vnor);
1874                 }
1875         }
1876
1877         if (vbo_data) {
1878                 EdgeDrawAttr eattr = {0};
1879                 mesh_render_data_edge_flag(rdata, eed, &eattr);
1880                 for (int i = 0; i < 2; i++) {
1881                         const int v_orig = rdata->mapped.v_origindex[*(&ed->v1 + i)];
1882                         eattr.v_flag = (v_orig != ORIGINDEX_NONE) ? mesh_render_data_vertex_flag(rdata, (&eed->v1)[i]) : 0;
1883                         GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx + i, &eattr);
1884                 }
1885         }
1886 }
1887
1888 static void add_edit_loose_vert(
1889         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_data,
1890         const uint pos_id, const uint vnor_id, const uint data_id,
1891         const BMVert *eve, const int base_vert_idx)
1892 {
1893         if (vbo_pos_nor) {
1894                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
1895                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
1896                         int vidx = BM_elem_index_get(eve);
1897                         const float *pos = rdata->edit_data->vertexCos[vidx];
1898                         GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx, pos);
1899                 }
1900                 else {
1901                         const float *pos = eve->co;
1902                         GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx, pos);
1903                 }
1904
1905                 GPUPackedNormal vnor = GPU_normal_convert_i10_v3(eve->no);
1906                 GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx, &vnor);
1907         }
1908
1909         if (vbo_data) {
1910                 uchar vflag[4] = {0, 0, 0, 0};
1911                 vflag[0] = mesh_render_data_vertex_flag(rdata, eve);
1912                 GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx, vflag);
1913         }
1914 }
1915 static void add_edit_loose_vert_mapped(
1916         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_data,
1917         const uint pos_id, const uint vnor_id, const uint data_id,
1918         const BMVert *eve, const MVert *mv, const int base_vert_idx)
1919 {
1920         if (vbo_pos_nor) {
1921                 const float *pos = mv->co;
1922                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx, pos);
1923
1924                 GPUPackedNormal vnor = GPU_normal_convert_i10_s3(mv->no);
1925                 GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx, &vnor);
1926         }
1927
1928         if (vbo_data) {
1929                 uchar vflag[4] = {0, 0, 0, 0};
1930                 vflag[0] = mesh_render_data_vertex_flag(rdata, eve);
1931                 GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx, vflag);
1932         }
1933 }
1934
1935 static bool add_edit_facedot(
1936         MeshRenderData *rdata, GPUVertBuf *vbo,
1937         const uint fdot_pos_id, const uint fdot_nor_flag_id,
1938         const int poly, const int base_vert_idx)
1939 {
1940         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
1941         float pnor[3], center[3];
1942         bool selected;
1943         if (rdata->edit_bmesh) {
1944                 const BMFace *efa = BM_face_at_index(rdata->edit_bmesh->bm, poly);
1945                 if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
1946                         return false;
1947                 }
1948                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
1949                         copy_v3_v3(center, rdata->edit_data->polyCos[poly]);
1950                         copy_v3_v3(pnor, rdata->edit_data->polyNos[poly]);
1951                 }
1952                 else {
1953                         BM_face_calc_center_median(efa, center);
1954                         copy_v3_v3(pnor, efa->no);
1955                 }
1956                 selected = (BM_elem_flag_test(efa, BM_ELEM_SELECT) != 0) ? true : false;
1957         }
1958         else {
1959                 MVert *mvert = rdata->mvert;
1960                 const MPoly *mpoly = rdata->mpoly + poly;
1961                 const MLoop *mloop = rdata->mloop + mpoly->loopstart;
1962
1963                 BKE_mesh_calc_poly_center(mpoly, mloop, mvert, center);
1964                 BKE_mesh_calc_poly_normal(mpoly, mloop, mvert, pnor);
1965
1966                 selected = false; /* No selection if not in edit mode */
1967         }
1968
1969         GPUPackedNormal nor = GPU_normal_convert_i10_v3(pnor);
1970         nor.w = (selected) ? 1 : 0;
1971         GPU_vertbuf_attr_set(vbo, fdot_nor_flag_id, base_vert_idx, &nor);
1972         GPU_vertbuf_attr_set(vbo, fdot_pos_id, base_vert_idx, center);
1973
1974         return true;
1975 }
1976 static bool add_edit_facedot_mapped(
1977         MeshRenderData *rdata, GPUVertBuf *vbo,
1978         const uint fdot_pos_id, const uint fdot_nor_flag_id,
1979         const int poly, const int base_vert_idx)
1980 {
1981         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
1982         float pnor[3], center[3];
1983         const int *p_origindex = rdata->mapped.p_origindex;
1984         const int p_orig = p_origindex[poly];
1985         if (p_orig == ORIGINDEX_NONE) {
1986                 return false;
1987         }
1988         BMEditMesh *em = rdata->edit_bmesh;
1989         const BMFace *efa = BM_face_at_index(rdata->edit_bmesh->bm, p_orig);
1990         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
1991                 return false;
1992         }
1993
1994         Mesh *me_cage = em->mesh_eval_cage;
1995         const MVert *mvert = me_cage->mvert;
1996         const MLoop *mloop = me_cage->mloop;
1997         const MPoly *mpoly = me_cage->mpoly;
1998
1999         const MPoly *mp = mpoly + poly;
2000         const MLoop *ml = mloop + mp->loopstart;
2001
2002         BKE_mesh_calc_poly_center(mp, ml, mvert, center);
2003         BKE_mesh_calc_poly_normal(mp, ml, mvert, pnor);
2004
2005         GPUPackedNormal nor = GPU_normal_convert_i10_v3(pnor);
2006         nor.w = (BM_elem_flag_test(efa, BM_ELEM_SELECT) != 0) ? 1 : 0;
2007         GPU_vertbuf_attr_set(vbo, fdot_nor_flag_id, base_vert_idx, &nor);
2008         GPU_vertbuf_attr_set(vbo, fdot_pos_id, base_vert_idx, center);
2009
2010         return true;
2011 }
2012
2013 /** \} */
2014
2015 /* ---------------------------------------------------------------------- */
2016
2017 /** \name Vertex Group Selection
2018  * \{ */
2019
2020 /** Reset the selection structure, deallocating heap memory as appropriate. */
2021 static void drw_mesh_weight_state_clear(struct DRW_MeshWeightState *wstate)
2022 {
2023         MEM_SAFE_FREE(wstate->defgroup_sel);
2024
2025         memset(wstate, 0, sizeof(*wstate));
2026
2027         wstate->defgroup_active = -1;
2028 }
2029
2030 /** Copy selection data from one structure to another, including heap memory. */
2031 static void drw_mesh_weight_state_copy(
2032         struct DRW_MeshWeightState *wstate_dst, const struct DRW_MeshWeightState *wstate_src)
2033 {
2034         MEM_SAFE_FREE(wstate_dst->defgroup_sel);
2035
2036         memcpy(wstate_dst, wstate_src, sizeof(*wstate_dst));
2037
2038         if (wstate_src->defgroup_sel) {
2039                 wstate_dst->defgroup_sel = MEM_dupallocN(wstate_src->defgroup_sel);
2040         }
2041 }
2042
2043 /** Compare two selection structures. */
2044 static bool drw_mesh_weight_state_compare(const struct DRW_MeshWeightState *a, const struct DRW_MeshWeightState *b)
2045 {
2046         return a->defgroup_active == b->defgroup_active &&
2047                a->defgroup_len == b->defgroup_len &&
2048                a->flags == b->flags &&
2049                a->alert_mode == b->alert_mode &&
2050                a->defgroup_sel_count == b->defgroup_sel_count &&
2051                ((!a->defgroup_sel && !b->defgroup_sel) ||
2052                 (a->defgroup_sel && b->defgroup_sel &&
2053                  memcmp(a->defgroup_sel, b->defgroup_sel, a->defgroup_len * sizeof(bool)) == 0));
2054 }
2055
2056 static void drw_mesh_weight_state_extract(
2057         Object *ob, Mesh *me, ToolSettings *ts, bool paint_mode,
2058         struct DRW_MeshWeightState *wstate)
2059 {
2060         /* Extract complete vertex weight group selection state and mode flags. */
2061         memset(wstate, 0, sizeof(*wstate));
2062
2063         wstate->defgroup_active = ob->actdef - 1;
2064         wstate->defgroup_len = BLI_listbase_count(&ob->defbase);
2065
2066         wstate->alert_mode = ts->weightuser;
2067
2068         if (paint_mode && ts->multipaint) {
2069                 /* Multipaint needs to know all selected bones, not just the active group.
2070                  * This is actually a relatively expensive operation, but caching would be difficult. */
2071                 wstate->defgroup_sel = BKE_object_defgroup_selected_get(ob, wstate->defgroup_len, &wstate->defgroup_sel_count);
2072
2073                 if (wstate->defgroup_sel_count > 1) {
2074                         wstate->flags |= DRW_MESH_WEIGHT_STATE_MULTIPAINT | (ts->auto_normalize ? DRW_MESH_WEIGHT_STATE_AUTO_NORMALIZE : 0);
2075
2076                         if (me->editflag & ME_EDIT_MIRROR_X) {
2077                                 BKE_object_defgroup_mirror_selection(
2078                                         ob, wstate->defgroup_len, wstate->defgroup_sel, wstate->defgroup_sel, &wstate->defgroup_sel_count);
2079                         }
2080                 }
2081                 /* With only one selected bone Multipaint reverts to regular mode. */
2082                 else {
2083                         wstate->defgroup_sel_count = 0;
2084                         MEM_SAFE_FREE(wstate->defgroup_sel);
2085                 }
2086         }
2087 }
2088
2089 /** \} */
2090
2091 /* ---------------------------------------------------------------------- */
2092
2093 /** \name Mesh GPUBatch Cache
2094  * \{ */
2095
2096 typedef struct MeshBatchCache {
2097         /* In order buffers: All verts only specified once.
2098          * To be used with a GPUIndexBuf. */
2099         struct {
2100                 /* Vertex data. */
2101                 GPUVertBuf *pos_nor;
2102                 GPUVertBuf *weights;
2103                 /* Loop data. */
2104                 GPUVertBuf *loop_pos_nor;
2105                 GPUVertBuf *loop_uv_tan;
2106                 GPUVertBuf *loop_vcol;
2107         } ordered;
2108
2109         /* Tesselated: (all verts specified for each triangles).
2110          * Indices does not match the CPU data structure's. */
2111         struct {
2112                 GPUVertBuf *pos_nor;
2113
2114                 GPUVertBuf *wireframe_data;
2115         } tess;
2116
2117         /* Edit Mesh Data:
2118          * Data is also tesselated because of barycentric wireframe rendering. */
2119         struct {
2120                 GPUVertBuf *pos_nor;
2121                 GPUVertBuf *pos_nor_ledges;
2122                 GPUVertBuf *pos_nor_lverts;
2123                 GPUVertBuf *pos_nor_data_facedots;
2124                 GPUVertBuf *data;
2125                 GPUVertBuf *data_ledges;
2126                 GPUVertBuf *data_lverts;
2127                 GPUVertBuf *lnor;
2128         } edit;
2129
2130         /* Index Buffers:
2131          * Only need to be updated when topology changes. */
2132         struct {
2133                 /* Indices to verts. */
2134                 GPUIndexBuf *surf_tris;
2135                 /* Indices to vloops. */
2136                 GPUIndexBuf *loops_tris;
2137                 GPUIndexBuf *loops_lines;
2138                 /* Contains indices to unique edit vertices to not
2139                  * draw the same vert multiple times (because of tesselation). */
2140                 GPUIndexBuf *edit_verts_points;
2141         } ibo;
2142
2143         struct {
2144                 /* Surfaces / Render */
2145                 GPUBatch *surface;
2146                 GPUBatch *surface_weights;
2147                 /* Edit mode */
2148                 GPUBatch *edit_triangles;
2149                 GPUBatch *edit_vertices;
2150                 GPUBatch *edit_loose_edges;
2151                 GPUBatch *edit_loose_verts;
2152                 GPUBatch *edit_triangles_nor;
2153                 GPUBatch *edit_triangles_lnor;
2154                 GPUBatch *edit_loose_edges_nor;
2155                 GPUBatch *edit_facedots;
2156                 /* Common display / Other */
2157                 GPUBatch *all_verts;
2158                 GPUBatch *wire_loops; /* Loops around faces. */
2159                 GPUBatch *wire_triangles; /* Triangles for object mode wireframe. */
2160         } batch;
2161
2162         GPUIndexBuf **surf_per_mat_tris;
2163         GPUBatch **surf_per_mat;
2164
2165         /* OLD BATCH METHOD, thoses needs to be ported and added in the structs above. */
2166
2167         /* Indices buffers. */
2168         GPUIndexBuf *edges_in_order;
2169         GPUIndexBuf *edges_adjacency; /* Store edges with adjacent vertices. */
2170         GPUIndexBuf *triangles_in_order;
2171         GPUIndexBuf *ledges_in_order;
2172
2173         GPUBatch *all_edges;
2174         GPUBatch *all_triangles;
2175
2176         GPUVertBuf *pos_with_normals;
2177         GPUVertBuf *pos_with_normals_visible_only;
2178         GPUVertBuf *pos_with_normals_edit;
2179         GPUVertBuf *pos_with_normals_visible_only_edit;
2180         GPUVertBuf *tri_aligned_uv;  /* Active UV layer (mloopuv) */
2181
2182         /**
2183          * Other uses are all positions or loose elements.
2184          * This stores all visible elements, needed for selection.
2185          */
2186         GPUVertBuf *ed_fcenter_pos_with_nor_and_sel;
2187         GPUVertBuf *ed_edge_pos;
2188         GPUVertBuf *ed_vert_pos;
2189
2190         GPUBatch *triangles_with_normals;
2191         GPUBatch *ledges_with_normals;
2192
2193         /* Skip hidden (depending on paint select mode) */
2194         GPUBatch *triangles_with_weights;
2195         GPUBatch *triangles_with_vert_colors;
2196         /* Always skip hidden */
2197         GPUBatch *triangles_with_select_mask;
2198         GPUBatch *triangles_with_select_id;
2199         uint       triangles_with_select_id_offset;
2200
2201         GPUBatch *facedot_with_select_id;  /* shares vbo with 'edit_facedots' */
2202         GPUBatch *edges_with_select_id;
2203         GPUBatch *verts_with_select_id;
2204
2205         uint facedot_with_select_id_offset;
2206         uint edges_with_select_id_offset;
2207         uint verts_with_select_id_offset;
2208
2209         GPUBatch *points_with_normals;
2210         GPUBatch *fancy_edges; /* owns its vertex buffer (not shared) */
2211
2212         GPUBatch *edge_detection;
2213
2214         /* Texture Paint.*/
2215         /* per-texture batch */
2216         GPUBatch **texpaint_triangles;
2217         GPUBatch  *texpaint_triangles_single;
2218
2219         GPUBatch *overlay_weight_faces;
2220         GPUBatch *overlay_weight_verts;
2221         GPUBatch *overlay_paint_edges;
2222
2223         /* 2D/UV edit */
2224         GPUVertBuf *edituv_pos;
2225         GPUVertBuf *edituv_area;
2226         GPUVertBuf *edituv_angle;
2227         GPUVertBuf *edituv_data;
2228
2229         GPUIndexBuf *edituv_visible_faces;
2230         GPUIndexBuf *edituv_visible_edges;
2231
2232         GPUBatch *texpaint_uv_loops;
2233
2234         GPUBatch *edituv_faces_strech_area;
2235         GPUBatch *edituv_faces_strech_angle;
2236         GPUBatch *edituv_faces;
2237         GPUBatch *edituv_edges;
2238         GPUBatch *edituv_verts;
2239         GPUBatch *edituv_facedots;
2240
2241         char edituv_state;
2242
2243         /* arrays of bool uniform names (and value) that will be use to
2244          * set srgb conversion for auto attribs.*/
2245         char *auto_layer_names;
2246         int *auto_layer_is_srgb;
2247         int auto_layer_len;
2248
2249         /* settings to determine if cache is invalid */
2250         bool is_maybe_dirty;
2251         bool is_dirty; /* Instantly invalidates cache, skipping mesh check */
2252         int edge_len;
2253         int tri_len;
2254         int poly_len;
2255         int vert_len;
2256         int mat_len;
2257         bool is_editmode;
2258
2259         struct DRW_MeshWeightState weight_state;
2260
2261         uchar cd_vused[CD_NUMTYPES];
2262         uchar cd_vneeded[CD_NUMTYPES];
2263         ushort cd_lused[CD_NUMTYPES];
2264         ushort cd_lneeded[CD_NUMTYPES];
2265
2266         /* XXX, only keep for as long as sculpt mode uses shaded drawing. */
2267         bool is_sculpt_points_tag;
2268
2269         /* Valid only if edges_adjacency is up to date. */
2270         bool is_manifold;
2271 } MeshBatchCache;
2272
2273 /* GPUBatch cache management. */
2274
2275 static bool mesh_batch_cache_valid(Mesh *me)
2276 {
2277         MeshBatchCache *cache = me->runtime.batch_cache;
2278
2279         if (cache == NULL) {
2280                 return false;
2281         }
2282
2283         if (cache->mat_len != mesh_render_mat_len_get(me)) {
2284                 return false;
2285         }
2286
2287         if (cache->is_editmode != (me->edit_btmesh != NULL)) {
2288                 return false;
2289         }
2290
2291         if (cache->is_dirty) {
2292                 return false;
2293         }
2294
2295         if (cache->is_maybe_dirty == false) {
2296                 return true;
2297         }
2298         else {
2299                 if (cache->is_editmode) {
2300                         return false;
2301                 }
2302                 else if ((cache->vert_len != mesh_render_verts_len_get(me)) ||
2303                          (cache->edge_len != mesh_render_edges_len_get(me)) ||
2304                          (cache->tri_len  != mesh_render_looptri_len_get(me)) ||
2305                          (cache->poly_len != mesh_render_polys_len_get(me)) ||
2306                          (cache->mat_len   != mesh_render_mat_len_get(me)))
2307                 {
2308                         return false;
2309                 }
2310         }
2311
2312         return true;
2313 }
2314
2315 static void mesh_batch_cache_init(Mesh *me)
2316 {
2317         MeshBatchCache *cache = me->runtime.batch_cache;
2318
2319         if (!cache) {
2320                 cache = me->runtime.batch_cache = MEM_callocN(sizeof(*cache), __func__);
2321         }
2322         else {
2323                 memset(cache, 0, sizeof(*cache));
2324         }
2325
2326         cache->is_editmode = me->edit_btmesh != NULL;
2327
2328         if (cache->is_editmode == false) {
2329                 cache->edge_len = mesh_render_edges_len_get(me);
2330                 cache->tri_len = mesh_render_looptri_len_get(me);
2331                 cache->poly_len = mesh_render_polys_len_get(me);
2332                 cache->vert_len = mesh_render_verts_len_get(me);
2333         }
2334
2335         cache->mat_len = mesh_render_mat_len_get(me);
2336         cache->surf_per_mat_tris = MEM_callocN(sizeof(*cache->surf_per_mat_tris) * cache->mat_len, __func__);
2337         cache->surf_per_mat = MEM_callocN(sizeof(*cache->surf_per_mat) * cache->mat_len, __func__);
2338
2339         /* TODO Might be wiser to alloc in one chunck. */
2340         for (int i = 0; i < cache->mat_len; ++i) {
2341                 cache->surf_per_mat_tris[i] = MEM_callocN(sizeof(GPUIndexBuf), "GPUIndexBuf");
2342                 cache->surf_per_mat[i] = MEM_callocN(sizeof(GPUBatch), "GPUBatch");
2343         }
2344
2345         cache->is_maybe_dirty = false;
2346         cache->is_dirty = false;
2347
2348         drw_mesh_weight_state_clear(&cache->weight_state);
2349 }
2350
2351 static MeshBatchCache *mesh_batch_cache_get(Mesh *me)
2352 {
2353         if (!mesh_batch_cache_valid(me)) {
2354                 mesh_batch_cache_clear(me);
2355                 mesh_batch_cache_init(me);
2356         }
2357         return me->runtime.batch_cache;
2358 }
2359
2360 static void mesh_batch_cache_check_vertex_group(MeshBatchCache *cache, const struct DRW_MeshWeightState *wstate)
2361 {
2362         if (!drw_mesh_weight_state_compare(&cache->weight_state, wstate)) {
2363                 GPU_BATCH_CLEAR_SAFE(cache->batch.surface_weights);
2364                 GPU_VERTBUF_DISCARD_SAFE(cache->ordered.weights);
2365
2366                 drw_mesh_weight_state_clear(&cache->weight_state);
2367         }
2368 }
2369
2370 static void mesh_batch_cache_discard_shaded_tri(MeshBatchCache *cache)
2371 {
2372         GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_pos_nor);
2373         GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_uv_tan);
2374         GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_vcol);
2375         /* TODO */
2376         // GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_orco);
2377
2378         if (cache->surf_per_mat_tris) {
2379                 for (int i = 0; i < cache->mat_len; i++) {
2380                         GPU_INDEXBUF_DISCARD_SAFE(cache->surf_per_mat_tris[i]);
2381                 }
2382         }
2383         MEM_SAFE_FREE(cache->surf_per_mat_tris);
2384         if (cache->surf_per_mat) {
2385                 for (int i = 0; i < cache->mat_len; i++) {
2386                         GPU_BATCH_DISCARD_SAFE(cache->surf_per_mat[i]);
2387                 }
2388         }
2389         MEM_SAFE_FREE(cache->surf_per_mat);
2390
2391         MEM_SAFE_FREE(cache->texpaint_triangles);
2392
2393         MEM_SAFE_FREE(cache->auto_layer_names);
2394         MEM_SAFE_FREE(cache->auto_layer_is_srgb);
2395
2396         cache->mat_len = 0;
2397 }
2398
2399 static void mesh_batch_cache_discard_uvedit(MeshBatchCache *cache)
2400 {
2401         GPU_VERTBUF_DISCARD_SAFE(cache->edituv_pos);
2402         GPU_VERTBUF_DISCARD_SAFE(cache->edituv_area);
2403         GPU_VERTBUF_DISCARD_SAFE(cache->edituv_angle);
2404         GPU_VERTBUF_DISCARD_SAFE(cache->edituv_data);
2405
2406         GPU_INDEXBUF_DISCARD_SAFE(cache->edituv_visible_faces);
2407         GPU_INDEXBUF_DISCARD_SAFE(cache->edituv_visible_edges);
2408
2409         if (cache->edituv_faces_strech_area) {
2410                 gpu_batch_presets_unregister(cache->edituv_faces_strech_area);
2411         }
2412         if (cache->edituv_faces_strech_angle) {
2413                 gpu_batch_presets_unregister(cache->edituv_faces_strech_angle);
2414         }
2415         if (cache->edituv_faces) {
2416                 gpu_batch_presets_unregister(cache->edituv_faces);
2417         }
2418         if (cache->edituv_edges) {
2419                 gpu_batch_presets_unregister(cache->edituv_edges);
2420         }
2421         if (cache->edituv_verts) {
2422                 gpu_batch_presets_unregister(cache->edituv_verts);
2423         }
2424         if (cache->edituv_facedots) {
2425                 gpu_batch_presets_unregister(cache->edituv_facedots);
2426         }
2427
2428         GPU_BATCH_DISCARD_SAFE(cache->edituv_faces_strech_area);
2429         GPU_BATCH_DISCARD_SAFE(cache->edituv_faces_strech_angle);
2430         GPU_BATCH_DISCARD_SAFE(cache->edituv_faces);
2431         GPU_BATCH_DISCARD_SAFE(cache->edituv_edges);
2432         GPU_BATCH_DISCARD_SAFE(cache->edituv_verts);
2433         GPU_BATCH_DISCARD_SAFE(cache->edituv_facedots);
2434
2435         gpu_batch_presets_unregister(cache->texpaint_uv_loops);
2436
2437         GPU_BATCH_DISCARD_SAFE(cache->texpaint_uv_loops);
2438
2439         cache->edituv_state = 0;
2440 }
2441
2442 void DRW_mesh_batch_cache_dirty_tag(Mesh *me, int mode)
2443 {
2444         MeshBatchCache *cache = me->runtime.batch_cache;
2445         if (cache == NULL) {
2446                 return;
2447         }
2448         switch (mode) {
2449                 case BKE_MESH_BATCH_DIRTY_MAYBE_ALL:
2450                         cache->is_maybe_dirty = true;
2451                         break;
2452                 case BKE_MESH_BATCH_DIRTY_SELECT:
2453                         GPU_VERTBUF_DISCARD_SAFE(cache->edit.data);
2454                         GPU_VERTBUF_DISCARD_SAFE(cache->edit.data_ledges);
2455                         GPU_VERTBUF_DISCARD_SAFE(cache->edit.data_lverts);
2456                         GPU_VERTBUF_DISCARD_SAFE(cache->edit.pos_nor_data_facedots);
2457                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_triangles);
2458                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_vertices);
2459                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_loose_verts);
2460                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_loose_edges);
2461                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_facedots);
2462                         GPU_VERTBUF_DISCARD_SAFE(cache->ed_edge_pos);
2463                         GPU_VERTBUF_DISCARD_SAFE(cache->ed_vert_pos);
2464                         /* Edit mode selection. */
2465                         GPU_BATCH_DISCARD_SAFE(cache->facedot_with_select_id);
2466                         GPU_BATCH_DISCARD_SAFE(cache->edges_with_select_id);
2467                         GPU_BATCH_DISCARD_SAFE(cache->verts_with_select_id);
2468                         /* Paint mode selection */
2469                         /* TODO only do that in paint mode. */
2470                         GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_pos_nor);
2471                         GPU_BATCH_DISCARD_SAFE(cache->batch.surface);
2472                         GPU_BATCH_DISCARD_SAFE(cache->batch.wire_loops);
2473                         if (cache->surf_per_mat) {
2474                                 for (int i = 0; i < cache->mat_len; i++) {
2475                                         GPU_BATCH_DISCARD_SAFE(cache->surf_per_mat[i]);
2476                                 }
2477                         }
2478                         GPU_BATCH_DISCARD_SAFE(cache->overlay_paint_edges);
2479                         GPU_BATCH_DISCARD_SAFE(cache->overlay_weight_faces);
2480                         GPU_BATCH_DISCARD_SAFE(cache->overlay_weight_verts);
2481                         /* Because visible UVs depends on edit mode selection, discard everything. */
2482                         mesh_batch_cache_discard_uvedit(cache);
2483                         break;
2484                 case BKE_MESH_BATCH_DIRTY_ALL:
2485                         cache->is_dirty = true;
2486                         break;
2487                 case BKE_MESH_BATCH_DIRTY_SHADING:
2488                         mesh_batch_cache_discard_shaded_tri(cache);
2489                         mesh_batch_cache_discard_uvedit(cache);
2490                         break;
2491                 case BKE_MESH_BATCH_DIRTY_SCULPT_COORDS:
2492                         cache->is_sculpt_points_tag = true;
2493                         break;
2494                 case BKE_MESH_BATCH_DIRTY_UVEDIT_ALL:
2495                         mesh_batch_cache_discard_uvedit(cache);
2496                         break;
2497                 case BKE_MESH_BATCH_DIRTY_UVEDIT_SELECT:
2498                         /* For now same as above. */
2499                         mesh_batch_cache_discard_uvedit(cache);
2500                         break;
2501                 default:
2502                         BLI_assert(0);
2503         }
2504 }
2505
2506 /**
2507  * This only clear the batches associated to the given vertex buffer.
2508  **/
2509 static void mesh_batch_cache_clear_selective(Mesh *me, GPUVertBuf *vert)
2510 {
2511         MeshBatchCache *cache = me->runtime.batch_cache;
2512         if (!cache) {
2513                 return;
2514         }
2515
2516         BLI_assert(vert != NULL);
2517
2518         if (ELEM(vert, cache->pos_with_normals, cache->pos_with_normals_visible_only,
2519                        cache->pos_with_normals_edit, cache->pos_with_normals_visible_only_edit))
2520         {
2521                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_normals);
2522                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_weights);
2523                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_vert_colors);
2524                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_select_id);
2525                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_select_mask);
2526                 GPU_BATCH_DISCARD_SAFE(cache->points_with_normals);
2527                 GPU_BATCH_DISCARD_SAFE(cache->ledges_with_normals);
2528                 // if (cache->shaded_triangles) {
2529                 //      for (int i = 0; i < cache->mat_len; i++) {
2530                 //              GPU_BATCH_DISCARD_SAFE(cache->shaded_triangles[i]);
2531                 //      }
2532                 // }
2533                 // MEM_SAFE_FREE(cache->shaded_triangles);
2534                 // if (cache->texpaint_triangles) {
2535                 //      for (int i = 0; i < cache->mat_len; i++) {
2536                 //              GPU_BATCH_DISCARD_SAFE(cache->texpaint_triangles[i]);
2537                 //      }
2538                 // }
2539                 MEM_SAFE_FREE(cache->texpaint_triangles);
2540                 GPU_BATCH_DISCARD_SAFE(cache->texpaint_triangles_single);
2541         }
2542         /* TODO: add the other ones if needed. */
2543         else {
2544                 /* Does not match any vertbuf in the batch cache! */
2545                 BLI_assert(0);
2546         }
2547 }
2548
2549 static void mesh_batch_cache_clear(Mesh *me)
2550 {
2551         MeshBatchCache *cache = me->runtime.batch_cache;
2552         if (!cache) {
2553                 return;
2554         }
2555
2556         for (int i = 0; i < sizeof(cache->ordered) / sizeof(void *); ++i) {
2557                 GPUVertBuf **vbo = (GPUVertBuf **)&cache->ordered;
2558                 GPU_VERTBUF_DISCARD_SAFE(vbo[i]);
2559         }
2560         for (int i = 0; i < sizeof(cache->tess) / sizeof(void *); ++i) {
2561                 GPUVertBuf **vbo = (GPUVertBuf **)&cache->tess;
2562                 GPU_VERTBUF_DISCARD_SAFE(vbo[i]);
2563         }
2564         for (int i = 0; i < sizeof(cache->edit) / sizeof(void *); ++i) {
2565                 GPUVertBuf **vbo = (GPUVertBuf **)&cache->edit;
2566                 GPU_VERTBUF_DISCARD_SAFE(vbo[i]);
2567         }
2568         for (int i = 0; i < sizeof(cache->ibo) / sizeof(void *); ++i) {
2569                 GPUIndexBuf **ibo = (GPUIndexBuf **)&cache->ibo;
2570                 GPU_INDEXBUF_DISCARD_SAFE(ibo[i]);
2571         }
2572         for (int i = 0; i < sizeof(cache->batch) / sizeof(void *); ++i) {
2573                 GPUBatch **batch = (GPUBatch **)&cache->batch;
2574                 GPU_BATCH_DISCARD_SAFE(batch[i]);
2575         }
2576
2577         GPU_BATCH_DISCARD_SAFE(cache->all_edges);
2578         GPU_BATCH_DISCARD_SAFE(cache->all_triangles);
2579
2580         GPU_INDEXBUF_DISCARD_SAFE(cache->edges_in_order);
2581         GPU_INDEXBUF_DISCARD_SAFE(cache->triangles_in_order);
2582         GPU_INDEXBUF_DISCARD_SAFE(cache->ledges_in_order);
2583
2584         GPU_BATCH_DISCARD_SAFE(cache->overlay_weight_faces);
2585         GPU_BATCH_DISCARD_SAFE(cache->overlay_weight_verts);
2586         GPU_BATCH_DISCARD_SAFE(cache->overlay_paint_edges);
2587
2588         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_normals);
2589         GPU_BATCH_DISCARD_SAFE(cache->points_with_normals);
2590         GPU_BATCH_DISCARD_SAFE(cache->ledges_with_normals);
2591         GPU_VERTBUF_DISCARD_SAFE(cache->pos_with_normals);
2592         GPU_VERTBUF_DISCARD_SAFE(cache->pos_with_normals_visible_only);
2593         GPU_VERTBUF_DISCARD_SAFE(cache->pos_with_normals_edit);
2594         GPU_VERTBUF_DISCARD_SAFE(cache->pos_with_normals_visible_only_edit);
2595         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_weights);
2596         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_vert_colors);
2597         GPU_VERTBUF_DISCARD_SAFE(cache->tri_aligned_uv);
2598         GPU_VERTBUF_DISCARD_SAFE(cache->ed_fcenter_pos_with_nor_and_sel);
2599         GPU_VERTBUF_DISCARD_SAFE(cache->ed_edge_pos);
2600         GPU_VERTBUF_DISCARD_SAFE(cache->ed_vert_pos);
2601         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_select_mask);
2602         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_select_id);
2603         GPU_BATCH_DISCARD_SAFE(cache->facedot_with_select_id);
2604         GPU_BATCH_DISCARD_SAFE(cache->edges_with_select_id);
2605         GPU_BATCH_DISCARD_SAFE(cache->verts_with_select_id);
2606
2607         GPU_BATCH_DISCARD_SAFE(cache->fancy_edges);
2608
2609         GPU_INDEXBUF_DISCARD_SAFE(cache->edges_adjacency);
2610         GPU_BATCH_DISCARD_SAFE(cache->edge_detection);
2611
2612         mesh_batch_cache_discard_shaded_tri(cache);
2613
2614         mesh_batch_cache_discard_uvedit(cache);
2615
2616         if (cache->texpaint_triangles) {
2617                 for (int i = 0; i < cache->mat_len; i++) {
2618                         GPU_BATCH_DISCARD_SAFE(cache->texpaint_triangles[i]);
2619                 }
2620         }
2621         MEM_SAFE_FREE(cache->texpaint_triangles);
2622
2623         drw_mesh_weight_state_clear(&cache->weight_state);
2624 }
2625
2626 void DRW_mesh_batch_cache_free(Mesh *me)
2627 {
2628         mesh_batch_cache_clear(me);
2629         MEM_SAFE_FREE(me->runtime.batch_cache);
2630 }
2631
2632 /* GPUBatch cache usage. */
2633
2634 static void mesh_create_pos_and_nor_tess(MeshRenderData *rdata, GPUVertBuf *vbo, bool use_hide)
2635 {
2636         static GPUVertFormat format = { 0 };
2637         static struct { uint pos, nor; } attr_id;
2638         if (format.attr_len == 0) {
2639                 attr_id.pos = GPU_vertformat_attr_add(&format, "pos", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
2640                 attr_id.nor = GPU_vertformat_attr_add(&format, "nor", GPU_COMP_I10, 3, GPU_FETCH_INT_TO_FLOAT_UNIT);
2641                 GPU_vertformat_triple_load(&format);
2642         }
2643
2644         GPU_vertbuf_init_with_format(vbo, &format);
2645
2646         const int tri_len = mesh_render_data_looptri_len_get_maybe_mapped(rdata);
2647         const int vbo_len_capacity = tri_len * 3;
2648         int vbo_len_used = 0;
2649         GPU_vertbuf_data_alloc(vbo, vbo_len_capacity);
2650
2651         GPUVertBufRaw pos_step, nor_step;
2652         GPU_vertbuf_attr_get_raw_data(vbo, attr_id.pos, &pos_step);
2653         GPU_vertbuf_attr_get_raw_data(vbo, attr_id.nor, &nor_step);
2654
2655         if (rdata->mapped.use == false) {
2656                 float (*lnors)[3] = rdata->loop_normals;
2657                 if (rdata->edit_bmesh) {
2658                         GPUPackedNormal *pnors_pack, *vnors_pack;
2659
2660                         if (lnors == NULL) {
2661                                 mesh_render_data_ensure_poly_normals_pack(rdata);
2662                                 mesh_render_data_ensure_vert_normals_pack(rdata);
2663
2664                                 pnors_pack = rdata->poly_normals_pack;
2665                                 vnors_pack = rdata->vert_normals_pack;
2666                         }
2667
2668                         for (int i = 0; i < tri_len; i++) {
2669                                 const BMLoop **bm_looptri = (const BMLoop **)rdata->edit_bmesh->looptris[i];
2670                                 const BMFace *bm_face = bm_looptri[0]->f;
2671
2672                                 /* use_hide always for edit-mode */
2673                                 if (BM_elem_flag_test(bm_face, BM_ELEM_HIDDEN)) {
2674                                         continue;
2675                                 }
2676
2677                                 if (lnors) {
2678                                         for (uint t = 0; t < 3; t++) {
2679                                                 const float *nor = lnors[BM_elem_index_get(bm_looptri[t])];
2680                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_v3(nor);
2681                                         }
2682                                 }
2683                                 else if (BM_elem_flag_test(bm_face, BM_ELEM_SMOOTH)) {
2684                                         for (uint t = 0; t < 3; t++) {
2685                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = vnors_pack[BM_elem_index_get(bm_looptri[t]->v)];
2686                                         }
2687                                 }
2688                                 else {
2689                                         const GPUPackedNormal *snor_pack = &pnors_pack[BM_elem_index_get(bm_face)];
2690                                         for (uint t = 0; t < 3; t++) {
2691                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = *snor_pack;
2692                                         }
2693                                 }
2694
2695                                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
2696                                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
2697                                         for (uint t = 0; t < 3; t++) {
2698                                                 int vidx = BM_elem_index_get(bm_looptri[t]->v);
2699                                                 const float *pos = rdata->edit_data->vertexCos[vidx];
2700                                                 copy_v3_v3(GPU_vertbuf_raw_step(&pos_step), pos);
2701                                         }
2702                                 }
2703                                 else {
2704                                         for (uint t = 0; t < 3; t++) {
2705                                                 copy_v3_v3(GPU_vertbuf_raw_step(&pos_step), bm_looptri[t]->v->co);
2706                                         }
2707                                 }
2708                         }
2709                 }
2710                 else {
2711                         if (lnors == NULL) {
2712                                 /* Use normals from vertex. */
2713                                 mesh_render_data_ensure_poly_normals_pack(rdata);
2714                         }
2715
2716                         for (int i = 0; i < tri_len; i++) {
2717                                 const MLoopTri *mlt = &rdata->mlooptri[i];
2718                                 const MPoly *mp = &rdata->mpoly[mlt->poly];
2719
2720                                 if (use_hide && (mp->flag & ME_HIDE)) {
2721                                         continue;
2722                                 }
2723
2724                                 const uint vtri[3] = {
2725                                         rdata->mloop[mlt->tri[0]].v,
2726                                         rdata->mloop[mlt->tri[1]].v,
2727                                         rdata->mloop[mlt->tri[2]].v,
2728                                 };
2729
2730                                 if (lnors) {
2731                                         for (uint t = 0; t < 3; t++) {
2732                                                 const float *nor = lnors[mlt->tri[t]];
2733                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_v3(nor);
2734                                         }
2735                                 }
2736                                 else if (mp->flag & ME_SMOOTH) {
2737                                         for (uint t = 0; t < 3; t++) {
2738                                                 const MVert *mv = &rdata->mvert[vtri[t]];
2739                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_s3(mv->no);
2740                                         }
2741                                 }
2742                                 else {
2743                                         const GPUPackedNormal *pnors_pack = &rdata->poly_normals_pack[mlt->poly];
2744                                         for (uint t = 0; t < 3; t++) {
2745                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = *pnors_pack;
2746                                         }
2747                                 }
2748
2749                                 for (uint t = 0; t < 3; t++) {
2750                                         const MVert *mv = &rdata->mvert[vtri[t]];
2751                                         copy_v3_v3(GPU_vertbuf_raw_step(&pos_step), mv->co);
2752                                 }
2753                         }
2754                 }
2755         }
2756         else {
2757                 /* Note: mapped doesn't support lnors yet. */
2758                 BMesh *bm = rdata->edit_bmesh->bm;
2759                 Mesh *me_cage = rdata->mapped.me_cage;
2760
2761                 /* TODO(campbell): unlike non-mapped modes we don't generate these on demand, just use if they exist.
2762                  * this seems like a low priority TODO since mapped meshes typically
2763                  * use the final mesh evaluated mesh for showing faces. */
2764                 const float (*lnors)[3] = CustomData_get_layer(&me_cage->ldata, CD_NORMAL);
2765
2766                 /* TODO(campbell): this is quite an expensive operation for something
2767                  * that's not used unless 'normal' display option is enabled. */
2768                 if (!CustomData_has_layer(&me_cage->pdata, CD_NORMAL)) {
2769                         /* TODO(campbell): this is quite an expensive operation for something
2770                          * that's not used unless 'normal' display option is enabled. */
2771                         BKE_mesh_ensure_normals_for_display(me_cage);
2772                 }
2773                 const float (*polynors)[3] = CustomData_get_layer(&me_cage->pdata, CD_NORMAL);
2774
2775                 const MVert *mvert = rdata->mapped.me_cage->mvert;
2776                 const MLoop *mloop = rdata->mapped.me_cage->mloop;
2777                 const MPoly *mpoly = rdata->mapped.me_cage->mpoly;
2778
2779                 const MLoopTri *mlooptri = BKE_mesh_runtime_looptri_ensure(me_cage);
2780                 for (int i = 0; i < tri_len; i++) {
2781                         const MLoopTri *mlt = &mlooptri[i];
2782                         const int p_orig = rdata->mapped.p_origindex[mlt->poly];
2783                         if (p_orig != ORIGINDEX_NONE) {
2784                                 /* Assume 'use_hide' */
2785                                 BMFace *efa = BM_face_at_index(bm, p_orig);
2786                                 if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
2787                                         const MPoly *mp = &mpoly[mlt->poly];
2788                                         const uint vtri[3] = {
2789                                                 mloop[mlt->tri[0]].v,
2790                                                 mloop[mlt->tri[1]].v,
2791                                                 mloop[mlt->tri[2]].v,
2792                                         };
2793
2794                                         if (lnors) {
2795                                                 for (uint t = 0; t < 3; t++) {
2796                                                         const float *nor = lnors[mlt->tri[t]];
2797                                                         *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_v3(nor);
2798                                                 }
2799                                         }
2800                                         else if (mp->flag & ME_SMOOTH) {
2801                                                 for (uint t = 0; t < 3; t++) {
2802                                                         const MVert *mv = &mvert[vtri[t]];
2803                                                         *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_s3(mv->no);
2804                                                 }
2805                                         }
2806                                         else {
2807                                                 /* we don't have cached 'rdata->poly_normals_pack'. */
2808                                                 const GPUPackedNormal pnor = GPU_normal_convert_i10_v3(polynors[mlt->poly]);
2809                                                 for (uint t = 0; t < 3; t++) {
2810                                                         *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = pnor;
2811                                                 }
2812                                         }
2813
2814                                         for (uint t = 0; t < 3; t++) {
2815                                                 const MVert *mv = &mvert[vtri[t]];
2816                                                 copy_v3_v3(GPU_vertbuf_raw_step(&pos_step), mv->co);
2817                                         }
2818                                 }
2819                         }
2820                 }
2821         }
2822
2823         vbo_len_used = GPU_vertbuf_raw_used(&pos_step);
2824         BLI_assert(vbo_len_used == GPU_vertbuf_raw_used(&nor_step));
2825
2826         if (vbo_len_capacity != vbo_len_used) {
2827                 GPU_vertbuf_data_resize(vbo, vbo_len_used);
2828         }
2829 }
2830
2831 static GPUVertBuf *mesh_batch_cache_get_tri_pos_and_normals_ex(
2832         MeshRenderData *rdata, const bool use_hide,
2833         GPUVertBuf **r_vbo)
2834 {
2835         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_LOOPTRI | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
2836
2837         if (*r_vbo == NULL) {
2838                 *r_vbo = GPU_vertbuf_create(GPU_USAGE_STATIC);
2839                 mesh_create_pos_and_nor_tess(rdata, *r_vbo, use_hide);
2840         }
2841         return *r_vbo;
2842 }
2843
2844 static GPUVertBuf *mesh_batch_cache_get_tri_pos_and_normals_edit(
2845         MeshRenderData *rdata, MeshBatchCache *cache, bool use_hide)
2846 {
2847         return mesh_batch_cache_get_tri_pos_and_normals_ex(
2848                 rdata, use_hide,
2849                 use_hide ? &cache->pos_with_normals_visible_only_edit : &cache->pos_with_normals_edit);
2850 }
2851
2852 /* DEPRECATED Need to be ported */
2853 static GPUVertBuf *mesh_batch_cache_get_facedot_pos_with_normals_and_flag(
2854         MeshRenderData *rdata, MeshBatchCache *cache)
2855 {
2856         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
2857
2858         if (cache->edit.pos_nor_data_facedots == NULL) {
2859                 cache->edit.pos_nor_data_facedots = GPU_vertbuf_create(GPU_USAGE_STATIC);
2860                 mesh_create_edit_facedots(rdata, cache->edit.pos_nor_data_facedots);
2861         }
2862
2863         return cache->edit.pos_nor_data_facedots;
2864 }
2865
2866 static GPUVertBuf *mesh_batch_cache_get_edges_visible(
2867         MeshRenderData *rdata, MeshBatchCache *cache)
2868 {
2869         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_EDGE));
2870
2871         if (cache->ed_edge_pos == NULL) {
2872                 static GPUVertFormat format = { 0 };
2873                 static struct { uint pos, data; } attr_id;
2874                 if (format.attr_len == 0) {
2875                         attr_id.pos = GPU_vertformat_attr_add(&format, "pos", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
2876                 }
2877
2878                 const int vbo_len_capacity = mesh_render_data_edges_len_get_maybe_mapped(rdata) * 2;
2879                 int vidx = 0;
2880
2881                 GPUVertBuf *vbo = cache->ed_edge_pos = GPU_vertbuf_create_with_format(&format);
2882                 GPU_vertbuf_data_alloc(vbo, vbo_len_capacity);
2883
2884                 if (rdata->mapped.use == false) {
2885                         if (rdata->edit_bmesh) {
2886                                 BMesh *bm = rdata->edit_bmesh->bm;
2887                                 BMIter iter;
2888                                 BMEdge *eed;
2889
2890                                 BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
2891                                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
2892                                                 GPU_vertbuf_attr_set(vbo, attr_id.pos, vidx, eed->v1->co);
2893                                                 vidx += 1;
2894                                                 GPU_vertbuf_attr_set(vbo, attr_id.pos, vidx, eed->v2->co);
2895                                                 vidx += 1;
2896                                         }
2897                                 }
2898                         }
2899                         else {
2900                                 /* not yet done! */
2901                                 BLI_assert(0);
2902                         }
2903                 }
2904                 else {
2905                         BMesh *bm = rdata->edit_bmesh->bm;
2906                         const MVert *mvert = rdata->mapped.me_cage->mvert;
2907                         const MEdge *medge = rdata->mapped.me_cage->medge;
2908                         const int *e_origindex = rdata->mapped.e_origindex;
2909                         for (int i = 0; i < rdata->mapped.edge_len; i++) {
2910                                 const int e_orig = e_origindex[i];
2911                                 if (e_orig != ORIGINDEX_NONE) {
2912                                         BMEdge *eed = BM_edge_at_index(bm, e_orig);
2913                                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
2914                                                 const MEdge *ed = &medge[i];
2915                     &