ClangFormat: apply to source, most of intern
[blender.git] / source / blender / blenkernel / intern / subdiv_mesh.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2018 by Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23
24 #include "BKE_subdiv_mesh.h"
25
26 #include "atomic_ops.h"
27
28 #include "DNA_mesh_types.h"
29 #include "DNA_meshdata_types.h"
30 #include "DNA_key_types.h"
31
32 #include "BLI_alloca.h"
33 #include "BLI_math_vector.h"
34
35 #include "BKE_customdata.h"
36 #include "BKE_mesh.h"
37 #include "BKE_key.h"
38 #include "BKE_subdiv.h"
39 #include "BKE_subdiv_eval.h"
40 #include "BKE_subdiv_foreach.h"
41
42 #include "MEM_guardedalloc.h"
43
44 /* =============================================================================
45  * Subdivision context.
46  */
47
48 typedef struct SubdivMeshContext {
49   const SubdivToMeshSettings *settings;
50   const Mesh *coarse_mesh;
51   Subdiv *subdiv;
52   Mesh *subdiv_mesh;
53   /* Cached custom data arrays for fastter access. */
54   int *vert_origindex;
55   int *edge_origindex;
56   int *loop_origindex;
57   int *poly_origindex;
58   /* UV layers interpolation. */
59   int num_uv_layers;
60   MLoopUV *uv_layers[MAX_MTFACE];
61   /* Accumulated values.
62    *
63    * Averaging is happening for vertices along the coarse edges and corners.
64    * This is needed for both displacement and normals.
65    *
66    * Displacement is being accumulated to a verticies coordinates, since those
67    * are not needed during traversal of edge/corner vertices.
68    *
69    * For normals we are using dedicated array, since we can not use same
70    * vertices (normals are `short`, which will cause a lot of precision
71    * issues). */
72   float (*accumulated_normals)[3];
73   /* Per-subdivided vertex counter of averaged values. */
74   int *accumulated_counters;
75   /* Denotes whether normals can be evaluated from a limit surface. One case
76    * when it's not possible is when displacement is used. */
77   bool can_evaluate_normals;
78   bool have_displacement;
79 } SubdivMeshContext;
80
81 static void subdiv_mesh_ctx_cache_uv_layers(SubdivMeshContext *ctx)
82 {
83   Mesh *subdiv_mesh = ctx->subdiv_mesh;
84   ctx->num_uv_layers = CustomData_number_of_layers(&subdiv_mesh->ldata, CD_MLOOPUV);
85   for (int layer_index = 0; layer_index < ctx->num_uv_layers; ++layer_index) {
86     ctx->uv_layers[layer_index] = CustomData_get_layer_n(
87         &subdiv_mesh->ldata, CD_MLOOPUV, layer_index);
88   }
89 }
90
91 static void subdiv_mesh_ctx_cache_custom_data_layers(SubdivMeshContext *ctx)
92 {
93   Mesh *subdiv_mesh = ctx->subdiv_mesh;
94   /* Pointers to original indices layers. */
95   ctx->vert_origindex = CustomData_get_layer(&subdiv_mesh->vdata, CD_ORIGINDEX);
96   ctx->edge_origindex = CustomData_get_layer(&subdiv_mesh->edata, CD_ORIGINDEX);
97   ctx->loop_origindex = CustomData_get_layer(&subdiv_mesh->ldata, CD_ORIGINDEX);
98   ctx->poly_origindex = CustomData_get_layer(&subdiv_mesh->pdata, CD_ORIGINDEX);
99   /* UV layers interpolation. */
100   subdiv_mesh_ctx_cache_uv_layers(ctx);
101 }
102
103 static void subdiv_mesh_prepare_accumulator(SubdivMeshContext *ctx, int num_vertices)
104 {
105   if (!ctx->can_evaluate_normals && !ctx->have_displacement) {
106     return;
107   }
108   /* TODO(sergey): Technically, this is overallocating, we don't need memory
109    * for an inner subdivision vertices. */
110   ctx->accumulated_normals = MEM_calloc_arrayN(
111       sizeof(*ctx->accumulated_normals), num_vertices, "subdiv accumulated normals");
112   ctx->accumulated_counters = MEM_calloc_arrayN(
113       sizeof(*ctx->accumulated_counters), num_vertices, "subdiv accumulated counters");
114 }
115
116 static void subdiv_mesh_context_free(SubdivMeshContext *ctx)
117 {
118   MEM_SAFE_FREE(ctx->accumulated_normals);
119   MEM_SAFE_FREE(ctx->accumulated_counters);
120 }
121
122 /* =============================================================================
123  * Loop custom data copy helpers.
124  */
125
126 typedef struct LoopsOfPtex {
127   /* First loop of the ptex, starts at ptex (0, 0) and goes in u direction. */
128   const MLoop *first_loop;
129   /* Last loop of the ptex, starts at ptex (0, 0) and goes in v direction. */
130   const MLoop *last_loop;
131   /* For quad coarse faces only. */
132   const MLoop *second_loop;
133   const MLoop *third_loop;
134 } LoopsOfPtex;
135
136 static void loops_of_ptex_get(const SubdivMeshContext *ctx,
137                               LoopsOfPtex *loops_of_ptex,
138                               const MPoly *coarse_poly,
139                               const int ptex_of_poly_index)
140 {
141   const MLoop *coarse_mloop = ctx->coarse_mesh->mloop;
142   const int first_ptex_loop_index = coarse_poly->loopstart + ptex_of_poly_index;
143   /* Loop which look in the (opposite) V direction of the current
144    * ptex face.
145    *
146    * TODO(sergey): Get rid of using module on every iteration. */
147   const int last_ptex_loop_index = coarse_poly->loopstart +
148                                    (ptex_of_poly_index + coarse_poly->totloop - 1) %
149                                        coarse_poly->totloop;
150   loops_of_ptex->first_loop = &coarse_mloop[first_ptex_loop_index];
151   loops_of_ptex->last_loop = &coarse_mloop[last_ptex_loop_index];
152   if (coarse_poly->totloop == 4) {
153     loops_of_ptex->second_loop = loops_of_ptex->first_loop + 1;
154     loops_of_ptex->third_loop = loops_of_ptex->first_loop + 2;
155   }
156   else {
157     loops_of_ptex->second_loop = NULL;
158     loops_of_ptex->third_loop = NULL;
159   }
160 }
161
162 /* =============================================================================
163  * Vertex custom data interpolation helpers.
164  */
165
166 /* TODO(sergey): Somehow de-duplicate with loops storage, without too much
167  * exception cases all over the code. */
168
169 typedef struct VerticesForInterpolation {
170   /* This field points to a vertex data which is to be used for interpolation.
171    * The idea is to avoid unnecessary allocations for regular faces, where
172    * we can simply use corner verticies. */
173   const CustomData *vertex_data;
174   /* Vertices data calculated for ptex corners. There are always 4 elements
175    * in this custom data, aligned the following way:
176    *
177    *   index 0 -> uv (0, 0)
178    *   index 1 -> uv (0, 1)
179    *   index 2 -> uv (1, 1)
180    *   index 3 -> uv (1, 0)
181    *
182    * Is allocated for non-regular faces (triangles and n-gons). */
183   CustomData vertex_data_storage;
184   bool vertex_data_storage_allocated;
185   /* Infices within vertex_data to interpolate for. The indices are aligned
186    * with uv coordinates in a similar way as indices in loop_data_storage. */
187   int vertex_indices[4];
188 } VerticesForInterpolation;
189
190 static void vertex_interpolation_init(const SubdivMeshContext *ctx,
191                                       VerticesForInterpolation *vertex_interpolation,
192                                       const MPoly *coarse_poly)
193 {
194   const Mesh *coarse_mesh = ctx->coarse_mesh;
195   const MLoop *coarse_mloop = coarse_mesh->mloop;
196   if (coarse_poly->totloop == 4) {
197     vertex_interpolation->vertex_data = &coarse_mesh->vdata;
198     vertex_interpolation->vertex_indices[0] = coarse_mloop[coarse_poly->loopstart + 0].v;
199     vertex_interpolation->vertex_indices[1] = coarse_mloop[coarse_poly->loopstart + 1].v;
200     vertex_interpolation->vertex_indices[2] = coarse_mloop[coarse_poly->loopstart + 2].v;
201     vertex_interpolation->vertex_indices[3] = coarse_mloop[coarse_poly->loopstart + 3].v;
202     vertex_interpolation->vertex_data_storage_allocated = false;
203   }
204   else {
205     vertex_interpolation->vertex_data = &vertex_interpolation->vertex_data_storage;
206     /* Allocate storage for loops corresponding to ptex corners. */
207     CustomData_copy(&ctx->coarse_mesh->vdata,
208                     &vertex_interpolation->vertex_data_storage,
209                     CD_MASK_EVERYTHING.vmask,
210                     CD_CALLOC,
211                     4);
212     /* Initialize indices. */
213     vertex_interpolation->vertex_indices[0] = 0;
214     vertex_interpolation->vertex_indices[1] = 1;
215     vertex_interpolation->vertex_indices[2] = 2;
216     vertex_interpolation->vertex_indices[3] = 3;
217     vertex_interpolation->vertex_data_storage_allocated = true;
218     /* Interpolate center of poly right away, it stays unchanged for all
219      * ptex faces. */
220     const float weight = 1.0f / (float)coarse_poly->totloop;
221     float *weights = BLI_array_alloca(weights, coarse_poly->totloop);
222     int *indices = BLI_array_alloca(indices, coarse_poly->totloop);
223     for (int i = 0; i < coarse_poly->totloop; ++i) {
224       weights[i] = weight;
225       indices[i] = coarse_mloop[coarse_poly->loopstart + i].v;
226     }
227     CustomData_interp(&coarse_mesh->vdata,
228                       &vertex_interpolation->vertex_data_storage,
229                       indices,
230                       weights,
231                       NULL,
232                       coarse_poly->totloop,
233                       2);
234   }
235 }
236
237 static void vertex_interpolation_from_corner(const SubdivMeshContext *ctx,
238                                              VerticesForInterpolation *vertex_interpolation,
239                                              const MPoly *coarse_poly,
240                                              const int corner)
241 {
242   if (coarse_poly->totloop == 4) {
243     /* Nothing to do, all indices and data is already assigned. */
244   }
245   else {
246     const CustomData *vertex_data = &ctx->coarse_mesh->vdata;
247     const Mesh *coarse_mesh = ctx->coarse_mesh;
248     const MLoop *coarse_mloop = coarse_mesh->mloop;
249     LoopsOfPtex loops_of_ptex;
250     loops_of_ptex_get(ctx, &loops_of_ptex, coarse_poly, corner);
251     /* Ptex face corner corresponds to a poly loop with same index. */
252     CustomData_copy_data(vertex_data,
253                          &vertex_interpolation->vertex_data_storage,
254                          coarse_mloop[coarse_poly->loopstart + corner].v,
255                          0,
256                          1);
257     /* Interpolate remaining ptex face corners, which hits loops
258      * middle points.
259      *
260      * TODO(sergey): Re-use one of interpolation results from previous
261      * iteration. */
262     const float weights[2] = {0.5f, 0.5f};
263     const int first_loop_index = loops_of_ptex.first_loop - coarse_mloop;
264     const int last_loop_index = loops_of_ptex.last_loop - coarse_mloop;
265     const int first_indices[2] = {
266         coarse_mloop[first_loop_index].v,
267         coarse_mloop[coarse_poly->loopstart +
268                      (first_loop_index - coarse_poly->loopstart + 1) % coarse_poly->totloop]
269             .v};
270     const int last_indices[2] = {coarse_mloop[first_loop_index].v,
271                                  coarse_mloop[last_loop_index].v};
272     CustomData_interp(vertex_data,
273                       &vertex_interpolation->vertex_data_storage,
274                       first_indices,
275                       weights,
276                       NULL,
277                       2,
278                       1);
279     CustomData_interp(vertex_data,
280                       &vertex_interpolation->vertex_data_storage,
281                       last_indices,
282                       weights,
283                       NULL,
284                       2,
285                       3);
286   }
287 }
288
289 static void vertex_interpolation_end(VerticesForInterpolation *vertex_interpolation)
290 {
291   if (vertex_interpolation->vertex_data_storage_allocated) {
292     CustomData_free(&vertex_interpolation->vertex_data_storage, 4);
293   }
294 }
295
296 /* =============================================================================
297  * Loop custom data interpolation helpers.
298  */
299
300 typedef struct LoopsForInterpolation {
301   /* This field points to a loop data which is to be used for interpolation.
302    * The idea is to avoid unnecessary allocations for regular faces, where
303    * we can simply interpolate corner verticies. */
304   const CustomData *loop_data;
305   /* Loops data calculated for ptex corners. There are always 4 elements
306    * in this custom data, aligned the following way:
307    *
308    *   index 0 -> uv (0, 0)
309    *   index 1 -> uv (0, 1)
310    *   index 2 -> uv (1, 1)
311    *   index 3 -> uv (1, 0)
312    *
313    * Is allocated for non-regular faces (triangles and n-gons). */
314   CustomData loop_data_storage;
315   bool loop_data_storage_allocated;
316   /* Infices within loop_data to interpolate for. The indices are aligned with
317    * uv coordinates in a similar way as indices in loop_data_storage. */
318   int loop_indices[4];
319 } LoopsForInterpolation;
320
321 static void loop_interpolation_init(const SubdivMeshContext *ctx,
322                                     LoopsForInterpolation *loop_interpolation,
323                                     const MPoly *coarse_poly)
324 {
325   const Mesh *coarse_mesh = ctx->coarse_mesh;
326   if (coarse_poly->totloop == 4) {
327     loop_interpolation->loop_data = &coarse_mesh->ldata;
328     loop_interpolation->loop_indices[0] = coarse_poly->loopstart + 0;
329     loop_interpolation->loop_indices[1] = coarse_poly->loopstart + 1;
330     loop_interpolation->loop_indices[2] = coarse_poly->loopstart + 2;
331     loop_interpolation->loop_indices[3] = coarse_poly->loopstart + 3;
332     loop_interpolation->loop_data_storage_allocated = false;
333   }
334   else {
335     loop_interpolation->loop_data = &loop_interpolation->loop_data_storage;
336     /* Allocate storage for loops corresponding to ptex corners. */
337     CustomData_copy(&ctx->coarse_mesh->ldata,
338                     &loop_interpolation->loop_data_storage,
339                     CD_MASK_EVERYTHING.lmask,
340                     CD_CALLOC,
341                     4);
342     /* Initialize indices. */
343     loop_interpolation->loop_indices[0] = 0;
344     loop_interpolation->loop_indices[1] = 1;
345     loop_interpolation->loop_indices[2] = 2;
346     loop_interpolation->loop_indices[3] = 3;
347     loop_interpolation->loop_data_storage_allocated = true;
348     /* Interpolate center of poly right away, it stays unchanged for all
349      * ptex faces. */
350     const float weight = 1.0f / (float)coarse_poly->totloop;
351     float *weights = BLI_array_alloca(weights, coarse_poly->totloop);
352     int *indices = BLI_array_alloca(indices, coarse_poly->totloop);
353     for (int i = 0; i < coarse_poly->totloop; ++i) {
354       weights[i] = weight;
355       indices[i] = coarse_poly->loopstart + i;
356     }
357     CustomData_interp(&coarse_mesh->ldata,
358                       &loop_interpolation->loop_data_storage,
359                       indices,
360                       weights,
361                       NULL,
362                       coarse_poly->totloop,
363                       2);
364   }
365 }
366
367 static void loop_interpolation_from_corner(const SubdivMeshContext *ctx,
368                                            LoopsForInterpolation *loop_interpolation,
369                                            const MPoly *coarse_poly,
370                                            const int corner)
371 {
372   if (coarse_poly->totloop == 4) {
373     /* Nothing to do, all indices and data is already assigned. */
374   }
375   else {
376     const CustomData *loop_data = &ctx->coarse_mesh->ldata;
377     const Mesh *coarse_mesh = ctx->coarse_mesh;
378     const MLoop *coarse_mloop = coarse_mesh->mloop;
379     LoopsOfPtex loops_of_ptex;
380     loops_of_ptex_get(ctx, &loops_of_ptex, coarse_poly, corner);
381     /* Ptex face corner corresponds to a poly loop with same index. */
382     CustomData_free_elem(&loop_interpolation->loop_data_storage, 0, 1);
383     CustomData_copy_data(
384         loop_data, &loop_interpolation->loop_data_storage, coarse_poly->loopstart + corner, 0, 1);
385     /* Interpolate remaining ptex face corners, which hits loops
386      * middle points.
387      *
388      * TODO(sergey): Re-use one of interpolation results from previous
389      * iteration. */
390     const float weights[2] = {0.5f, 0.5f};
391     const int base_loop_index = coarse_poly->loopstart;
392     const int first_loop_index = loops_of_ptex.first_loop - coarse_mloop;
393     const int second_loop_index = base_loop_index +
394                                   (first_loop_index - base_loop_index + 1) % coarse_poly->totloop;
395     const int first_indices[2] = {first_loop_index, second_loop_index};
396     const int last_indices[2] = {loops_of_ptex.last_loop - coarse_mloop,
397                                  loops_of_ptex.first_loop - coarse_mloop};
398     CustomData_interp(
399         loop_data, &loop_interpolation->loop_data_storage, first_indices, weights, NULL, 2, 1);
400     CustomData_interp(
401         loop_data, &loop_interpolation->loop_data_storage, last_indices, weights, NULL, 2, 3);
402   }
403 }
404
405 static void loop_interpolation_end(LoopsForInterpolation *loop_interpolation)
406 {
407   if (loop_interpolation->loop_data_storage_allocated) {
408     CustomData_free(&loop_interpolation->loop_data_storage, 4);
409   }
410 }
411
412 /* =============================================================================
413  * TLS.
414  */
415
416 typedef struct SubdivMeshTLS {
417   bool vertex_interpolation_initialized;
418   VerticesForInterpolation vertex_interpolation;
419   const MPoly *vertex_interpolation_coarse_poly;
420   int vertex_interpolation_coarse_corner;
421
422   bool loop_interpolation_initialized;
423   LoopsForInterpolation loop_interpolation;
424   const MPoly *loop_interpolation_coarse_poly;
425   int loop_interpolation_coarse_corner;
426 } SubdivMeshTLS;
427
428 static void subdiv_mesh_tls_free(void *tls_v)
429 {
430   SubdivMeshTLS *tls = tls_v;
431   if (tls->vertex_interpolation_initialized) {
432     vertex_interpolation_end(&tls->vertex_interpolation);
433   }
434   if (tls->loop_interpolation_initialized) {
435     loop_interpolation_end(&tls->loop_interpolation);
436   }
437 }
438
439 /* =============================================================================
440  * Evaluation helper functions.
441  */
442
443 static void eval_final_point_and_vertex_normal(Subdiv *subdiv,
444                                                const int ptex_face_index,
445                                                const float u,
446                                                const float v,
447                                                float r_P[3],
448                                                short r_N[3])
449 {
450   if (subdiv->displacement_evaluator == NULL) {
451     BKE_subdiv_eval_limit_point_and_short_normal(subdiv, ptex_face_index, u, v, r_P, r_N);
452   }
453   else {
454     BKE_subdiv_eval_final_point(subdiv, ptex_face_index, u, v, r_P);
455   }
456 }
457
458 /* =============================================================================
459  * Accumulation helpers.
460  */
461
462 static void subdiv_accumulate_vertex_normal_and_displacement(SubdivMeshContext *ctx,
463                                                              const int ptex_face_index,
464                                                              const float u,
465                                                              const float v,
466                                                              MVert *subdiv_vert)
467 {
468   Subdiv *subdiv = ctx->subdiv;
469   const int subdiv_vertex_index = subdiv_vert - ctx->subdiv_mesh->mvert;
470   float dummy_P[3], dPdu[3], dPdv[3], D[3];
471   BKE_subdiv_eval_limit_point_and_derivatives(subdiv, ptex_face_index, u, v, dummy_P, dPdu, dPdv);
472   /* Accumulate normal. */
473   if (ctx->can_evaluate_normals) {
474     float N[3];
475     cross_v3_v3v3(N, dPdu, dPdv);
476     normalize_v3(N);
477     add_v3_v3(ctx->accumulated_normals[subdiv_vertex_index], N);
478   }
479   /* Accumulate displacement if needed. */
480   if (ctx->have_displacement) {
481     BKE_subdiv_eval_displacement(subdiv, ptex_face_index, u, v, dPdu, dPdv, D);
482     add_v3_v3(subdiv_vert->co, D);
483   }
484   ++ctx->accumulated_counters[subdiv_vertex_index];
485 }
486
487 /* =============================================================================
488  * Callbacks.
489  */
490
491 static bool subdiv_mesh_topology_info(const SubdivForeachContext *foreach_context,
492                                       const int num_vertices,
493                                       const int num_edges,
494                                       const int num_loops,
495                                       const int num_polygons)
496 {
497   SubdivMeshContext *subdiv_context = foreach_context->user_data;
498   subdiv_context->subdiv_mesh = BKE_mesh_new_nomain_from_template(
499       subdiv_context->coarse_mesh, num_vertices, num_edges, 0, num_loops, num_polygons);
500   subdiv_mesh_ctx_cache_custom_data_layers(subdiv_context);
501   subdiv_mesh_prepare_accumulator(subdiv_context, num_vertices);
502   return true;
503 }
504
505 /* =============================================================================
506  * Vertex subdivision process.
507  */
508
509 static void subdiv_vertex_data_copy(const SubdivMeshContext *ctx,
510                                     const MVert *coarse_vertex,
511                                     MVert *subdiv_vertex)
512 {
513   const Mesh *coarse_mesh = ctx->coarse_mesh;
514   Mesh *subdiv_mesh = ctx->subdiv_mesh;
515   const int coarse_vertex_index = coarse_vertex - coarse_mesh->mvert;
516   const int subdiv_vertex_index = subdiv_vertex - subdiv_mesh->mvert;
517   CustomData_copy_data(
518       &coarse_mesh->vdata, &ctx->subdiv_mesh->vdata, coarse_vertex_index, subdiv_vertex_index, 1);
519 }
520
521 static void subdiv_vertex_data_interpolate(const SubdivMeshContext *ctx,
522                                            MVert *subdiv_vertex,
523                                            const VerticesForInterpolation *vertex_interpolation,
524                                            const float u,
525                                            const float v)
526 {
527   const int subdiv_vertex_index = subdiv_vertex - ctx->subdiv_mesh->mvert;
528   const float weights[4] = {(1.0f - u) * (1.0f - v), u * (1.0f - v), u * v, (1.0f - u) * v};
529   CustomData_interp(vertex_interpolation->vertex_data,
530                     &ctx->subdiv_mesh->vdata,
531                     vertex_interpolation->vertex_indices,
532                     weights,
533                     NULL,
534                     4,
535                     subdiv_vertex_index);
536   if (ctx->vert_origindex != NULL) {
537     ctx->vert_origindex[subdiv_vertex_index] = ORIGINDEX_NONE;
538   }
539 }
540
541 static void evaluate_vertex_and_apply_displacement_copy(const SubdivMeshContext *ctx,
542                                                         const int ptex_face_index,
543                                                         const float u,
544                                                         const float v,
545                                                         const MVert *coarse_vert,
546                                                         MVert *subdiv_vert)
547 {
548   const int subdiv_vertex_index = subdiv_vert - ctx->subdiv_mesh->mvert;
549   const float inv_num_accumulated = 1.0f / ctx->accumulated_counters[subdiv_vertex_index];
550   /* Displacement is accumulated in subdiv vertex position.
551    * Needs to be backed up before copying data from original vertex. */
552   float D[3] = {0.0f, 0.0f, 0.0f};
553   if (ctx->have_displacement) {
554     copy_v3_v3(D, subdiv_vert->co);
555     mul_v3_fl(D, inv_num_accumulated);
556   }
557   /* Copy custom data and evaluate position. */
558   subdiv_vertex_data_copy(ctx, coarse_vert, subdiv_vert);
559   BKE_subdiv_eval_limit_point(ctx->subdiv, ptex_face_index, u, v, subdiv_vert->co);
560   /* Apply displacement. */
561   add_v3_v3(subdiv_vert->co, D);
562   /* Copy normal from accumulated storage. */
563   if (ctx->can_evaluate_normals) {
564     float N[3];
565     copy_v3_v3(N, ctx->accumulated_normals[subdiv_vertex_index]);
566     normalize_v3(N);
567     normal_float_to_short_v3(subdiv_vert->no, N);
568   }
569 }
570
571 static void evaluate_vertex_and_apply_displacement_interpolate(
572     const SubdivMeshContext *ctx,
573     const int ptex_face_index,
574     const float u,
575     const float v,
576     VerticesForInterpolation *vertex_interpolation,
577     MVert *subdiv_vert)
578 {
579   const int subdiv_vertex_index = subdiv_vert - ctx->subdiv_mesh->mvert;
580   const float inv_num_accumulated = 1.0f / ctx->accumulated_counters[subdiv_vertex_index];
581   /* Displacement is accumulated in subdiv vertex position.
582    * Needs to be backed up before copying data from original vertex. */
583   float D[3] = {0.0f, 0.0f, 0.0f};
584   if (ctx->have_displacement) {
585     copy_v3_v3(D, subdiv_vert->co);
586     mul_v3_fl(D, inv_num_accumulated);
587   }
588   /* Interpolate custom data and evaluate position. */
589   subdiv_vertex_data_interpolate(ctx, subdiv_vert, vertex_interpolation, u, v);
590   BKE_subdiv_eval_limit_point(ctx->subdiv, ptex_face_index, u, v, subdiv_vert->co);
591   /* Apply displacement. */
592   add_v3_v3(subdiv_vert->co, D);
593   /* Copy normal from accumulated storage. */
594   if (ctx->can_evaluate_normals) {
595     float N[3];
596     copy_v3_v3(N, ctx->accumulated_normals[subdiv_vertex_index]);
597     mul_v3_fl(N, inv_num_accumulated);
598     normalize_v3(N);
599     normal_float_to_short_v3(subdiv_vert->no, N);
600   }
601 }
602
603 static void subdiv_mesh_vertex_every_corner_or_edge(const SubdivForeachContext *foreach_context,
604                                                     void *UNUSED(tls),
605                                                     const int ptex_face_index,
606                                                     const float u,
607                                                     const float v,
608                                                     const int subdiv_vertex_index)
609 {
610   SubdivMeshContext *ctx = foreach_context->user_data;
611   Mesh *subdiv_mesh = ctx->subdiv_mesh;
612   MVert *subdiv_mvert = subdiv_mesh->mvert;
613   MVert *subdiv_vert = &subdiv_mvert[subdiv_vertex_index];
614   subdiv_accumulate_vertex_normal_and_displacement(ctx, ptex_face_index, u, v, subdiv_vert);
615 }
616
617 static void subdiv_mesh_vertex_every_corner(const SubdivForeachContext *foreach_context,
618                                             void *tls,
619                                             const int ptex_face_index,
620                                             const float u,
621                                             const float v,
622                                             const int UNUSED(coarse_vertex_index),
623                                             const int UNUSED(coarse_poly_index),
624                                             const int UNUSED(coarse_corner),
625                                             const int subdiv_vertex_index)
626 {
627   subdiv_mesh_vertex_every_corner_or_edge(
628       foreach_context, tls, ptex_face_index, u, v, subdiv_vertex_index);
629 }
630
631 static void subdiv_mesh_vertex_every_edge(const SubdivForeachContext *foreach_context,
632                                           void *tls,
633                                           const int ptex_face_index,
634                                           const float u,
635                                           const float v,
636                                           const int UNUSED(coarse_edge_index),
637                                           const int UNUSED(coarse_poly_index),
638                                           const int UNUSED(coarse_corner),
639                                           const int subdiv_vertex_index)
640 {
641   subdiv_mesh_vertex_every_corner_or_edge(
642       foreach_context, tls, ptex_face_index, u, v, subdiv_vertex_index);
643 }
644
645 static void subdiv_mesh_vertex_corner(const SubdivForeachContext *foreach_context,
646                                       void *UNUSED(tls),
647                                       const int ptex_face_index,
648                                       const float u,
649                                       const float v,
650                                       const int coarse_vertex_index,
651                                       const int UNUSED(coarse_poly_index),
652                                       const int UNUSED(coarse_corner),
653                                       const int subdiv_vertex_index)
654 {
655   BLI_assert(coarse_vertex_index != ORIGINDEX_NONE);
656   SubdivMeshContext *ctx = foreach_context->user_data;
657   const Mesh *coarse_mesh = ctx->coarse_mesh;
658   const MVert *coarse_mvert = coarse_mesh->mvert;
659   Mesh *subdiv_mesh = ctx->subdiv_mesh;
660   MVert *subdiv_mvert = subdiv_mesh->mvert;
661   const MVert *coarse_vert = &coarse_mvert[coarse_vertex_index];
662   MVert *subdiv_vert = &subdiv_mvert[subdiv_vertex_index];
663   evaluate_vertex_and_apply_displacement_copy(
664       ctx, ptex_face_index, u, v, coarse_vert, subdiv_vert);
665 }
666
667 static void subdiv_mesh_ensure_vertex_interpolation(SubdivMeshContext *ctx,
668                                                     SubdivMeshTLS *tls,
669                                                     const MPoly *coarse_poly,
670                                                     const int coarse_corner)
671 {
672   /* Check whether we've moved to another corner or polygon. */
673   if (tls->vertex_interpolation_initialized) {
674     if (tls->vertex_interpolation_coarse_poly != coarse_poly ||
675         tls->vertex_interpolation_coarse_corner != coarse_corner) {
676       vertex_interpolation_end(&tls->vertex_interpolation);
677       tls->vertex_interpolation_initialized = false;
678     }
679   }
680   /* Initialize the interpolation. */
681   if (!tls->vertex_interpolation_initialized) {
682     vertex_interpolation_init(ctx, &tls->vertex_interpolation, coarse_poly);
683   }
684   /* Update it for a new corner if needed. */
685   if (!tls->vertex_interpolation_initialized ||
686       tls->vertex_interpolation_coarse_corner != coarse_corner) {
687     vertex_interpolation_from_corner(ctx, &tls->vertex_interpolation, coarse_poly, coarse_corner);
688   }
689   /* Store settings used for the current state of interpolator. */
690   tls->vertex_interpolation_initialized = true;
691   tls->vertex_interpolation_coarse_poly = coarse_poly;
692   tls->vertex_interpolation_coarse_corner = coarse_corner;
693 }
694
695 static void subdiv_mesh_vertex_edge(const SubdivForeachContext *foreach_context,
696                                     void *tls_v,
697                                     const int ptex_face_index,
698                                     const float u,
699                                     const float v,
700                                     const int UNUSED(coarse_edge_index),
701                                     const int coarse_poly_index,
702                                     const int coarse_corner,
703                                     const int subdiv_vertex_index)
704 {
705   SubdivMeshContext *ctx = foreach_context->user_data;
706   SubdivMeshTLS *tls = tls_v;
707   const Mesh *coarse_mesh = ctx->coarse_mesh;
708   const MPoly *coarse_mpoly = coarse_mesh->mpoly;
709   const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
710   Mesh *subdiv_mesh = ctx->subdiv_mesh;
711   MVert *subdiv_mvert = subdiv_mesh->mvert;
712   MVert *subdiv_vert = &subdiv_mvert[subdiv_vertex_index];
713   subdiv_mesh_ensure_vertex_interpolation(ctx, tls, coarse_poly, coarse_corner);
714   evaluate_vertex_and_apply_displacement_interpolate(
715       ctx, ptex_face_index, u, v, &tls->vertex_interpolation, subdiv_vert);
716 }
717
718 static void subdiv_mesh_vertex_inner(const SubdivForeachContext *foreach_context,
719                                      void *tls_v,
720                                      const int ptex_face_index,
721                                      const float u,
722                                      const float v,
723                                      const int coarse_poly_index,
724                                      const int coarse_corner,
725                                      const int subdiv_vertex_index)
726 {
727   SubdivMeshContext *ctx = foreach_context->user_data;
728   SubdivMeshTLS *tls = tls_v;
729   Subdiv *subdiv = ctx->subdiv;
730   const Mesh *coarse_mesh = ctx->coarse_mesh;
731   const MPoly *coarse_mpoly = coarse_mesh->mpoly;
732   const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
733   Mesh *subdiv_mesh = ctx->subdiv_mesh;
734   MVert *subdiv_mvert = subdiv_mesh->mvert;
735   MVert *subdiv_vert = &subdiv_mvert[subdiv_vertex_index];
736   subdiv_mesh_ensure_vertex_interpolation(ctx, tls, coarse_poly, coarse_corner);
737   subdiv_vertex_data_interpolate(ctx, subdiv_vert, &tls->vertex_interpolation, u, v);
738   eval_final_point_and_vertex_normal(
739       subdiv, ptex_face_index, u, v, subdiv_vert->co, subdiv_vert->no);
740 }
741
742 /* =============================================================================
743  * Edge subdivision process.
744  */
745
746 static void subdiv_copy_edge_data(SubdivMeshContext *ctx,
747                                   MEdge *subdiv_edge,
748                                   const MEdge *coarse_edge)
749 {
750   const int subdiv_edge_index = subdiv_edge - ctx->subdiv_mesh->medge;
751   if (coarse_edge == NULL) {
752     subdiv_edge->crease = 0;
753     subdiv_edge->bweight = 0;
754     subdiv_edge->flag = 0;
755     if (!ctx->settings->use_optimal_display) {
756       subdiv_edge->flag |= ME_EDGERENDER;
757     }
758     if (ctx->edge_origindex != NULL) {
759       ctx->edge_origindex[subdiv_edge_index] = ORIGINDEX_NONE;
760     }
761     return;
762   }
763   const int coarse_edge_index = coarse_edge - ctx->coarse_mesh->medge;
764   CustomData_copy_data(
765       &ctx->coarse_mesh->edata, &ctx->subdiv_mesh->edata, coarse_edge_index, subdiv_edge_index, 1);
766   subdiv_edge->flag |= ME_EDGERENDER;
767 }
768
769 static void subdiv_mesh_edge(const SubdivForeachContext *foreach_context,
770                              void *UNUSED(tls),
771                              const int coarse_edge_index,
772                              const int subdiv_edge_index,
773                              const int subdiv_v1,
774                              const int subdiv_v2)
775 {
776   SubdivMeshContext *ctx = foreach_context->user_data;
777   Mesh *subdiv_mesh = ctx->subdiv_mesh;
778   MEdge *subdiv_medge = subdiv_mesh->medge;
779   MEdge *subdiv_edge = &subdiv_medge[subdiv_edge_index];
780   const MEdge *coarse_edge = NULL;
781   if (coarse_edge_index != ORIGINDEX_NONE) {
782     const Mesh *coarse_mesh = ctx->coarse_mesh;
783     const MEdge *coarse_medge = coarse_mesh->medge;
784     coarse_edge = &coarse_medge[coarse_edge_index];
785   }
786   subdiv_copy_edge_data(ctx, subdiv_edge, coarse_edge);
787   subdiv_edge->v1 = subdiv_v1;
788   subdiv_edge->v2 = subdiv_v2;
789 }
790
791 /* =============================================================================
792  * Loops creation/interpolation.
793  */
794
795 static void subdiv_interpolate_loop_data(const SubdivMeshContext *ctx,
796                                          MLoop *subdiv_loop,
797                                          const LoopsForInterpolation *loop_interpolation,
798                                          const float u,
799                                          const float v)
800 {
801   const int subdiv_loop_index = subdiv_loop - ctx->subdiv_mesh->mloop;
802   const float weights[4] = {(1.0f - u) * (1.0f - v), u * (1.0f - v), u * v, (1.0f - u) * v};
803   CustomData_interp(loop_interpolation->loop_data,
804                     &ctx->subdiv_mesh->ldata,
805                     loop_interpolation->loop_indices,
806                     weights,
807                     NULL,
808                     4,
809                     subdiv_loop_index);
810   /* TODO(sergey): Set ORIGINDEX. */
811 }
812
813 static void subdiv_eval_uv_layer(SubdivMeshContext *ctx,
814                                  MLoop *subdiv_loop,
815                                  const int ptex_face_index,
816                                  const float u,
817                                  const float v)
818 {
819   if (ctx->num_uv_layers == 0) {
820     return;
821   }
822   Subdiv *subdiv = ctx->subdiv;
823   const int mloop_index = subdiv_loop - ctx->subdiv_mesh->mloop;
824   for (int layer_index = 0; layer_index < ctx->num_uv_layers; layer_index++) {
825     MLoopUV *subdiv_loopuv = &ctx->uv_layers[layer_index][mloop_index];
826     BKE_subdiv_eval_face_varying(subdiv, layer_index, ptex_face_index, u, v, subdiv_loopuv->uv);
827   }
828 }
829
830 static void subdiv_mesh_ensure_loop_interpolation(SubdivMeshContext *ctx,
831                                                   SubdivMeshTLS *tls,
832                                                   const MPoly *coarse_poly,
833                                                   const int coarse_corner)
834 {
835   /* Check whether we've moved to another corner or polygon. */
836   if (tls->loop_interpolation_initialized) {
837     if (tls->loop_interpolation_coarse_poly != coarse_poly ||
838         tls->loop_interpolation_coarse_corner != coarse_corner) {
839       loop_interpolation_end(&tls->loop_interpolation);
840       tls->loop_interpolation_initialized = false;
841     }
842   }
843   /* Initialize the interpolation. */
844   if (!tls->loop_interpolation_initialized) {
845     loop_interpolation_init(ctx, &tls->loop_interpolation, coarse_poly);
846   }
847   /* Update it for a new corner if needed. */
848   if (!tls->loop_interpolation_initialized ||
849       tls->loop_interpolation_coarse_corner != coarse_corner) {
850     loop_interpolation_from_corner(ctx, &tls->loop_interpolation, coarse_poly, coarse_corner);
851   }
852   /* Store settings used for the current state of interpolator. */
853   tls->loop_interpolation_initialized = true;
854   tls->loop_interpolation_coarse_poly = coarse_poly;
855   tls->loop_interpolation_coarse_corner = coarse_corner;
856 }
857
858 static void subdiv_mesh_loop(const SubdivForeachContext *foreach_context,
859                              void *tls_v,
860                              const int ptex_face_index,
861                              const float u,
862                              const float v,
863                              const int UNUSED(coarse_loop_index),
864                              const int coarse_poly_index,
865                              const int coarse_corner,
866                              const int subdiv_loop_index,
867                              const int subdiv_vertex_index,
868                              const int subdiv_edge_index)
869 {
870   SubdivMeshContext *ctx = foreach_context->user_data;
871   SubdivMeshTLS *tls = tls_v;
872   const Mesh *coarse_mesh = ctx->coarse_mesh;
873   const MPoly *coarse_mpoly = coarse_mesh->mpoly;
874   const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
875   Mesh *subdiv_mesh = ctx->subdiv_mesh;
876   MLoop *subdiv_mloop = subdiv_mesh->mloop;
877   MLoop *subdiv_loop = &subdiv_mloop[subdiv_loop_index];
878   subdiv_mesh_ensure_loop_interpolation(ctx, tls, coarse_poly, coarse_corner);
879   subdiv_interpolate_loop_data(ctx, subdiv_loop, &tls->loop_interpolation, u, v);
880   subdiv_eval_uv_layer(ctx, subdiv_loop, ptex_face_index, u, v);
881   subdiv_loop->v = subdiv_vertex_index;
882   subdiv_loop->e = subdiv_edge_index;
883 }
884
885 /* =============================================================================
886  * Polygons subdivision process.
887  */
888
889 static void subdiv_copy_poly_data(const SubdivMeshContext *ctx,
890                                   MPoly *subdiv_poly,
891                                   const MPoly *coarse_poly)
892 {
893   const int coarse_poly_index = coarse_poly - ctx->coarse_mesh->mpoly;
894   const int subdiv_poly_index = subdiv_poly - ctx->subdiv_mesh->mpoly;
895   CustomData_copy_data(
896       &ctx->coarse_mesh->pdata, &ctx->subdiv_mesh->pdata, coarse_poly_index, subdiv_poly_index, 1);
897 }
898
899 static void subdiv_mesh_poly(const SubdivForeachContext *foreach_context,
900                              void *UNUSED(tls),
901                              const int coarse_poly_index,
902                              const int subdiv_poly_index,
903                              const int start_loop_index,
904                              const int num_loops)
905 {
906   BLI_assert(coarse_poly_index != ORIGINDEX_NONE);
907   SubdivMeshContext *ctx = foreach_context->user_data;
908   const Mesh *coarse_mesh = ctx->coarse_mesh;
909   const MPoly *coarse_mpoly = coarse_mesh->mpoly;
910   const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
911   Mesh *subdiv_mesh = ctx->subdiv_mesh;
912   MPoly *subdiv_mpoly = subdiv_mesh->mpoly;
913   MPoly *subdiv_poly = &subdiv_mpoly[subdiv_poly_index];
914   subdiv_copy_poly_data(ctx, subdiv_poly, coarse_poly);
915   subdiv_poly->loopstart = start_loop_index;
916   subdiv_poly->totloop = num_loops;
917 }
918
919 /* =============================================================================
920  * Loose elements subdivision process.
921  */
922
923 static void subdiv_mesh_vertex_loose(const SubdivForeachContext *foreach_context,
924                                      void *UNUSED(tls),
925                                      const int coarse_vertex_index,
926                                      const int subdiv_vertex_index)
927 {
928   SubdivMeshContext *ctx = foreach_context->user_data;
929   const Mesh *coarse_mesh = ctx->coarse_mesh;
930   const MVert *coarse_mvert = coarse_mesh->mvert;
931   const MVert *coarse_vertex = &coarse_mvert[coarse_vertex_index];
932   Mesh *subdiv_mesh = ctx->subdiv_mesh;
933   MVert *subdiv_mvert = subdiv_mesh->mvert;
934   MVert *subdiv_vertex = &subdiv_mvert[subdiv_vertex_index];
935   subdiv_vertex_data_copy(ctx, coarse_vertex, subdiv_vertex);
936 }
937
938 /* Get neighbor edges of the given one.
939  * - neighbors[0] is an edge adjacent to edge->v1.
940  * - neighbors[1] is an edge adjacent to edge->v2. */
941 static void find_edge_neighbors(const SubdivMeshContext *ctx,
942                                 const MEdge *edge,
943                                 const MEdge *neighbors[2])
944 {
945   const Mesh *coarse_mesh = ctx->coarse_mesh;
946   const MEdge *coarse_medge = coarse_mesh->medge;
947   neighbors[0] = NULL;
948   neighbors[1] = NULL;
949   int neighbor_counters[2] = {0, 0};
950   for (int edge_index = 0; edge_index < coarse_mesh->totedge; edge_index++) {
951     const MEdge *current_edge = &coarse_medge[edge_index];
952     if (current_edge == edge) {
953       continue;
954     }
955     if (ELEM(edge->v1, current_edge->v1, current_edge->v2)) {
956       neighbors[0] = current_edge;
957       ++neighbor_counters[0];
958     }
959     if (ELEM(edge->v2, current_edge->v1, current_edge->v2)) {
960       neighbors[1] = current_edge;
961       ++neighbor_counters[1];
962     }
963   }
964   /* Vertices which has more than one neighbor are considered infinitely
965    * sharp. This is also how topology factory treats vertices of a surface
966    * which are adjacent to a loose edge. */
967   if (neighbor_counters[0] > 1) {
968     neighbors[0] = NULL;
969   }
970   if (neighbor_counters[1] > 1) {
971     neighbors[1] = NULL;
972   }
973 }
974
975 static void points_for_loose_edges_interpolation_get(SubdivMeshContext *ctx,
976                                                      const MEdge *coarse_edge,
977                                                      const MEdge *neighbors[2],
978                                                      float points_r[4][3])
979 {
980   const Mesh *coarse_mesh = ctx->coarse_mesh;
981   const MVert *coarse_mvert = coarse_mesh->mvert;
982   /* Middle points corresponds to the edge. */
983   copy_v3_v3(points_r[1], coarse_mvert[coarse_edge->v1].co);
984   copy_v3_v3(points_r[2], coarse_mvert[coarse_edge->v2].co);
985   /* Start point, duplicate from edge start if no neighbor. */
986   if (neighbors[0] != NULL) {
987     if (neighbors[0]->v1 == coarse_edge->v1) {
988       copy_v3_v3(points_r[0], coarse_mvert[neighbors[0]->v2].co);
989     }
990     else {
991       copy_v3_v3(points_r[0], coarse_mvert[neighbors[0]->v1].co);
992     }
993   }
994   else {
995     sub_v3_v3v3(points_r[0], points_r[1], points_r[2]);
996     add_v3_v3(points_r[0], points_r[1]);
997   }
998   /* End point, duplicate from edge end if no neighbor. */
999   if (neighbors[1] != NULL) {
1000     if (neighbors[1]->v1 == coarse_edge->v2) {
1001       copy_v3_v3(points_r[3], coarse_mvert[neighbors[1]->v2].co);
1002     }
1003     else {
1004       copy_v3_v3(points_r[3], coarse_mvert[neighbors[1]->v1].co);
1005     }
1006   }
1007   else {
1008     sub_v3_v3v3(points_r[3], points_r[2], points_r[1]);
1009     add_v3_v3(points_r[3], points_r[2]);
1010   }
1011 }
1012
1013 static void subdiv_mesh_vertex_of_loose_edge_interpolate(SubdivMeshContext *ctx,
1014                                                          const MEdge *coarse_edge,
1015                                                          const float u,
1016                                                          const int subdiv_vertex_index)
1017 {
1018   const Mesh *coarse_mesh = ctx->coarse_mesh;
1019   Mesh *subdiv_mesh = ctx->subdiv_mesh;
1020   if (u == 0.0f) {
1021     CustomData_copy_data(
1022         &coarse_mesh->vdata, &subdiv_mesh->vdata, coarse_edge->v1, subdiv_vertex_index, 1);
1023   }
1024   else if (u == 1.0f) {
1025     CustomData_copy_data(
1026         &coarse_mesh->vdata, &subdiv_mesh->vdata, coarse_edge->v2, subdiv_vertex_index, 1);
1027   }
1028   else {
1029     BLI_assert(u > 0.0f);
1030     BLI_assert(u < 1.0f);
1031     const float interpolation_weights[2] = {1.0f - u, u};
1032     const int coarse_vertex_indices[2] = {coarse_edge->v1, coarse_edge->v2};
1033     CustomData_interp(&coarse_mesh->vdata,
1034                       &subdiv_mesh->vdata,
1035                       coarse_vertex_indices,
1036                       interpolation_weights,
1037                       NULL,
1038                       2,
1039                       subdiv_vertex_index);
1040     if (ctx->vert_origindex != NULL) {
1041       ctx->vert_origindex[subdiv_vertex_index] = ORIGINDEX_NONE;
1042     }
1043   }
1044 }
1045
1046 static void subdiv_mesh_vertex_of_loose_edge(const struct SubdivForeachContext *foreach_context,
1047                                              void *UNUSED(tls),
1048                                              const int coarse_edge_index,
1049                                              const float u,
1050                                              const int subdiv_vertex_index)
1051 {
1052   SubdivMeshContext *ctx = foreach_context->user_data;
1053   const Mesh *coarse_mesh = ctx->coarse_mesh;
1054   const MEdge *coarse_edge = &coarse_mesh->medge[coarse_edge_index];
1055   Mesh *subdiv_mesh = ctx->subdiv_mesh;
1056   MVert *subdiv_mvert = subdiv_mesh->mvert;
1057   /* Find neighbors of the current loose edge. */
1058   const MEdge *neighbors[2];
1059   find_edge_neighbors(ctx, coarse_edge, neighbors);
1060   /* Get points for b-spline interpolation. */
1061   float points[4][3];
1062   points_for_loose_edges_interpolation_get(ctx, coarse_edge, neighbors, points);
1063   /* Perform interpolation. */
1064   float weights[4];
1065   key_curve_position_weights(u, weights, KEY_BSPLINE);
1066   /* Interpolate custom data. */
1067   subdiv_mesh_vertex_of_loose_edge_interpolate(ctx, coarse_edge, u, subdiv_vertex_index);
1068   /* Initialize  */
1069   MVert *subdiv_vertex = &subdiv_mvert[subdiv_vertex_index];
1070   interp_v3_v3v3v3v3(subdiv_vertex->co, points[0], points[1], points[2], points[3], weights);
1071   /* Reset flags and such. */
1072   subdiv_vertex->flag = 0;
1073   /* TODO(sergey): This matches old behavior, but we can as well interpolate
1074    * it. Maybe even using vertex varying attributes. */
1075   subdiv_vertex->bweight = 0.0f;
1076   /* Reset normal, initialize it in a similar way as edit mode does for a
1077    * vertices adjacent to a loose edges. */
1078   normal_float_to_short_v3(subdiv_vertex->no, subdiv_vertex->co);
1079 }
1080
1081 /* =============================================================================
1082  * Initialization.
1083  */
1084
1085 static void setup_foreach_callbacks(const SubdivMeshContext *subdiv_context,
1086                                     SubdivForeachContext *foreach_context)
1087 {
1088   memset(foreach_context, 0, sizeof(*foreach_context));
1089   /* General information. */
1090   foreach_context->topology_info = subdiv_mesh_topology_info;
1091   /* Every boundary geometry. Used for dispalcement and normals averaging. */
1092   if (subdiv_context->can_evaluate_normals || subdiv_context->have_displacement) {
1093     foreach_context->vertex_every_corner = subdiv_mesh_vertex_every_corner;
1094     foreach_context->vertex_every_edge = subdiv_mesh_vertex_every_edge;
1095   }
1096   else {
1097     foreach_context->vertex_every_corner = NULL;
1098     foreach_context->vertex_every_edge = NULL;
1099   }
1100   foreach_context->vertex_corner = subdiv_mesh_vertex_corner;
1101   foreach_context->vertex_edge = subdiv_mesh_vertex_edge;
1102   foreach_context->vertex_inner = subdiv_mesh_vertex_inner;
1103   foreach_context->edge = subdiv_mesh_edge;
1104   foreach_context->loop = subdiv_mesh_loop;
1105   foreach_context->poly = subdiv_mesh_poly;
1106   foreach_context->vertex_loose = subdiv_mesh_vertex_loose;
1107   foreach_context->vertex_of_loose_edge = subdiv_mesh_vertex_of_loose_edge;
1108   foreach_context->user_data_tls_free = subdiv_mesh_tls_free;
1109 }
1110
1111 /* =============================================================================
1112  * Public entry point.
1113  */
1114
1115 Mesh *BKE_subdiv_to_mesh(Subdiv *subdiv,
1116                          const SubdivToMeshSettings *settings,
1117                          const Mesh *coarse_mesh)
1118 {
1119   BKE_subdiv_stats_begin(&subdiv->stats, SUBDIV_STATS_SUBDIV_TO_MESH);
1120   /* Make sure evaluator is up to date with possible new topology, and that
1121    * is is refined for the new positions of coarse vertices.
1122    */
1123   if (!BKE_subdiv_eval_update_from_mesh(subdiv, coarse_mesh)) {
1124     /* This could happen in two situations:
1125      * - OpenSubdiv is disabled.
1126      * - Something totally bad happened, and OpenSubdiv rejected our
1127      *   topology.
1128      * In either way, we can't safely continue. */
1129     if (coarse_mesh->totpoly) {
1130       BKE_subdiv_stats_end(&subdiv->stats, SUBDIV_STATS_SUBDIV_TO_MESH);
1131       return NULL;
1132     }
1133   }
1134   /* Initialize subdivion mesh creation context/ */
1135   SubdivMeshContext subdiv_context = {0};
1136   subdiv_context.settings = settings;
1137   subdiv_context.coarse_mesh = coarse_mesh;
1138   subdiv_context.subdiv = subdiv;
1139   subdiv_context.have_displacement = (subdiv->displacement_evaluator != NULL);
1140   subdiv_context.can_evaluate_normals = !subdiv_context.have_displacement;
1141   /* Multi-threaded traversal/evaluation. */
1142   BKE_subdiv_stats_begin(&subdiv->stats, SUBDIV_STATS_SUBDIV_TO_MESH_GEOMETRY);
1143   SubdivForeachContext foreach_context;
1144   setup_foreach_callbacks(&subdiv_context, &foreach_context);
1145   SubdivMeshTLS tls = {0};
1146   foreach_context.user_data = &subdiv_context;
1147   foreach_context.user_data_tls_size = sizeof(SubdivMeshTLS);
1148   foreach_context.user_data_tls = &tls;
1149   BKE_subdiv_foreach_subdiv_geometry(subdiv, &foreach_context, settings, coarse_mesh);
1150   BKE_subdiv_stats_end(&subdiv->stats, SUBDIV_STATS_SUBDIV_TO_MESH_GEOMETRY);
1151   Mesh *result = subdiv_context.subdiv_mesh;
1152   // BKE_mesh_validate(result, true, true);
1153   BKE_subdiv_stats_end(&subdiv->stats, SUBDIV_STATS_SUBDIV_TO_MESH);
1154   if (!subdiv_context.can_evaluate_normals) {
1155     result->runtime.cd_dirty_vert |= CD_MASK_NORMAL;
1156   }
1157   /* Free used memoty. */
1158   subdiv_mesh_context_free(&subdiv_context);
1159   return result;
1160 }