Multires: Simplify reshaping code
[blender.git] / source / blender / blenkernel / intern / multires_reshape.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) 2018 Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Sergey Sharybin.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/multires_reshape.c
27  *  \ingroup bke
28  */
29
30 #include "MEM_guardedalloc.h"
31
32 #include "DNA_mesh_types.h"
33 #include "DNA_meshdata_types.h"
34 #include "DNA_scene_types.h"
35
36 #include "BLI_utildefines.h"
37 #include "BLI_math_vector.h"
38 #include "BLI_task.h"
39
40 #include "BKE_ccg.h"
41 #include "BKE_library.h"
42 #include "BKE_mesh.h"
43 #include "BKE_mesh_runtime.h"
44 #include "BKE_modifier.h"
45 #include "BKE_multires.h"
46 #include "BKE_subdiv.h"
47 #include "BKE_subdiv_ccg.h"
48 #include "BKE_subdiv_eval.h"
49 #include "BKE_subdiv_foreach.h"
50 #include "BKE_subdiv_mesh.h"
51
52 #include "DEG_depsgraph_query.h"
53
54 static void multires_reshape_init_mmd(
55         MultiresModifierData *reshape_mmd,
56         const MultiresModifierData *mmd)
57 {
58         *reshape_mmd = *mmd;
59 }
60
61 static void multires_reshape_init_mmd_top_level(
62         MultiresModifierData *reshape_mmd,
63         const MultiresModifierData *mmd)
64 {
65         *reshape_mmd = *mmd;
66         reshape_mmd->lvl = reshape_mmd->totlvl;
67 }
68
69 /* =============================================================================
70  * General reshape implementation, reused by all particular cases.
71  */
72
73 typedef struct MultiresReshapeContext {
74         Subdiv *subdiv;
75         const Mesh *coarse_mesh;
76         MDisps *mdisps;
77         GridPaintMask *grid_paint_mask;
78         int top_grid_size;
79         int top_level;
80 } MultiresReshapeContext;
81
82 static void multires_reshape_allocate_displacement_grid(
83         MDisps *displacement_grid, const int level)
84 {
85         const int grid_size = BKE_subdiv_grid_size_from_level(level);
86         const int grid_area = grid_size * grid_size;
87         float (*disps)[3] = MEM_calloc_arrayN(
88                 grid_area, 3 * sizeof(float), "multires disps");
89         displacement_grid->disps = disps;
90         displacement_grid->totdisp = grid_area;
91         displacement_grid->level = level;
92 }
93
94 static void multires_reshape_ensure_displacement_grid(
95         MDisps *displacement_grid, const int level)
96 {
97         if (displacement_grid->disps != NULL) {
98                 return;
99         }
100         multires_reshape_allocate_displacement_grid(
101         displacement_grid, level);
102 }
103
104 static void multires_reshape_ensure_displacement_grids(
105         Mesh *mesh,
106         const int grid_level)
107 {
108         const int num_grids = mesh->totloop;
109         MDisps *mdisps = CustomData_get_layer(&mesh->ldata, CD_MDISPS);
110         for (int grid_index = 0; grid_index < num_grids; grid_index++) {
111                 multires_reshape_ensure_displacement_grid(
112                         &mdisps[grid_index], grid_level);
113         }
114 }
115
116 static void multires_reshape_ensure_mask_grids(Mesh *mesh, const int grid_level)
117 {
118         GridPaintMask *grid_paint_masks =
119                 CustomData_get_layer(&mesh->ldata, CD_GRID_PAINT_MASK);
120         if (grid_paint_masks == NULL) {
121                 return;
122         }
123         const int num_grids = mesh->totloop;
124         const int grid_size = BKE_subdiv_grid_size_from_level(grid_level);
125         const int grid_area = grid_size * grid_size;
126         for (int grid_index = 0; grid_index < num_grids; grid_index++) {
127                 GridPaintMask *grid_paint_mask = &grid_paint_masks[grid_index];
128                 if (grid_paint_mask->level == grid_level) {
129                         continue;
130                 }
131                 grid_paint_mask->level = grid_level;
132                 if (grid_paint_mask->data) {
133                         MEM_freeN(grid_paint_mask->data);
134                 }
135                 grid_paint_mask->data = MEM_calloc_arrayN(
136                         grid_area, sizeof(float), "gpm.data");
137         }
138 }
139
140 static void multires_reshape_ensure_grids(Mesh *mesh, const int grid_level)
141 {
142         multires_reshape_ensure_displacement_grids(mesh, grid_level);
143         multires_reshape_ensure_mask_grids(mesh, grid_level);
144 }
145
146 /* Convert normalized coordinate within a grid to a normalized coordinate within
147  * a ptex face. */
148 static void multires_reshape_grid_coord_to_ptex(
149         const MPoly *coarse_poly,
150         const int corner, const float corner_u, const float corner_v,
151         float *r_ptex_face_u, float *r_ptex_face_v)
152 {
153         if (coarse_poly->totloop == 4) {
154                 float grid_u, grid_v;
155                 BKE_subdiv_ptex_face_uv_to_grid_uv(
156                         corner_u, corner_v, &grid_u, &grid_v);
157                 BKE_subdiv_rotate_grid_to_quad(corner, grid_u, grid_v,
158                                                r_ptex_face_u, r_ptex_face_v);
159         }
160         else {
161                 *r_ptex_face_u = corner_u;
162                 *r_ptex_face_v = corner_v;
163         }
164 }
165
166 /* NOTE: The tangent vectors are measured in ptex face normalized coordinates,
167  * which is different from grid tangent. */
168 static void multires_reshape_sample_surface(
169         Subdiv *subdiv,
170         const MPoly *coarse_poly,
171         const int corner, const float corner_u, const float corner_v,
172         const int ptex_face_index,
173         float r_P[3], float r_dPdu[3], float r_dPdv[3])
174 {
175         float ptex_face_u, ptex_face_v;
176         multires_reshape_grid_coord_to_ptex(coarse_poly, corner, corner_u, corner_v,
177                                             &ptex_face_u, &ptex_face_v);
178         BKE_subdiv_eval_limit_point_and_derivatives(
179                 subdiv,
180                 ptex_face_index, ptex_face_u, ptex_face_v,
181                 r_P, r_dPdu, r_dPdv);
182 }
183
184 static void multires_reshape_tangent_matrix_for_corner(
185         const MPoly *coarse_poly,
186         const int coarse_corner,
187         const float dPdu[3], const float dPdv[3],
188         float r_tangent_matrix[3][3])
189 {
190         /* For a quad faces we would need to flip the tangent, since they will use
191          * use different coordinates within displacement grid comparent to ptex
192          * face. */
193         const bool is_quad = (coarse_poly->totloop == 4);
194         const int tangent_corner = is_quad ? coarse_corner : 0;
195         BKE_multires_construct_tangent_matrix(
196                 r_tangent_matrix, dPdu, dPdv, tangent_corner);
197 }
198
199 static void multires_reshape_vertex_from_final_data(
200         MultiresReshapeContext *ctx,
201         const int ptex_face_index,
202         const float corner_u, const float corner_v,
203         const int coarse_poly_index,
204         const int coarse_corner,
205         const float final_P[3], const float final_mask)
206 {
207         Subdiv *subdiv = ctx->subdiv;
208         const int grid_size = ctx->top_grid_size;
209         const Mesh *coarse_mesh = ctx->coarse_mesh;
210         const MPoly *coarse_mpoly = coarse_mesh->mpoly;
211         const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
212         const int loop_index = coarse_poly->loopstart + coarse_corner;
213         /* Evaluate limit surface. */
214         float P[3], dPdu[3], dPdv[3];
215         multires_reshape_sample_surface(
216                 subdiv,
217                 coarse_poly,
218                 coarse_corner, corner_u, corner_v,
219                 ptex_face_index,
220                 P, dPdu, dPdv);
221         /* Construct tangent matrix which matches orientation of the current
222          * displacement grid. */
223         float tangent_matrix[3][3], inv_tangent_matrix[3][3];
224         multires_reshape_tangent_matrix_for_corner(coarse_poly, coarse_corner,
225                                                    dPdu, dPdv,
226                                                    tangent_matrix);
227         invert_m3_m3(inv_tangent_matrix, tangent_matrix);
228         /* Convert object coordinate to a tangent space of displacement grid. */
229         float D[3];
230         sub_v3_v3v3(D, final_P, P);
231         float tangent_D[3];
232         mul_v3_m3v3(tangent_D, inv_tangent_matrix, D);
233         /* Calculate index of element within the grid. */
234         float grid_u, grid_v;
235         BKE_subdiv_ptex_face_uv_to_grid_uv(corner_u, corner_v, &grid_u, &grid_v);
236         const int grid_x = (grid_u * (grid_size - 1) + 0.5f);
237         const int grid_y = (grid_v * (grid_size - 1) + 0.5f);
238         const int index = grid_y * grid_size + grid_x;
239         /* Write tangent displacement. */
240         MDisps *displacement_grid = &ctx->mdisps[loop_index];
241         copy_v3_v3(displacement_grid->disps[index], tangent_D);
242         /* Write mask grid. */
243         if (ctx->grid_paint_mask != NULL) {
244                 GridPaintMask *grid_paint_mask = &ctx->grid_paint_mask[loop_index];
245                 BLI_assert(grid_paint_mask->level == displacement_grid->level);
246                 grid_paint_mask->data[index] = final_mask;
247         }
248 }
249
250 /* =============================================================================
251  * Helpers to propagate displacement to higher levels.
252  */
253
254 typedef struct MultiresPropagateData {
255         /* Number of displacement grids. */
256         int num_grids;
257         /* Resolution level up to which displacement is known. */
258         int reshape_level;
259         /* Resolution up to which propagation is happening, affecting all the
260          * levels in [reshape_level + 1, top_level]. */
261         int top_level;
262         /* Grid sizes at the corresponding levels. */
263         int reshape_grid_size;
264         int top_grid_size;
265         /* Keys to access CCG at different levels. */
266         CCGKey reshape_level_key;
267         CCGKey top_level_key;
268         /* Original grid data, before any updates for reshape.
269          * Contains data at the reshape_level resolution level. */
270         CCGElem **orig_grids_data;
271         /* Custom data layers from a coarse mesh. */
272         MDisps *mdisps;
273         GridPaintMask *grid_paint_mask;
274 } MultiresPropagateData;
275
276 static CCGElem **allocate_grids(CCGKey *key, int num_grids)
277 {
278         CCGElem **grids = MEM_calloc_arrayN(
279                 num_grids, sizeof(CCGElem *), "reshape grids*");
280         for (int grid_index = 0; grid_index < num_grids; grid_index++) {
281                 grids[grid_index] = MEM_calloc_arrayN(
282                         key->elem_size,
283                         key->grid_area,
284                         "reshape orig_grids_data elems");
285         }
286         return grids;
287 }
288
289 static void free_grids(CCGElem **grids, int num_grids)
290 {
291         if (grids == NULL) {
292                 return;
293         }
294         for (int grid_index = 0; grid_index < num_grids; grid_index++) {
295                 MEM_freeN(grids[grid_index]);
296         }
297         MEM_freeN(grids);
298 }
299
300 /* Initialize element sizes and offsets. */
301 static void multires_reshape_init_key_layers(
302         CCGKey *key,
303         const MultiresPropagateData *data)
304 {
305         key->elem_size = 3 * sizeof(float);
306         if (data->grid_paint_mask != NULL) {
307                 key->mask_offset = 3 * sizeof(float);
308                 key->elem_size += sizeof(float);
309                 key->has_mask = true;
310         }
311         else {
312                 key->mask_offset = -1;
313                 key->has_mask = false;
314         }
315         /* We never have normals in original grids. */
316         key->normal_offset = -1;
317         key->has_normals = false;
318 }
319
320 /* Initialize key used to access reshape grids at given level. */
321 static void multires_reshape_init_level_key(
322         CCGKey *key,
323         const MultiresPropagateData *data,
324         const int level)
325 {
326         key->level = level;
327         /* Init layers. */
328         multires_reshape_init_key_layers(key, data);
329         /* By default, only 3 floats for coordinate, */
330         key->grid_size = BKE_subdiv_grid_size_from_level(key->level);
331         key->grid_area = key->grid_size * key->grid_size;
332         key->grid_bytes = key->elem_size * key->grid_area;
333 }
334
335 static void multires_reshape_store_original_grids(
336         MultiresPropagateData *data)
337 {
338         const int num_grids = data->num_grids;
339         /* Original data to be backed up. */
340         const MDisps *mdisps = data->mdisps;
341         const GridPaintMask *grid_paint_mask = data->grid_paint_mask;
342         /* Allocate grids for backup. */
343         CCGKey *orig_key = &data->reshape_level_key;
344         CCGElem **orig_grids_data = allocate_grids(orig_key, num_grids);
345         /* Fill in grids. */
346         const int orig_grid_size = data->reshape_grid_size;
347         const int top_grid_size = data->top_grid_size;
348         const int skip = (top_grid_size - 1) / (orig_grid_size - 1);
349         for (int grid_index = 0; grid_index < num_grids; grid_index++) {
350                 CCGElem *orig_grid = orig_grids_data[grid_index];
351                 for (int y = 0; y < orig_grid_size; y++) {
352                         const int top_y = y * skip;
353                         for (int x = 0; x < orig_grid_size; x++) {
354                                 const int top_x = x * skip;
355                                 const int top_index = top_y * top_grid_size + top_x;
356                                 memcpy(CCG_grid_elem_co(orig_key, orig_grid, x, y),
357                                        mdisps[grid_index].disps[top_index],
358                                        sizeof(float) * 3);
359                                 if (orig_key->has_mask) {
360                                         *CCG_grid_elem_mask(orig_key, orig_grid, x, y) =
361                                                 grid_paint_mask[grid_index].data[top_index];
362                                 }
363                         }
364                 }
365         }
366         /* Store in the context. */
367         data->orig_grids_data = orig_grids_data;
368 }
369
370 static void multires_reshape_propagate_prepare(
371         MultiresPropagateData *data,
372         Mesh *coarse_mesh,
373         const int reshape_level,
374         const int top_level)
375 {
376         BLI_assert(reshape_level <= top_level);
377         memset(data, 0, sizeof(*data));
378         data->num_grids = coarse_mesh->totloop;
379         data->reshape_level = reshape_level;
380         data->top_level = top_level;
381         if (reshape_level == top_level) {
382                 /* Nothing to do, reshape will happen on the whole grid content. */
383                 return;
384         }
385         data->mdisps = CustomData_get_layer(&coarse_mesh->ldata, CD_MDISPS);
386         data->grid_paint_mask =
387                 CustomData_get_layer(&coarse_mesh->ldata, CD_GRID_PAINT_MASK);
388         data->top_grid_size = BKE_subdiv_grid_size_from_level(top_level);
389         data->reshape_grid_size = BKE_subdiv_grid_size_from_level(reshape_level);
390         /* Initialize keys to access CCG at different levels. */
391         multires_reshape_init_level_key(
392                 &data->reshape_level_key, data, data->reshape_level);
393         multires_reshape_init_level_key(
394                 &data->top_level_key, data, data->top_level);
395         /* Make a copy of grids before reshaping, so we can calculate deltas
396          * later on. */
397         multires_reshape_store_original_grids(data);
398 }
399
400 static void multires_reshape_propagate_prepare_from_mmd(
401         MultiresPropagateData *data,
402         struct Depsgraph *depsgraph,
403         Object *object,
404         const MultiresModifierData *mmd,
405         const int top_level,
406         const bool use_render_params)
407 {
408     /* TODO(sergey): Find mode reliable way of getting current level. */
409         Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
410         Mesh *mesh = object->data;
411         const int level = multires_get_level(
412                 scene_eval, object, mmd, use_render_params, true);
413         multires_reshape_propagate_prepare(data, mesh, level, top_level);
414 }
415
416 /* Calculate delta of changed reshape level data layers. Delta goes to a
417  * grids at top level (meaning, the result grids are only partially filled
418  * in). */
419 static void multires_reshape_calculate_delta(
420         MultiresPropagateData *data,
421         CCGElem **delta_grids_data)
422 {
423         const int num_grids = data->num_grids;
424         /* At this point those custom data layers has updated data for the
425          * level we are propagating from. */
426         const MDisps *mdisps = data->mdisps;
427         const GridPaintMask *grid_paint_mask = data->grid_paint_mask;
428         CCGKey *reshape_key = &data->reshape_level_key;
429         CCGKey *delta_level_key = &data->top_level_key;
430         /* Calculate delta. */
431         const int top_grid_size = data->top_grid_size;
432         const int reshape_grid_size = data->reshape_grid_size;
433         const int delta_grid_size = data->top_grid_size;
434         const int skip = (top_grid_size - 1) / (reshape_grid_size - 1);
435         for (int grid_index = 0; grid_index < num_grids; grid_index++) {
436                 /*const*/ CCGElem *orig_grid = data->orig_grids_data[grid_index];
437                 CCGElem *delta_grid = delta_grids_data[grid_index];
438                 for (int y = 0; y < reshape_grid_size; y++) {
439                         const int top_y = y * skip;
440                         for (int x = 0; x < reshape_grid_size; x++) {
441                                 const int top_x = x * skip;
442                                 const int top_index = top_y * delta_grid_size + top_x;
443                                 sub_v3_v3v3(
444                                         CCG_grid_elem_co(
445                                                 delta_level_key, delta_grid, top_x, top_y),
446                                         mdisps[grid_index].disps[top_index],
447                                         CCG_grid_elem_co(reshape_key, orig_grid, x, y));
448                                 if (delta_level_key->has_mask) {
449                                         const float old_mask_value = *CCG_grid_elem_mask(
450                                                 reshape_key, orig_grid, x, y);
451                                         const float new_mask_value =
452                                                 grid_paint_mask[grid_index].data[top_index];
453                                         *CCG_grid_elem_mask(
454                                                 delta_level_key, delta_grid, top_x, top_y) =
455                                                         new_mask_value - old_mask_value;
456                                 }
457                         }
458                 }
459         }
460 }
461
462 /* Makes it so delta is propagated onto all the higher levels, but is also
463  * that this delta is smoothed in a way that it does not cause artifacts on
464  * boundaries. */
465
466 typedef struct MultiresPropagateCornerData {
467         float coord_delta[3];
468         float mask_delta;
469 } MultiresPropagateCornerData;
470
471 BLI_INLINE void multires_reshape_propagate_init_patch_corners(
472         MultiresPropagateData *data,
473         CCGElem *delta_grid,
474         const int patch_x, const int patch_y,
475         MultiresPropagateCornerData r_corners[4])
476 {
477         CCGKey *delta_level_key = &data->top_level_key;
478         const int orig_grid_size = data->reshape_grid_size;
479         const int top_grid_size = data->top_grid_size;
480         const int skip = (top_grid_size - 1) / (orig_grid_size - 1);
481         const int x = patch_x * skip;
482         const int y = patch_y * skip;
483         /* Store coordinate deltas. */
484         copy_v3_v3(r_corners[0].coord_delta,
485                    CCG_grid_elem_co(delta_level_key, delta_grid, x, y));
486         copy_v3_v3(r_corners[1].coord_delta,
487                    CCG_grid_elem_co(delta_level_key, delta_grid, x + skip, y));
488         copy_v3_v3(r_corners[2].coord_delta,
489                    CCG_grid_elem_co(delta_level_key, delta_grid, x, y + skip));
490         copy_v3_v3(r_corners[3].coord_delta,
491                    CCG_grid_elem_co(delta_level_key, delta_grid,
492                                     x + skip, y + skip));
493         if (delta_level_key->has_mask) {
494                 r_corners[0].mask_delta =
495                            *CCG_grid_elem_mask(delta_level_key, delta_grid, x, y);
496                 r_corners[1].mask_delta =
497                            *CCG_grid_elem_mask(delta_level_key, delta_grid,
498                                                x + skip, y);
499                 r_corners[2].mask_delta =
500                            *CCG_grid_elem_mask(delta_level_key, delta_grid,
501                                                x, y + skip);
502                 r_corners[3].mask_delta =
503                            *CCG_grid_elem_mask(delta_level_key, delta_grid,
504                                                x + skip, y + skip);
505         }
506 }
507
508 BLI_INLINE void multires_reshape_propagate_interpolate_coord(
509         float delta[3],
510         const MultiresPropagateCornerData corners[4],
511         const float weights[4])
512 {
513         interp_v3_v3v3v3v3(
514                delta,
515                corners[0].coord_delta, corners[1].coord_delta,
516                corners[2].coord_delta, corners[3].coord_delta,
517                weights);
518 }
519
520 BLI_INLINE float multires_reshape_propagate_interpolate_mask(
521         const MultiresPropagateCornerData corners[4],
522         const float weights[4])
523 {
524         return corners[0].mask_delta * weights[0] +
525                corners[1].mask_delta * weights[1] +
526                corners[2].mask_delta * weights[2] +
527                corners[3].mask_delta * weights[3];
528 }
529
530 BLI_INLINE void multires_reshape_propagate_and_smooth_delta_grid_patch(
531         MultiresPropagateData *data,
532         CCGElem *delta_grid,
533         const int patch_x, const int patch_y)
534 {
535         CCGKey *delta_level_key = &data->top_level_key;
536         const int orig_grid_size = data->reshape_grid_size;
537         const int top_grid_size = data->top_grid_size;
538         const int skip = (top_grid_size - 1) / (orig_grid_size - 1);
539         const float skip_inv = 1.0f / (float)skip;
540         MultiresPropagateCornerData corners[4];
541         multires_reshape_propagate_init_patch_corners(
542                 data, delta_grid, patch_x, patch_y, corners);
543         const int start_x = patch_x * skip;
544         const int start_y = patch_y * skip;
545         for (int y = 0; y <= skip; y++) {
546                 const float v = (float)y * skip_inv;
547                 const int final_y = start_y + y;
548                 for (int x = 0; x <= skip; x++) {
549                         const float u = (float)x * skip_inv;
550                         const int final_x = start_x + x;
551                         const float linear_weights[4] = {(1.0f - u) * (1.0f - v),
552                                                          u * (1.0f - v),
553                                                          (1.0f - u) * v,
554                                                          u * v};
555                         multires_reshape_propagate_interpolate_coord(
556                                 CCG_grid_elem_co(delta_level_key, delta_grid,
557                                                  final_x, final_y),
558                                 corners,
559                                 linear_weights);
560                         if (delta_level_key->has_mask) {
561                                 float *mask = CCG_grid_elem_mask(delta_level_key, delta_grid,
562                                                                  final_x, final_y);
563                                 *mask = multires_reshape_propagate_interpolate_mask(
564                                         corners, linear_weights);
565                         }
566                 }
567         }
568 }
569
570 BLI_INLINE void multires_reshape_propagate_and_smooth_delta_grid(
571         MultiresPropagateData *data,
572         CCGElem *delta_grid)
573 {
574         const int orig_grid_size = data->reshape_grid_size;
575         for (int patch_y = 0; patch_y < orig_grid_size - 1; patch_y++) {
576                 for (int patch_x = 0; patch_x < orig_grid_size - 1; patch_x++) {
577                         multires_reshape_propagate_and_smooth_delta_grid_patch(
578                                 data, delta_grid, patch_x, patch_y);
579                 }
580         }
581 }
582
583 /* Entry point to propagate+smooth. */
584 static void multires_reshape_propagate_and_smooth_delta(
585         MultiresPropagateData *data,
586         CCGElem **delta_grids_data)
587 {
588         const int num_grids = data->num_grids;
589         for (int grid_index = 0; grid_index < num_grids; grid_index++) {
590                 CCGElem *delta_grid = delta_grids_data[grid_index];
591                 multires_reshape_propagate_and_smooth_delta_grid(data, delta_grid);
592         }
593 }
594
595 /* Apply smoothed deltas on the actual data layers. */
596 static void multires_reshape_propagate_apply_delta(
597         MultiresPropagateData *data,
598         CCGElem **delta_grids_data)
599 {
600         const int num_grids = data->num_grids;
601         /* At this point those custom data layers has updated data for the
602          * level we are propagating from. */
603         MDisps *mdisps = data->mdisps;
604         GridPaintMask *grid_paint_mask = data->grid_paint_mask;
605         CCGKey *orig_key = &data->reshape_level_key;
606         CCGKey *delta_level_key = &data->top_level_key;
607         CCGElem **orig_grids_data = data->orig_grids_data;
608         const int orig_grid_size = data->reshape_grid_size;
609         const int top_grid_size = data->top_grid_size;
610         const int skip = (top_grid_size - 1) / (orig_grid_size - 1);
611         /* Restore grid values at the reshape level. Those values are to be changed
612          * to the accommodate for the smooth delta. */
613         for (int grid_index = 0; grid_index < num_grids; grid_index++) {
614                 CCGElem *orig_grid = orig_grids_data[grid_index];
615                 for (int y = 0; y < orig_grid_size; y++) {
616                         const int top_y = y * skip;
617                         for (int x = 0; x < orig_grid_size; x++) {
618                                 const int top_x = x * skip;
619                                 const int top_index = top_y * top_grid_size + top_x;
620                                 copy_v3_v3(mdisps[grid_index].disps[top_index],
621                                        CCG_grid_elem_co(orig_key, orig_grid, x, y));
622                                 if (grid_paint_mask != NULL) {
623                                         grid_paint_mask[grid_index].data[top_index] =
624                                                 *CCG_grid_elem_mask(orig_key, orig_grid, x, y);
625                                 }
626                         }
627                 }
628         }
629         /* Add smoothed delta to all the levels. */
630         for (int grid_index = 0; grid_index < num_grids; grid_index++) {
631                 CCGElem *delta_grid = delta_grids_data[grid_index];
632                 for (int y = 0; y < top_grid_size; y++) {
633                         for (int x = 0; x < top_grid_size; x++) {
634                                 const int top_index = y * top_grid_size + x;
635                                 add_v3_v3(mdisps[grid_index].disps[top_index],
636                                        CCG_grid_elem_co(delta_level_key, delta_grid, x, y));
637                                 if (delta_level_key->has_mask) {
638                                         grid_paint_mask[grid_index].data[top_index] +=
639                                                *CCG_grid_elem_mask(
640                                                        delta_level_key, delta_grid, x, y);
641                                 }
642                         }
643                 }
644         }
645 }
646
647 static void multires_reshape_propagate(MultiresPropagateData *data)
648 {
649         if (data->reshape_level == data->top_level) {
650                 return;
651         }
652         const int num_grids = data->num_grids;
653         /* Calculate delta made at the reshape level. */
654         CCGKey *delta_level_key = &data->top_level_key;
655         CCGElem **delta_grids_data = allocate_grids(delta_level_key, num_grids);
656         multires_reshape_calculate_delta(data, delta_grids_data);
657         /* Propagate deltas to the higher levels. */
658         multires_reshape_propagate_and_smooth_delta(data, delta_grids_data);
659         /* Finally, apply smoothed deltas. */
660         multires_reshape_propagate_apply_delta(data, delta_grids_data);
661         /* Cleanup. */
662         free_grids(delta_grids_data, num_grids);
663 }
664
665 static void multires_reshape_propagate_free(MultiresPropagateData *data)
666 {
667         free_grids(data->orig_grids_data, data->num_grids);
668 }
669
670 /* =============================================================================
671  * Reshape from deformed vertex coordinates.
672  */
673
674 typedef struct MultiresReshapeFromDeformedVertsContext {
675         MultiresReshapeContext reshape_ctx;
676         const float (*deformed_verts)[3];
677         int num_deformed_verts;
678 } MultiresReshapeFromDeformedVertsContext;
679
680 static bool multires_reshape_topology_info(
681         const SubdivForeachContext *foreach_context,
682         const int num_vertices,
683         const int UNUSED(num_edges),
684         const int UNUSED(num_loops),
685         const int UNUSED(num_polygons))
686 {
687         MultiresReshapeFromDeformedVertsContext *ctx = foreach_context->user_data;
688         if (num_vertices != ctx->num_deformed_verts) {
689                 return false;
690         }
691         return true;
692 }
693
694 static void multires_reshape_vertex(
695         MultiresReshapeFromDeformedVertsContext *ctx,
696         const int ptex_face_index,
697         const float u, const float v,
698         const int coarse_poly_index,
699         const int coarse_corner,
700         const int subdiv_vertex_index)
701 {
702         const float *final_P = ctx->deformed_verts[subdiv_vertex_index];
703         const Mesh *coarse_mesh = ctx->reshape_ctx.coarse_mesh;
704         const MPoly *coarse_mpoly = coarse_mesh->mpoly;
705         const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
706         float corner_u, corner_v;
707         int actual_coarse_corner;
708         if (coarse_poly->totloop == 4) {
709                 actual_coarse_corner = BKE_subdiv_rotate_quad_to_corner(
710                         u, v, &corner_u, &corner_v);
711         }
712         else {
713                 actual_coarse_corner = coarse_corner;
714                 corner_u = u;
715                 corner_v = v;
716         }
717         multires_reshape_vertex_from_final_data(
718                 &ctx->reshape_ctx,
719                 ptex_face_index, corner_u, corner_v,
720                 coarse_poly_index,
721                 actual_coarse_corner,
722                 final_P, 0.0f);
723 }
724
725 static void multires_reshape_vertex_inner(
726         const SubdivForeachContext *foreach_context,
727         void *UNUSED(tls_v),
728         const int ptex_face_index,
729         const float u, const float v,
730         const int coarse_poly_index,
731         const int coarse_corner,
732         const int subdiv_vertex_index)
733 {
734         MultiresReshapeFromDeformedVertsContext *ctx = foreach_context->user_data;
735         multires_reshape_vertex(
736                 ctx,
737                 ptex_face_index, u, v,
738                 coarse_poly_index,
739                 coarse_corner,
740                 subdiv_vertex_index);
741 }
742
743 static void multires_reshape_vertex_every_corner(
744         const struct SubdivForeachContext *foreach_context,
745         void *UNUSED(tls_v),
746         const int ptex_face_index,
747         const float u, const float v,
748         const int UNUSED(coarse_vertex_index),
749         const int coarse_poly_index,
750         const int coarse_corner,
751         const int subdiv_vertex_index)
752 {
753         MultiresReshapeFromDeformedVertsContext *ctx = foreach_context->user_data;
754         multires_reshape_vertex(
755                 ctx,
756                 ptex_face_index, u, v,
757                 coarse_poly_index,
758                 coarse_corner,
759                 subdiv_vertex_index);
760 }
761
762 static void multires_reshape_vertex_every_edge(
763         const struct SubdivForeachContext *foreach_context,
764         void *UNUSED(tls_v),
765         const int ptex_face_index,
766         const float u, const float v,
767         const int UNUSED(coarse_edge_index),
768         const int coarse_poly_index,
769         const int coarse_corner,
770         const int subdiv_vertex_index)
771 {
772         MultiresReshapeFromDeformedVertsContext *ctx = foreach_context->user_data;
773         multires_reshape_vertex(
774                 ctx,
775                 ptex_face_index, u, v,
776                 coarse_poly_index,
777                 coarse_corner,
778                 subdiv_vertex_index);
779 }
780
781 static Subdiv *multires_create_subdiv_for_reshape(
782         struct Depsgraph *depsgraph,
783         /*const*/ Object *object,
784         const MultiresModifierData *mmd)
785 {
786         Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
787         Object *object_eval = DEG_get_evaluated_object(depsgraph, object);
788         Mesh *deformed_mesh = mesh_get_eval_deform(
789                 depsgraph, scene_eval, object_eval, CD_MASK_BAREMESH);
790         SubdivSettings subdiv_settings;
791         BKE_multires_subdiv_settings_init(&subdiv_settings, mmd);
792         Subdiv *subdiv = BKE_subdiv_new_from_mesh(&subdiv_settings, deformed_mesh);
793         if (!BKE_subdiv_eval_update_from_mesh(subdiv, deformed_mesh)) {
794                 BKE_subdiv_free(subdiv);
795                 return NULL;
796         }
797         return subdiv;
798 }
799
800 static bool multires_reshape_from_vertcos(
801         struct Depsgraph *depsgraph,
802         Object *object,
803         const MultiresModifierData *mmd,
804         const float (*deformed_verts)[3],
805         const int num_deformed_verts,
806         const bool use_render_params)
807 {
808         Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
809         Mesh *coarse_mesh = object->data;
810         MDisps *mdisps = CustomData_get_layer(&coarse_mesh->ldata, CD_MDISPS);
811         /* Pick maximum between multires level and dispalcement level.
812          * This is because mesh can be used by objects with multires at different
813          * levels.
814          *
815          * TODO(sergey): At this point it should be possible to always use
816          * mdisps->level. */
817         const int top_level = max_ii(mmd->totlvl, mdisps->level);
818         /* Make sure displacement grids are ready. */
819         multires_reshape_ensure_grids(coarse_mesh, top_level);
820         /* Construct context. */
821         MultiresReshapeFromDeformedVertsContext reshape_deformed_verts_ctx = {
822                 .reshape_ctx = {
823                         .coarse_mesh = coarse_mesh,
824                         .mdisps = mdisps,
825                         .grid_paint_mask = NULL,
826                         .top_grid_size = BKE_subdiv_grid_size_from_level(top_level),
827                         .top_level = top_level,
828                 },
829                 .deformed_verts = deformed_verts,
830                 .num_deformed_verts = num_deformed_verts,
831         };
832         SubdivForeachContext foreach_context = {
833                 .topology_info = multires_reshape_topology_info,
834                 .vertex_inner = multires_reshape_vertex_inner,
835                 .vertex_every_edge = multires_reshape_vertex_every_edge,
836                 .vertex_every_corner = multires_reshape_vertex_every_corner,
837                 .user_data = &reshape_deformed_verts_ctx,
838         };
839         /* Initialize subdivision surface. */
840         Subdiv *subdiv = multires_create_subdiv_for_reshape(depsgraph, object, mmd);
841         if (subdiv == NULL) {
842                 return false;
843         }
844         reshape_deformed_verts_ctx.reshape_ctx.subdiv = subdiv;
845         /* Initialize mesh rasterization settings. */
846         SubdivToMeshSettings mesh_settings;
847         BKE_multires_subdiv_mesh_settings_init(
848         &mesh_settings, scene_eval, object, mmd, use_render_params, true);
849         /* Initialize propagation to higher levels. */
850         MultiresPropagateData propagate_data;
851         multires_reshape_propagate_prepare_from_mmd(
852         &propagate_data, depsgraph, object, mmd, top_level, use_render_params);
853         /* Run all the callbacks. */
854         BKE_subdiv_foreach_subdiv_geometry(
855                 subdiv,
856                 &foreach_context,
857                 &mesh_settings,
858                 coarse_mesh);
859         BKE_subdiv_free(subdiv);
860         /* Update higher levels if needed. */
861         multires_reshape_propagate(&propagate_data);
862         multires_reshape_propagate_free(&propagate_data);
863         return true;
864 }
865
866 /* =============================================================================
867  * Reshape from object.
868  */
869
870 /* Returns truth on success, false otherwise.
871  *
872  * This function might fail in cases like source and destination not having
873  * matched amount of vertices. */
874 bool multiresModifier_reshapeFromObject(
875         struct Depsgraph *depsgraph,
876         MultiresModifierData *mmd,
877         Object *dst,
878         Object *src)
879 {
880         /* Would be cool to support this eventually, but it is very tricky to match
881          * vertices order even for meshes, when mixing meshes and other objects it's
882          * even more tricky. */
883         if (src->type != OB_MESH) {
884                 return false;
885         }
886         MultiresModifierData reshape_mmd;
887         multires_reshape_init_mmd(&reshape_mmd, mmd);
888         /* Get evaluated vertices locations to reshape to. */
889         Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
890         Object *src_eval = DEG_get_evaluated_object(depsgraph, src);
891         Mesh *src_mesh_eval = mesh_get_eval_final(
892                 depsgraph, scene_eval, src_eval, CD_MASK_BAREMESH);
893         int num_deformed_verts;
894         float (*deformed_verts)[3] = BKE_mesh_vertexCos_get(
895                 src_mesh_eval, &num_deformed_verts);
896         bool result = multires_reshape_from_vertcos(
897                 depsgraph,
898                 dst,
899                 &reshape_mmd,
900                 deformed_verts,
901                 num_deformed_verts,
902                 false);
903         MEM_freeN(deformed_verts);
904         return result;
905 }
906
907 /* =============================================================================
908  * Reshape from modifier.
909  */
910
911 bool multiresModifier_reshapeFromDeformModifier(
912         struct Depsgraph *depsgraph,
913         MultiresModifierData *mmd,
914         Object *object,
915         ModifierData *md)
916 {
917         MultiresModifierData highest_mmd;
918         /* It is possible that the current subdivision level of multires is lower
919          * that it's maximum possible one (i.e., viewport is set to a lower level
920          * for the performance purposes). But even then, we want all the multires
921          * levels to be reshaped. Most accurate way to do so is to ignore all
922          * simplifications and calculate deformation modifier for the highest
923          * possible multires level.
924          * Alternative would be propagate displacement from current level to a
925          * higher ones, but that is likely to cause artifacts. */
926         multires_reshape_init_mmd_top_level(&highest_mmd, mmd);
927         Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
928         /* Perform sanity checks and early output. */
929         if (multires_get_level(
930                     scene_eval, object, &highest_mmd, false, true) == 0)
931         {
932                 return false;
933         }
934         /* Create mesh for the multires, ignoring any further modifiers (leading
935          * deformation modifiers will be applied though). */
936         Mesh *multires_mesh = BKE_multires_create_mesh(
937                 depsgraph, scene_eval, &highest_mmd, object);
938         int num_deformed_verts;
939         float (*deformed_verts)[3] = BKE_mesh_vertexCos_get(
940                 multires_mesh, &num_deformed_verts);
941         /* Apply deformation modifier on the multires, */
942         const ModifierEvalContext modifier_ctx = {
943                 .depsgraph = depsgraph,
944                 .object = object,
945                 .flag = MOD_APPLY_USECACHE | MOD_APPLY_IGNORE_SIMPLIFY,
946         };
947         modwrap_deformVerts(
948                 md, &modifier_ctx, multires_mesh, deformed_verts,
949                 multires_mesh->totvert);
950         BKE_id_free(NULL, multires_mesh);
951         /* Reshaping */
952         bool result = multires_reshape_from_vertcos(
953                 depsgraph,
954                 object,
955                 &highest_mmd,
956                 deformed_verts,
957                 num_deformed_verts,
958                 false);
959         /* Cleanup */
960         MEM_freeN(deformed_verts);
961         return result;
962 }
963
964 /* =============================================================================
965  * Reshape from grids.
966  */
967
968 typedef struct ReshapeFromCCGTaskData {
969         MultiresReshapeContext reshape_ctx;
970         int *face_ptex_offset;
971         const CCGKey *key;
972         /*const*/ CCGElem **grids;
973 } ReshapeFromCCGTaskData;
974
975 static void reshape_from_ccg_task(
976         void *__restrict userdata,
977         const int coarse_poly_index,
978         const ParallelRangeTLS *__restrict UNUSED(tls))
979 {
980         ReshapeFromCCGTaskData *data = userdata;
981         const CCGKey *key = data->key;
982         /*const*/ CCGElem **grids = data->grids;
983         const Mesh *coarse_mesh = data->reshape_ctx.coarse_mesh;
984         const MPoly *coarse_mpoly = coarse_mesh->mpoly;
985         const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
986         const int key_grid_size = key->grid_size;
987         const int key_grid_size_1 = key_grid_size - 1;
988         const int resolution = key_grid_size;
989         const float resolution_1_inv = 1.0f / (float)(resolution - 1);
990         const int start_ptex_face_index = data->face_ptex_offset[coarse_poly_index];
991         const bool is_quad = (coarse_poly->totloop == 4);
992         for (int corner = 0; corner < coarse_poly->totloop; corner++) {
993                 for (int y = 0; y < resolution; y++) {
994                         const float corner_v = y * resolution_1_inv;
995                         for (int x = 0; x < resolution; x++) {
996                                 const float corner_u = x * resolution_1_inv;
997                                 /* Quad faces consists of a single ptex face. */
998                                 const int ptex_face_index =
999                                         is_quad ? start_ptex_face_index
1000                                                 : start_ptex_face_index + corner;
1001                                 float grid_u, grid_v;
1002                                 BKE_subdiv_ptex_face_uv_to_grid_uv(
1003                                         corner_u, corner_v, &grid_u, &grid_v);
1004                                 /*const*/ CCGElem *grid =
1005                                         grids[coarse_poly->loopstart + corner];
1006                                 /*const*/ CCGElem *grid_element = CCG_grid_elem(
1007                                         key,
1008                                         grid,
1009                                         key_grid_size_1 * grid_u,
1010                                         key_grid_size_1 * grid_v);
1011                                 const float *final_P = CCG_elem_co(key, grid_element);
1012                                 float final_mask = 0.0f;
1013                                 if (key->has_mask) {
1014                                         final_mask = *CCG_elem_mask(key, grid_element);
1015                                 }
1016                                 multires_reshape_vertex_from_final_data(
1017                                         &data->reshape_ctx,
1018                                         ptex_face_index,
1019                                         corner_u, corner_v,
1020                                         coarse_poly_index,
1021                                         corner,
1022                                         final_P, final_mask);
1023                         }
1024                 }
1025         }
1026 }
1027
1028 bool multiresModifier_reshapeFromCCG(
1029         const int tot_level,
1030         Mesh *coarse_mesh,
1031         SubdivCCG *subdiv_ccg)
1032 {
1033         CCGKey key;
1034         BKE_subdiv_ccg_key_top_level(&key, subdiv_ccg);
1035         /* Sanity checks. */
1036         if (coarse_mesh->totloop != subdiv_ccg->num_grids) {
1037                 /* Grids are supposed to eb created for each face-cornder (aka loop). */
1038                 return false;
1039         }
1040         MDisps *mdisps = CustomData_get_layer(&coarse_mesh->ldata, CD_MDISPS);
1041         if (mdisps == NULL) {
1042                 /* Multires displacement has been removed before current changes were
1043                  * applies to all the levels. */
1044                 return false;
1045         }
1046         GridPaintMask *grid_paint_mask =
1047                 CustomData_get_layer(&coarse_mesh->ldata, CD_GRID_PAINT_MASK);
1048         Subdiv *subdiv = subdiv_ccg->subdiv;
1049         /* Pick maximum between multires level and dispalcement level.
1050          * This is because mesh can be used by objects with multires at different
1051          * levels.
1052          *
1053          * TODO(sergey): At this point it should be possible to always use
1054          * mdisps->level. */
1055         const int top_level = max_ii(tot_level, mdisps->level);
1056         /* Make sure displacement grids are ready. */
1057         multires_reshape_ensure_grids(coarse_mesh, top_level);
1058         /* Construct context. */
1059         ReshapeFromCCGTaskData data = {
1060                 .reshape_ctx = {
1061                         .subdiv = subdiv,
1062                         .coarse_mesh = coarse_mesh,
1063                         .mdisps  = mdisps,
1064                         .grid_paint_mask = grid_paint_mask,
1065                         .top_grid_size = BKE_subdiv_grid_size_from_level(top_level),
1066                         .top_level = top_level,
1067                 },
1068                 .face_ptex_offset = BKE_subdiv_face_ptex_offset_get(subdiv),
1069                 .key = &key,
1070                 .grids = subdiv_ccg->grids,
1071         };
1072         /* Initialize propagation to higher levels. */
1073         MultiresPropagateData propagate_data;
1074         multires_reshape_propagate_prepare(
1075                 &propagate_data, coarse_mesh, key.level, top_level);
1076         /* Threaded grids iteration. */
1077         ParallelRangeSettings parallel_range_settings;
1078         BLI_parallel_range_settings_defaults(&parallel_range_settings);
1079         BLI_task_parallel_range(0, coarse_mesh->totpoly,
1080                                 &data,
1081                                 reshape_from_ccg_task,
1082                                 &parallel_range_settings);
1083         /* Update higher levels if needed. */
1084         multires_reshape_propagate(&propagate_data);
1085         multires_reshape_propagate_free(&propagate_data);
1086         return true;
1087 }