doxygen: add newline after \file
[blender.git] / source / blender / blenkernel / intern / dynamicpaint.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
17 /** \file
18  * \ingroup bke
19  */
20
21 #include "MEM_guardedalloc.h"
22
23 #include <math.h>
24 #include <stdio.h>
25
26 #include "BLI_blenlib.h"
27 #include "BLI_math.h"
28 #include "BLI_kdtree.h"
29 #include "BLI_string_utils.h"
30 #include "BLI_task.h"
31 #include "BLI_threads.h"
32 #include "BLI_utildefines.h"
33
34 #include "BLT_translation.h"
35
36 #include "DNA_anim_types.h"
37 #include "DNA_armature_types.h"
38 #include "DNA_collection_types.h"
39 #include "DNA_constraint_types.h"
40 #include "DNA_dynamicpaint_types.h"
41 #include "DNA_material_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_modifier_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_texture_types.h"
48
49 #include "BKE_animsys.h"
50 #include "BKE_armature.h"
51 #include "BKE_bvhutils.h"   /* bvh tree */
52 #include "BKE_collection.h"
53 #include "BKE_collision.h"
54 #include "BKE_colorband.h"
55 #include "BKE_constraint.h"
56 #include "BKE_customdata.h"
57 #include "BKE_deform.h"
58 #include "BKE_dynamicpaint.h"
59 #include "BKE_effect.h"
60 #include "BKE_image.h"
61 #include "BKE_library.h"
62 #include "BKE_main.h"
63 #include "BKE_material.h"
64 #include "BKE_mesh.h"
65 #include "BKE_mesh_mapping.h"
66 #include "BKE_mesh_runtime.h"
67 #include "BKE_modifier.h"
68 #include "BKE_object.h"
69 #include "BKE_particle.h"
70 #include "BKE_pointcache.h"
71 #include "BKE_scene.h"
72
73 #include "DEG_depsgraph.h"
74 #include "DEG_depsgraph_query.h"
75
76 /* for image output     */
77 #include "IMB_imbuf_types.h"
78 #include "IMB_imbuf.h"
79
80 /* to read material/texture color */
81 #include "RE_render_ext.h"
82 #include "RE_shader_ext.h"
83
84 #include "atomic_ops.h"
85
86 #include "CLG_log.h"
87
88 /* could enable at some point but for now there are far too many conversions */
89 #ifdef __GNUC__
90 //#  pragma GCC diagnostic ignored "-Wdouble-promotion"
91 #endif
92
93 static CLG_LogRef LOG = {"bke.dynamicpaint"};
94
95 /* precalculated gaussian factors for 5x super sampling */
96 static const float gaussianFactors[5] = {
97     0.996849f,
98     0.596145f,
99     0.596145f,
100     0.596145f,
101     0.524141f};
102 static const float gaussianTotal = 3.309425f;
103
104 /* UV Image neighboring pixel table x and y list */
105 static int neighX[8] = {1, 1, 0, -1, -1, -1, 0, 1};
106 static int neighY[8] = {0, 1, 1, 1, 0, -1, -1, -1};
107
108 /* Neighbor x/y list that prioritizes grid directions over diagonals */
109 static int neighStraightX[8] = {1, 0, -1,  0, 1, -1, -1,  1};
110 static int neighStraightY[8] = {0, 1,  0, -1, 1,  1, -1, -1};
111
112 /* subframe_updateObject() flags */
113 #define SUBFRAME_RECURSION 5
114 /* surface_getBrushFlags() return vals */
115 #define BRUSH_USES_VELOCITY (1 << 0)
116 /* brush mesh raycast status */
117 #define HIT_VOLUME 1
118 #define HIT_PROXIMITY 2
119 /* dynamicPaint_findNeighbourPixel() return codes */
120 #define NOT_FOUND -1
121 #define ON_MESH_EDGE -2
122 #define OUT_OF_TEXTURE -3
123 /* paint effect default movement per frame in global units */
124 #define EFF_MOVEMENT_PER_FRAME 0.05f
125 /* initial wave time factor */
126 #define WAVE_TIME_FAC (1.0f / 24.f)
127 #define CANVAS_REL_SIZE 5.0f
128 /* drying limits */
129 #define MIN_WETNESS 0.001f
130 #define MAX_WETNESS 5.0f
131
132
133 /* dissolve inline function */
134 BLI_INLINE void value_dissolve(float *r_value, const float time, const float scale, const bool is_log)
135 {
136         *r_value = (is_log) ?
137                       (*r_value) * (powf(MIN_WETNESS, 1.0f / (1.2f * time / scale))) :
138                       (*r_value) - 1.0f / time * scale;
139 }
140
141
142 /***************************** Internal Structs ***************************/
143
144 typedef struct Bounds2D {
145         float min[2], max[2];
146 } Bounds2D;
147
148 typedef struct Bounds3D {
149         float min[3], max[3];
150         bool valid;
151 } Bounds3D;
152
153 typedef struct VolumeGrid {
154         int dim[3];
155         Bounds3D grid_bounds;  /* whole grid bounds */
156
157         Bounds3D *bounds;  /* (x*y*z) precalculated grid cell bounds */
158         int *s_pos;  /* (x*y*z) t_index begin id */
159         int *s_num;  /* (x*y*z) number of t_index points */
160         int *t_index;  /* actual surface point index, access: (s_pos + s_num) */
161
162         int *temp_t_index;
163 } VolumeGrid;
164
165 typedef struct Vec3f {
166         float v[3];
167 } Vec3f;
168
169 typedef struct BakeAdjPoint {
170         float dir[3];   /* vector pointing towards this neighbor */
171         float dist;     /* distance to */
172 } BakeAdjPoint;
173
174 /* Surface data used while processing a frame */
175 typedef struct PaintBakeNormal {
176         float invNorm[3];  /* current pixel world-space inverted normal */
177         float normal_scale;  /* normal directional scale for displace mapping */
178 } PaintBakeNormal;
179
180 /* Temp surface data used to process a frame */
181 typedef struct PaintBakeData {
182         /* point space data */
183         PaintBakeNormal *bNormal;
184         int *s_pos;  /* index to start reading point sample realCoord */
185         int *s_num;  /* num of realCoord samples */
186         Vec3f *realCoord;  /* current pixel center world-space coordinates for each sample ordered as (s_pos + s_num) */
187         Bounds3D mesh_bounds;
188         float dim[3];
189
190         /* adjacency info */
191         BakeAdjPoint *bNeighs;  /* current global neighbor distances and directions, if required */
192         double average_dist;
193         /* space partitioning */
194         VolumeGrid *grid;       /* space partitioning grid to optimize brush checks */
195
196         /* velocity and movement */
197         Vec3f *velocity;        /* speed vector in global space movement per frame, if required */
198         Vec3f *prev_velocity;
199         float *brush_velocity;  /* special temp data for post-p velocity based brushes like smudge
200                                  * 3 float dir vec + 1 float str */
201         MVert *prev_verts;      /* copy of previous frame vertices. used to observe surface movement */
202         float prev_obmat[4][4]; /* previous frame object matrix */
203         int clear;              /* flag to check if surface was cleared/reset -> have to redo velocity etc. */
204 } PaintBakeData;
205
206 /* UV Image sequence format point */
207 typedef struct PaintUVPoint {
208         /* Pixel / mesh data */
209         unsigned int tri_index, pixel_index;    /* tri index on domain derived mesh */
210         unsigned int v1, v2, v3;                /* vertex indexes */
211
212         unsigned int neighbour_pixel;   /* If this pixel isn't uv mapped to any face, but it's neighboring pixel is */
213 } PaintUVPoint;
214
215 typedef struct ImgSeqFormatData {
216         PaintUVPoint *uv_p;
217         Vec3f *barycentricWeights;      /* b-weights for all pixel samples */
218 } ImgSeqFormatData;
219
220 /* adjacency data flags */
221 #define ADJ_ON_MESH_EDGE (1 << 0)
222 #define ADJ_BORDER_PIXEL (1 << 1)
223
224 typedef struct PaintAdjData {
225         int *n_target;  /* array of neighboring point indexes, for single sample use (n_index + neigh_num) */
226         int *n_index;   /* index to start reading n_target for each point */
227         int *n_num;     /* num of neighs for each point */
228         int *flags;     /* vertex adjacency flags */
229         int total_targets; /* size of n_target */
230         int *border;    /* indices of border pixels (only for texture paint) */
231         int total_border; /* size of border */
232 } PaintAdjData;
233
234 /***************************** General Utils ******************************/
235
236 /* Set canvas error string to display at the bake report */
237 static int setError(DynamicPaintCanvasSettings *canvas, const char *string)
238 {
239         /* Add error to canvas ui info label */
240         BLI_strncpy(canvas->error, string, sizeof(canvas->error));
241         CLOG_STR_ERROR(&LOG, string);
242         return 0;
243 }
244
245 /* Get number of surface points for cached types */
246 static int dynamicPaint_surfaceNumOfPoints(DynamicPaintSurface *surface)
247 {
248         if (surface->format == MOD_DPAINT_SURFACE_F_PTEX) {
249                 return 0; /* not supported atm */
250         }
251         else if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
252                 return (surface->canvas->mesh) ? surface->canvas->mesh->totvert : 0;
253         }
254
255         return 0;
256 }
257
258 /* checks whether surface's format/type has realtime preview */
259 bool dynamicPaint_surfaceHasColorPreview(DynamicPaintSurface *surface)
260 {
261         if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
262                 return false;
263         }
264         else if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
265                 return !ELEM(surface->type, MOD_DPAINT_SURFACE_T_DISPLACE, MOD_DPAINT_SURFACE_T_WAVE);
266         }
267
268         return true;
269 }
270
271 /* get currently active surface (in user interface) */
272 DynamicPaintSurface *get_activeSurface(DynamicPaintCanvasSettings *canvas)
273 {
274         return BLI_findlink(&canvas->surfaces, canvas->active_sur);
275 }
276
277 /* set preview to first previewable surface */
278 void dynamicPaint_resetPreview(DynamicPaintCanvasSettings *canvas)
279 {
280         DynamicPaintSurface *surface = canvas->surfaces.first;
281         bool done = false;
282
283         for (; surface; surface = surface->next) {
284                 if (!done && dynamicPaint_surfaceHasColorPreview(surface)) {
285                         surface->flags |= MOD_DPAINT_PREVIEW;
286                         done = true;
287                 }
288                 else {
289                         surface->flags &= ~MOD_DPAINT_PREVIEW;
290                 }
291         }
292 }
293
294 /* set preview to defined surface */
295 static void dynamicPaint_setPreview(DynamicPaintSurface *t_surface)
296 {
297         DynamicPaintSurface *surface = t_surface->canvas->surfaces.first;
298         for (; surface; surface = surface->next) {
299                 if (surface == t_surface)
300                         surface->flags |= MOD_DPAINT_PREVIEW;
301                 else
302                         surface->flags &= ~MOD_DPAINT_PREVIEW;
303         }
304 }
305
306 bool dynamicPaint_outputLayerExists(struct DynamicPaintSurface *surface, Object *ob, int output)
307 {
308         const char *name;
309
310         if (output == 0)
311                 name = surface->output_name;
312         else if (output == 1)
313                 name = surface->output_name2;
314         else
315                 return false;
316
317         if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
318                 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
319                         Mesh *me = ob->data;
320                         return (CustomData_get_named_layer_index(&me->ldata, CD_MLOOPCOL, name) != -1);
321                 }
322                 else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) {
323                         return (defgroup_name_index(ob, name) != -1);
324                 }
325         }
326
327         return false;
328 }
329
330 static bool surface_duplicateOutputExists(void *arg, const char *name)
331 {
332         DynamicPaintSurface *t_surface = arg;
333         DynamicPaintSurface *surface = t_surface->canvas->surfaces.first;
334
335         for (; surface; surface = surface->next) {
336                 if (surface != t_surface && surface->type == t_surface->type && surface->format == t_surface->format) {
337                         if ((surface->output_name[0] != '\0' && !BLI_path_cmp(name, surface->output_name)) ||
338                             (surface->output_name2[0] != '\0' && !BLI_path_cmp(name, surface->output_name2)))
339                         {
340                                 return true;
341                         }
342                 }
343         }
344         return false;
345 }
346
347 static void surface_setUniqueOutputName(DynamicPaintSurface *surface, char *basename, int output)
348 {
349         char name[64];
350         BLI_strncpy(name, basename, sizeof(name)); /* in case basename is surface->name use a copy */
351         if (output == 0) {
352                 BLI_uniquename_cb(surface_duplicateOutputExists, surface, name, '.',
353                                   surface->output_name, sizeof(surface->output_name));
354         }
355         else if (output == 1) {
356                 BLI_uniquename_cb(surface_duplicateOutputExists, surface, name, '.',
357                                   surface->output_name2, sizeof(surface->output_name2));
358         }
359 }
360
361
362 static bool surface_duplicateNameExists(void *arg, const char *name)
363 {
364         DynamicPaintSurface *t_surface = arg;
365         DynamicPaintSurface *surface = t_surface->canvas->surfaces.first;
366
367         for (; surface; surface = surface->next) {
368                 if (surface != t_surface && STREQ(name, surface->name))
369                         return true;
370         }
371         return false;
372 }
373
374 void dynamicPaintSurface_setUniqueName(DynamicPaintSurface *surface, const char *basename)
375 {
376         char name[64];
377         BLI_strncpy(name, basename, sizeof(name)); /* in case basename is surface->name use a copy */
378         BLI_uniquename_cb(surface_duplicateNameExists, surface, name, '.', surface->name, sizeof(surface->name));
379 }
380
381
382 /* change surface data to defaults on new type */
383 void dynamicPaintSurface_updateType(struct DynamicPaintSurface *surface)
384 {
385         if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
386                 surface->output_name[0] = '\0';
387                 surface->output_name2[0] = '\0';
388                 surface->flags |= MOD_DPAINT_ANTIALIAS;
389                 surface->depth_clamp = 1.0f;
390         }
391         else {
392                 strcpy(surface->output_name, "dp_");
393                 BLI_strncpy(surface->output_name2, surface->output_name, sizeof(surface->output_name2));
394                 surface->flags &= ~MOD_DPAINT_ANTIALIAS;
395                 surface->depth_clamp = 0.0f;
396         }
397
398         if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
399                 strcat(surface->output_name, "paintmap");
400                 strcat(surface->output_name2, "wetmap");
401                 surface_setUniqueOutputName(surface, surface->output_name2, 1);
402         }
403         else if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
404                 strcat(surface->output_name, "displace");
405         }
406         else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) {
407                 strcat(surface->output_name, "weight");
408         }
409         else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
410                 strcat(surface->output_name, "wave");
411         }
412
413         surface_setUniqueOutputName(surface, surface->output_name, 0);
414
415         /* update preview */
416         if (dynamicPaint_surfaceHasColorPreview(surface))
417                 dynamicPaint_setPreview(surface);
418         else
419                 dynamicPaint_resetPreview(surface->canvas);
420 }
421
422 static int surface_totalSamples(DynamicPaintSurface *surface)
423 {
424         if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ && surface->flags & MOD_DPAINT_ANTIALIAS) {
425                 return (surface->data->total_points * 5);
426         }
427         if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX &&
428             surface->flags & MOD_DPAINT_ANTIALIAS && surface->data->adj_data)
429         {
430                 return (surface->data->total_points + surface->data->adj_data->total_targets);
431         }
432
433         return surface->data->total_points;
434 }
435
436 static void blendColors(
437         const float t_color[3], const float t_alpha, const float s_color[3], const float s_alpha, float result[4])
438 {
439         /* Same thing as BLI's blend_color_mix_float(), but for non-premultiplied alpha. */
440         int i;
441         float i_alpha = 1.0f - s_alpha;
442         float f_alpha = t_alpha * i_alpha + s_alpha;
443
444         /* blend colors */
445         if (f_alpha) {
446                 for (i = 0; i < 3; i++) {
447                         result[i] = (t_color[i] * t_alpha * i_alpha + s_color[i] * s_alpha) / f_alpha;
448                 }
449         }
450         else {
451                 copy_v3_v3(result, t_color);
452         }
453         /* return final alpha */
454         result[3] = f_alpha;
455 }
456
457 /* Mix two alpha weighed colors by a defined ratio. output is saved at a_color */
458 static float mixColors(float a_color[3], float a_weight, const float b_color[3], float b_weight, float ratio)
459 {
460         float weight_ratio, factor;
461         if (b_weight) {
462                 /* if first value has no weight just use b_color */
463                 if (!a_weight) {
464                         copy_v3_v3(a_color, b_color);
465                         return b_weight * ratio;
466                 }
467                 weight_ratio = b_weight / (a_weight + b_weight);
468         }
469         else {
470                 return a_weight * (1.0f - ratio);
471         }
472
473         /* calculate final interpolation factor */
474         if (ratio <= 0.5f) {
475                 factor = weight_ratio * (ratio * 2.0f);
476         }
477         else {
478                 ratio = (ratio * 2.0f - 1.0f);
479                 factor = weight_ratio * (1.0f - ratio) + ratio;
480         }
481         /* mix final color */
482         interp_v3_v3v3(a_color, a_color, b_color, factor);
483         return (1.0f - factor) * a_weight + factor * b_weight;
484 }
485
486 static void scene_setSubframe(Scene *scene, float subframe)
487 {
488         /* dynamic paint subframes must be done on previous frame */
489         scene->r.cfra -= 1;
490         scene->r.subframe = subframe;
491 }
492
493 static int surface_getBrushFlags(DynamicPaintSurface *surface, Depsgraph *depsgraph)
494 {
495         unsigned int numobjects;
496         Object **objects = BKE_collision_objects_create(depsgraph, NULL, surface->brush_group, &numobjects, eModifierType_DynamicPaint);
497
498         int flags = 0;
499
500         for (int i = 0; i < numobjects; i++) {
501                 Object *brushObj = objects[i];
502
503                 ModifierData *md = modifiers_findByType(brushObj, eModifierType_DynamicPaint);
504                 if (md && md->mode & (eModifierMode_Realtime | eModifierMode_Render)) {
505                         DynamicPaintModifierData *pmd2 = (DynamicPaintModifierData *)md;
506
507                         if (pmd2->brush) {
508                                 DynamicPaintBrushSettings *brush = pmd2->brush;
509
510                                 if (brush->flags & MOD_DPAINT_USES_VELOCITY)
511                                         flags |= BRUSH_USES_VELOCITY;
512                         }
513                 }
514         }
515
516         BKE_collision_objects_free(objects);
517
518         return flags;
519 }
520
521 /* check whether two bounds intersect */
522 static bool boundsIntersect(Bounds3D *b1, Bounds3D *b2)
523 {
524         if (!b1->valid || !b2->valid)
525                 return false;
526         for (int i = 2; i--;) {
527                 if (!(b1->min[i] <= b2->max[i] && b1->max[i] >= b2->min[i]))
528                         return false;
529         }
530         return true;
531 }
532
533 /* check whether two bounds intersect inside defined proximity */
534 static bool boundsIntersectDist(Bounds3D *b1, Bounds3D *b2, const float dist)
535 {
536         if (!b1->valid || !b2->valid)
537                 return false;
538         for (int i = 2; i--;) {
539                 if (!(b1->min[i] <= (b2->max[i] + dist) && b1->max[i] >= (b2->min[i] - dist)))
540                         return false;
541         }
542         return true;
543 }
544
545 /* check whether bounds intersects a point with given radius */
546 static bool boundIntersectPoint(Bounds3D *b, float point[3], const float radius)
547 {
548         if (!b->valid)
549                 return false;
550         for (int i = 2; i--;) {
551                 if (!(b->min[i] <= (point[i] + radius) && b->max[i] >= (point[i] - radius)))
552                         return false;
553         }
554         return true;
555 }
556
557 /* expand bounds by a new point */
558 static void boundInsert(Bounds3D *b, float point[3])
559 {
560         if (!b->valid) {
561                 copy_v3_v3(b->min, point);
562                 copy_v3_v3(b->max, point);
563                 b->valid = true;
564                 return;
565         }
566
567         minmax_v3v3_v3(b->min, b->max, point);
568 }
569
570 static float getSurfaceDimension(PaintSurfaceData *sData)
571 {
572         Bounds3D *mb = &sData->bData->mesh_bounds;
573         return max_fff((mb->max[0] - mb->min[0]), (mb->max[1] - mb->min[1]), (mb->max[2] - mb->min[2]));
574 }
575
576 static void freeGrid(PaintSurfaceData *data)
577 {
578         PaintBakeData *bData = data->bData;
579         VolumeGrid *grid = bData->grid;
580
581         if (grid->bounds) MEM_freeN(grid->bounds);
582         if (grid->s_pos) MEM_freeN(grid->s_pos);
583         if (grid->s_num) MEM_freeN(grid->s_num);
584         if (grid->t_index) MEM_freeN(grid->t_index);
585
586         MEM_freeN(bData->grid);
587         bData->grid = NULL;
588 }
589
590 static void grid_bound_insert_cb_ex(void *__restrict userdata,
591                                     const int i,
592                                     const ParallelRangeTLS *__restrict tls)
593 {
594         PaintBakeData *bData = userdata;
595
596         Bounds3D *grid_bound = tls->userdata_chunk;
597
598         boundInsert(grid_bound, bData->realCoord[bData->s_pos[i]].v);
599 }
600
601 static void grid_bound_insert_finalize(void *__restrict userdata,
602                                        void *__restrict userdata_chunk)
603 {
604         PaintBakeData *bData = userdata;
605         VolumeGrid *grid = bData->grid;
606
607         Bounds3D *grid_bound = userdata_chunk;
608
609         boundInsert(&grid->grid_bounds, grid_bound->min);
610         boundInsert(&grid->grid_bounds, grid_bound->max);
611 }
612
613 static void grid_cell_points_cb_ex(void *__restrict userdata,
614                                    const int i,
615                                    const ParallelRangeTLS *__restrict tls)
616 {
617         PaintBakeData *bData = userdata;
618         VolumeGrid *grid = bData->grid;
619         int *temp_t_index = grid->temp_t_index;
620         int *s_num = tls->userdata_chunk;
621
622         int co[3];
623
624         for (int j = 3; j--;) {
625                 co[j] = (int)floorf((bData->realCoord[bData->s_pos[i]].v[j] - grid->grid_bounds.min[j]) /
626                                     bData->dim[j] * grid->dim[j]);
627                 CLAMP(co[j], 0, grid->dim[j] - 1);
628         }
629
630         temp_t_index[i] = co[0] + co[1] * grid->dim[0] + co[2] * grid->dim[0] * grid->dim[1];
631         s_num[temp_t_index[i]]++;
632 }
633
634 static void grid_cell_points_finalize(void *__restrict userdata,
635                                       void *__restrict userdata_chunk)
636 {
637         PaintBakeData *bData = userdata;
638         VolumeGrid *grid = bData->grid;
639         const int grid_cells = grid->dim[0] * grid->dim[1] * grid->dim[2];
640
641         int *s_num = userdata_chunk;
642
643         /* calculate grid indexes */
644         for (int i = 0; i < grid_cells; i++) {
645                 grid->s_num[i] += s_num[i];
646         }
647 }
648
649 static void grid_cell_bounds_cb(void *__restrict userdata,
650                                 const int x,
651                                 const ParallelRangeTLS *__restrict UNUSED(tls))
652 {
653         PaintBakeData *bData = userdata;
654         VolumeGrid *grid = bData->grid;
655         float *dim = bData->dim;
656         int *grid_dim = grid->dim;
657
658         for (int y = 0; y < grid_dim[1]; y++) {
659                 for (int z = 0; z < grid_dim[2]; z++) {
660                         const int b_index = x + y * grid_dim[0] + z * grid_dim[0] * grid_dim[1];
661                         /* set bounds */
662                         for (int j = 3; j--;) {
663                                 const int s = (j == 0) ? x : ((j == 1) ? y : z);
664                                 grid->bounds[b_index].min[j] = grid->grid_bounds.min[j] + dim[j] / grid_dim[j] * s;
665                                 grid->bounds[b_index].max[j] = grid->grid_bounds.min[j] + dim[j] / grid_dim[j] * (s + 1);
666                         }
667                         grid->bounds[b_index].valid = true;
668                 }
669         }
670 }
671
672 static void surfaceGenerateGrid(struct DynamicPaintSurface *surface)
673 {
674         PaintSurfaceData *sData = surface->data;
675         PaintBakeData *bData = sData->bData;
676         VolumeGrid *grid;
677         int grid_cells, axis = 3;
678         int *temp_t_index = NULL;
679         int *temp_s_num = NULL;
680
681         if (bData->grid)
682                 freeGrid(sData);
683
684         bData->grid = MEM_callocN(sizeof(VolumeGrid), "Surface Grid");
685         grid = bData->grid;
686
687         {
688                 int i, error = 0;
689                 float dim_factor, volume, dim[3];
690                 float td[3];
691                 float min_dim;
692
693                 /* calculate canvas dimensions */
694                 /* Important to init correctly our ref grid_bound... */
695                 boundInsert(&grid->grid_bounds, bData->realCoord[bData->s_pos[0]].v);
696                 {
697                         ParallelRangeSettings settings;
698                         BLI_parallel_range_settings_defaults(&settings);
699                         settings.use_threading = (sData->total_points > 1000);
700                         settings.userdata_chunk = &grid->grid_bounds;
701                         settings.userdata_chunk_size = sizeof(grid->grid_bounds);
702                         settings.func_finalize = grid_bound_insert_finalize;
703                         BLI_task_parallel_range(
704                                 0, sData->total_points,
705                                 bData,
706                                 grid_bound_insert_cb_ex,
707                                 &settings);
708                 }
709                 /* get dimensions */
710                 sub_v3_v3v3(dim, grid->grid_bounds.max, grid->grid_bounds.min);
711                 copy_v3_v3(td, dim);
712                 copy_v3_v3(bData->dim, dim);
713                 min_dim = max_fff(td[0], td[1], td[2]) / 1000.f;
714
715                 /* deactivate zero axises */
716                 for (i = 0; i < 3; i++) {
717                         if (td[i] < min_dim) {
718                                 td[i] = 1.0f;
719                                 axis--;
720                         }
721                 }
722
723                 if (axis == 0 || max_fff(td[0], td[1], td[2]) < 0.0001f) {
724                         MEM_freeN(bData->grid);
725                         bData->grid = NULL;
726                         return;
727                 }
728
729                 /* now calculate grid volume/area/width depending on num of active axis */
730                 volume = td[0] * td[1] * td[2];
731
732                 /* determine final grid size by trying to fit average 10.000 points per grid cell */
733                 dim_factor = (float)pow((double)volume / ((double)sData->total_points / 10000.0), 1.0 / (double)axis);
734
735                 /* define final grid size using dim_factor, use min 3 for active axises */
736                 for (i = 0; i < 3; i++) {
737                         grid->dim[i] = (int)floor(td[i] / dim_factor);
738                         CLAMP(grid->dim[i], (dim[i] >= min_dim) ? 3 : 1, 100);
739                 }
740                 grid_cells = grid->dim[0] * grid->dim[1] * grid->dim[2];
741
742                 /* allocate memory for grids */
743                 grid->bounds = MEM_callocN(sizeof(Bounds3D) * grid_cells, "Surface Grid Bounds");
744                 grid->s_pos = MEM_callocN(sizeof(int) * grid_cells, "Surface Grid Position");
745
746                 grid->s_num = MEM_callocN(sizeof(int) * grid_cells, "Surface Grid Points");
747                 temp_s_num = MEM_callocN(sizeof(int) * grid_cells, "Temp Surface Grid Points");
748                 grid->t_index = MEM_callocN(sizeof(int) * sData->total_points, "Surface Grid Target Ids");
749                 grid->temp_t_index = temp_t_index = MEM_callocN(sizeof(int) * sData->total_points, "Temp Surface Grid Target Ids");
750
751                 /* in case of an allocation failure abort here */
752                 if (!grid->bounds || !grid->s_pos || !grid->s_num || !grid->t_index || !temp_s_num || !temp_t_index)
753                         error = 1;
754
755                 if (!error) {
756                         /* calculate number of points within each cell */
757                         {
758                                 ParallelRangeSettings settings;
759                                 BLI_parallel_range_settings_defaults(&settings);
760                                 settings.use_threading = (sData->total_points > 1000);
761                                 settings.userdata_chunk = grid->s_num;
762                                 settings.userdata_chunk_size = sizeof(*grid->s_num) * grid_cells;
763                                 settings.func_finalize = grid_cell_points_finalize;
764                                 BLI_task_parallel_range(
765                                         0, sData->total_points,
766                                         bData,
767                                         grid_cell_points_cb_ex,
768                                         &settings);
769                         }
770
771                         /* calculate grid indexes (not needed for first cell, which is zero). */
772                         for (i = 1; i < grid_cells; i++) {
773                                 grid->s_pos[i] = grid->s_pos[i - 1] + grid->s_num[i - 1];
774                         }
775
776                         /* save point indexes to final array */
777                         for (i = 0; i < sData->total_points; i++) {
778                                 int pos = grid->s_pos[temp_t_index[i]] + temp_s_num[temp_t_index[i]];
779                                 grid->t_index[pos] = i;
780
781                                 temp_s_num[temp_t_index[i]]++;
782                         }
783
784                         /* calculate cell bounds */
785                         {
786                                 ParallelRangeSettings settings;
787                                 BLI_parallel_range_settings_defaults(&settings);
788                                 settings.use_threading = (grid_cells > 1000);
789                                 BLI_task_parallel_range(0, grid->dim[0],
790                                                         bData,
791                                                         grid_cell_bounds_cb,
792                                                         &settings);
793                         }
794                 }
795
796                 if (temp_s_num)
797                         MEM_freeN(temp_s_num);
798                 if (temp_t_index)
799                         MEM_freeN(temp_t_index);
800                 grid->temp_t_index = NULL;
801
802                 if (error || !grid->s_num) {
803                         setError(surface->canvas, N_("Not enough free memory"));
804                         freeGrid(sData);
805                 }
806         }
807 }
808
809 /***************************** Freeing data ******************************/
810
811 /* Free brush data */
812 void dynamicPaint_freeBrush(struct DynamicPaintModifierData *pmd)
813 {
814         if (pmd->brush) {
815                 if (pmd->brush->mesh) {
816                         BKE_id_free(NULL, pmd->brush->mesh);
817                 }
818                 pmd->brush->mesh = NULL;
819
820                 if (pmd->brush->paint_ramp)
821                         MEM_freeN(pmd->brush->paint_ramp);
822                 if (pmd->brush->vel_ramp)
823                         MEM_freeN(pmd->brush->vel_ramp);
824
825                 MEM_freeN(pmd->brush);
826                 pmd->brush = NULL;
827         }
828 }
829
830 static void dynamicPaint_freeAdjData(PaintSurfaceData *data)
831 {
832         if (data->adj_data) {
833                 if (data->adj_data->n_index)
834                         MEM_freeN(data->adj_data->n_index);
835                 if (data->adj_data->n_num)
836                         MEM_freeN(data->adj_data->n_num);
837                 if (data->adj_data->n_target)
838                         MEM_freeN(data->adj_data->n_target);
839                 if (data->adj_data->flags)
840                         MEM_freeN(data->adj_data->flags);
841                 if (data->adj_data->border)
842                         MEM_freeN(data->adj_data->border);
843                 MEM_freeN(data->adj_data);
844                 data->adj_data = NULL;
845         }
846 }
847
848 static void free_bakeData(PaintSurfaceData *data)
849 {
850         PaintBakeData *bData = data->bData;
851         if (bData) {
852                 if (bData->bNormal)
853                         MEM_freeN(bData->bNormal);
854                 if (bData->s_pos)
855                         MEM_freeN(bData->s_pos);
856                 if (bData->s_num)
857                         MEM_freeN(bData->s_num);
858                 if (bData->realCoord)
859                         MEM_freeN(bData->realCoord);
860                 if (bData->bNeighs)
861                         MEM_freeN(bData->bNeighs);
862                 if (bData->grid)
863                         freeGrid(data);
864                 if (bData->prev_verts)
865                         MEM_freeN(bData->prev_verts);
866                 if (bData->velocity)
867                         MEM_freeN(bData->velocity);
868                 if (bData->prev_velocity)
869                         MEM_freeN(bData->prev_velocity);
870
871                 MEM_freeN(data->bData);
872                 data->bData = NULL;
873         }
874 }
875
876 /* free surface data if it's not used anymore */
877 static void surface_freeUnusedData(DynamicPaintSurface *surface)
878 {
879         if (!surface->data)
880                 return;
881
882         /* free bakedata if not active or surface is baked */
883         if (!(surface->flags & MOD_DPAINT_ACTIVE) || (surface->pointcache && surface->pointcache->flag & PTCACHE_BAKED)) {
884                 free_bakeData(surface->data);
885         }
886 }
887
888 void dynamicPaint_freeSurfaceData(DynamicPaintSurface *surface)
889 {
890         PaintSurfaceData *data = surface->data;
891         if (!data)
892                 return;
893
894         if (data->format_data) {
895                 /* format specific free */
896                 if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
897                         ImgSeqFormatData *format_data = (ImgSeqFormatData *)data->format_data;
898                         if (format_data->uv_p)
899                                 MEM_freeN(format_data->uv_p);
900                         if (format_data->barycentricWeights)
901                                 MEM_freeN(format_data->barycentricWeights);
902                 }
903                 MEM_freeN(data->format_data);
904         }
905         /* type data */
906         if (data->type_data)
907                 MEM_freeN(data->type_data);
908         dynamicPaint_freeAdjData(data);
909         /* bake data */
910         free_bakeData(data);
911
912         MEM_freeN(surface->data);
913         surface->data = NULL;
914 }
915
916 void dynamicPaint_freeSurface(const DynamicPaintModifierData *pmd,
917                               DynamicPaintSurface *surface)
918 {
919         /* point cache */
920         if ((pmd->modifier.flag & eModifierFlag_SharedCaches) == 0) {
921                 BKE_ptcache_free_list(&(surface->ptcaches));
922         }
923         surface->pointcache = NULL;
924
925         if (surface->effector_weights)
926                 MEM_freeN(surface->effector_weights);
927         surface->effector_weights = NULL;
928
929         BLI_remlink(&(surface->canvas->surfaces), surface);
930         dynamicPaint_freeSurfaceData(surface);
931         MEM_freeN(surface);
932 }
933
934 /* Free canvas data */
935 void dynamicPaint_freeCanvas(DynamicPaintModifierData *pmd)
936 {
937         if (pmd->canvas) {
938                 /* Free surface data */
939                 DynamicPaintSurface *surface = pmd->canvas->surfaces.first;
940                 DynamicPaintSurface *next_surface = NULL;
941
942                 while (surface) {
943                         next_surface = surface->next;
944                         dynamicPaint_freeSurface(pmd, surface);
945                         surface = next_surface;
946                 }
947
948                 /* free mesh copy */
949                 if (pmd->canvas->mesh) {
950                         BKE_id_free(NULL, pmd->canvas->mesh);
951                 }
952                 pmd->canvas->mesh = NULL;
953
954                 MEM_freeN(pmd->canvas);
955                 pmd->canvas = NULL;
956         }
957 }
958
959 /* Free whole dp modifier */
960 void dynamicPaint_Modifier_free(struct DynamicPaintModifierData *pmd)
961 {
962         if (pmd) {
963                 dynamicPaint_freeCanvas(pmd);
964                 dynamicPaint_freeBrush(pmd);
965         }
966 }
967
968
969 /***************************** Initialize and reset ******************************/
970
971 /*
972  * Creates a new surface and adds it to the list
973  * If scene is null, frame range of 1-250 is used
974  * A pointer to this surface is returned
975  */
976 DynamicPaintSurface *dynamicPaint_createNewSurface(DynamicPaintCanvasSettings *canvas, Scene *scene)
977 {
978         DynamicPaintSurface *surface = MEM_callocN(sizeof(DynamicPaintSurface), "DynamicPaintSurface");
979         if (!surface)
980                 return NULL;
981
982         surface->canvas = canvas;
983         surface->format = MOD_DPAINT_SURFACE_F_VERTEX;
984         surface->type = MOD_DPAINT_SURFACE_T_PAINT;
985
986         /* cache */
987         surface->pointcache = BKE_ptcache_add(&(surface->ptcaches));
988         surface->pointcache->flag |= PTCACHE_DISK_CACHE;
989         surface->pointcache->step = 1;
990
991         /* Set initial values */
992         surface->flags = MOD_DPAINT_ANTIALIAS | MOD_DPAINT_MULALPHA | MOD_DPAINT_DRY_LOG | MOD_DPAINT_DISSOLVE_LOG |
993                          MOD_DPAINT_ACTIVE | MOD_DPAINT_PREVIEW | MOD_DPAINT_OUT1 | MOD_DPAINT_USE_DRYING;
994         surface->effect = 0;
995         surface->effect_ui = 1;
996
997         surface->diss_speed = 250;
998         surface->dry_speed = 500;
999         surface->color_dry_threshold = 1.0f;
1000         surface->depth_clamp = 0.0f;
1001         surface->disp_factor = 1.0f;
1002         surface->disp_type = MOD_DPAINT_DISP_DISPLACE;
1003         surface->image_fileformat = MOD_DPAINT_IMGFORMAT_PNG;
1004
1005         surface->influence_scale = 1.0f;
1006         surface->radius_scale = 1.0f;
1007
1008         surface->init_color[0] = 1.0f;
1009         surface->init_color[1] = 1.0f;
1010         surface->init_color[2] = 1.0f;
1011         surface->init_color[3] = 1.0f;
1012
1013         surface->image_resolution = 256;
1014         surface->substeps = 0;
1015
1016         if (scene) {
1017                 surface->start_frame = scene->r.sfra;
1018                 surface->end_frame = scene->r.efra;
1019         }
1020         else {
1021                 surface->start_frame = 1;
1022                 surface->end_frame = 250;
1023         }
1024
1025         surface->spread_speed = 1.0f;
1026         surface->color_spread_speed = 1.0f;
1027         surface->shrink_speed = 1.0f;
1028
1029         surface->wave_damping = 0.04f;
1030         surface->wave_speed = 1.0f;
1031         surface->wave_timescale = 1.0f;
1032         surface->wave_spring = 0.20f;
1033         surface->wave_smoothness = 1.0f;
1034
1035         modifier_path_init(surface->image_output_path, sizeof(surface->image_output_path), "cache_dynamicpaint");
1036
1037         /* Using ID_BRUSH i18n context, as we have no physics/dpaint one for now... */
1038         dynamicPaintSurface_setUniqueName(surface, CTX_DATA_(BLT_I18NCONTEXT_ID_BRUSH, "Surface"));
1039
1040         surface->effector_weights = BKE_effector_add_weights(NULL);
1041
1042         dynamicPaintSurface_updateType(surface);
1043
1044         BLI_addtail(&canvas->surfaces, surface);
1045
1046         return surface;
1047 }
1048
1049 /*
1050  * Initialize modifier data
1051  */
1052 bool dynamicPaint_createType(struct DynamicPaintModifierData *pmd, int type, struct Scene *scene)
1053 {
1054         if (pmd) {
1055                 if (type == MOD_DYNAMICPAINT_TYPE_CANVAS) {
1056                         DynamicPaintCanvasSettings *canvas;
1057                         if (pmd->canvas)
1058                                 dynamicPaint_freeCanvas(pmd);
1059
1060                         canvas = pmd->canvas = MEM_callocN(sizeof(DynamicPaintCanvasSettings), "DynamicPaint Canvas");
1061                         if (!canvas)
1062                                 return false;
1063                         canvas->pmd = pmd;
1064                         canvas->mesh = NULL;
1065
1066                         /* Create one surface */
1067                         if (!dynamicPaint_createNewSurface(canvas, scene))
1068                                 return false;
1069
1070                 }
1071                 else if (type == MOD_DYNAMICPAINT_TYPE_BRUSH) {
1072                         DynamicPaintBrushSettings *brush;
1073                         if (pmd->brush)
1074                                 dynamicPaint_freeBrush(pmd);
1075
1076                         brush = pmd->brush = MEM_callocN(sizeof(DynamicPaintBrushSettings), "DynamicPaint Paint");
1077                         if (!brush)
1078                                 return false;
1079                         brush->pmd = pmd;
1080
1081                         brush->psys = NULL;
1082
1083                         brush->flags = MOD_DPAINT_ABS_ALPHA | MOD_DPAINT_RAMP_ALPHA;
1084                         brush->collision = MOD_DPAINT_COL_VOLUME;
1085
1086                         brush->r = 0.15f;
1087                         brush->g = 0.4f;
1088                         brush->b = 0.8f;
1089                         brush->alpha = 1.0f;
1090                         brush->wetness = 1.0f;
1091
1092                         brush->paint_distance = 1.0f;
1093                         brush->proximity_falloff = MOD_DPAINT_PRFALL_SMOOTH;
1094
1095                         brush->particle_radius = 0.2f;
1096                         brush->particle_smooth = 0.05f;
1097
1098                         brush->wave_type = MOD_DPAINT_WAVEB_CHANGE;
1099                         brush->wave_factor = 1.0f;
1100                         brush->wave_clamp = 0.0f;
1101                         brush->smudge_strength = 0.3f;
1102                         brush->max_velocity = 1.0f;
1103
1104                         brush->mesh = NULL;
1105
1106                         /* Paint proximity falloff colorramp. */
1107                         {
1108                                 CBData *ramp;
1109
1110                                 brush->paint_ramp = BKE_colorband_add(false);
1111                                 if (!brush->paint_ramp)
1112                                         return false;
1113                                 ramp = brush->paint_ramp->data;
1114                                 /* Add default smooth-falloff ramp. */
1115                                 ramp[0].r = ramp[0].g = ramp[0].b = ramp[0].a = 1.0f;
1116                                 ramp[0].pos = 0.0f;
1117                                 ramp[1].r = ramp[1].g = ramp[1].b = ramp[1].pos = 1.0f;
1118                                 ramp[1].a = 0.0f;
1119                                 pmd->brush->paint_ramp->tot = 2;
1120                         }
1121
1122                         /* Brush velocity ramp. */
1123                         {
1124                                 CBData *ramp;
1125
1126                                 brush->vel_ramp = BKE_colorband_add(false);
1127                                 if (!brush->vel_ramp)
1128                                         return false;
1129                                 ramp = brush->vel_ramp->data;
1130                                 ramp[0].r = ramp[0].g = ramp[0].b = ramp[0].a = ramp[0].pos = 0.0f;
1131                                 ramp[1].r = ramp[1].g = ramp[1].b = ramp[1].a = ramp[1].pos = 1.0f;
1132                                 brush->paint_ramp->tot = 2;
1133                         }
1134                 }
1135         }
1136         else {
1137                 return false;
1138         }
1139
1140         return true;
1141 }
1142
1143 void dynamicPaint_Modifier_copy(const struct DynamicPaintModifierData *pmd,
1144                                 struct DynamicPaintModifierData *tpmd,
1145                                 int flag)
1146 {
1147         /* Init modifier */
1148         tpmd->type = pmd->type;
1149         if (pmd->canvas)
1150                 dynamicPaint_createType(tpmd, MOD_DYNAMICPAINT_TYPE_CANVAS, NULL);
1151         if (pmd->brush)
1152                 dynamicPaint_createType(tpmd, MOD_DYNAMICPAINT_TYPE_BRUSH, NULL);
1153
1154         /* Copy data */
1155         if (tpmd->canvas) {
1156                 DynamicPaintSurface *surface;
1157                 tpmd->canvas->pmd = tpmd;
1158                 /* free default surface */
1159                 if (tpmd->canvas->surfaces.first)
1160                         dynamicPaint_freeSurface(tpmd, tpmd->canvas->surfaces.first);
1161
1162                 /* copy existing surfaces */
1163                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1164                         DynamicPaintSurface *t_surface = dynamicPaint_createNewSurface(tpmd->canvas, NULL);
1165                         if (flag & LIB_ID_CREATE_NO_MAIN) {
1166                                 /* TODO(sergey): Consider passing some tips to the surface
1167                                  * creation to avoid this allocate-and-free cache behavior. */
1168                                 BKE_ptcache_free_list(&t_surface->ptcaches);
1169                                 tpmd->modifier.flag |= eModifierFlag_SharedCaches;
1170                                 t_surface->ptcaches = surface->ptcaches;
1171                                 t_surface->pointcache = surface->pointcache;
1172                         }
1173
1174                         /* surface settings */
1175                         t_surface->brush_group = surface->brush_group;
1176                         MEM_freeN(t_surface->effector_weights);
1177                         t_surface->effector_weights = MEM_dupallocN(surface->effector_weights);
1178
1179                         BLI_strncpy(t_surface->name, surface->name, sizeof(t_surface->name));
1180                         t_surface->format = surface->format;
1181                         t_surface->type = surface->type;
1182                         t_surface->disp_type = surface->disp_type;
1183                         t_surface->image_fileformat = surface->image_fileformat;
1184                         t_surface->effect_ui = surface->effect_ui;
1185                         t_surface->preview_id = surface->preview_id;
1186                         t_surface->init_color_type = surface->init_color_type;
1187                         t_surface->flags = surface->flags;
1188                         t_surface->effect = surface->effect;
1189
1190                         t_surface->image_resolution = surface->image_resolution;
1191                         t_surface->substeps = surface->substeps;
1192                         t_surface->start_frame = surface->start_frame;
1193                         t_surface->end_frame = surface->end_frame;
1194
1195                         copy_v4_v4(t_surface->init_color, surface->init_color);
1196                         t_surface->init_texture = surface->init_texture;
1197                         BLI_strncpy(t_surface->init_layername, surface->init_layername, sizeof(t_surface->init_layername));
1198
1199                         t_surface->dry_speed = surface->dry_speed;
1200                         t_surface->diss_speed = surface->diss_speed;
1201                         t_surface->color_dry_threshold = surface->color_dry_threshold;
1202                         t_surface->depth_clamp = surface->depth_clamp;
1203                         t_surface->disp_factor = surface->disp_factor;
1204
1205
1206                         t_surface->spread_speed = surface->spread_speed;
1207                         t_surface->color_spread_speed = surface->color_spread_speed;
1208                         t_surface->shrink_speed = surface->shrink_speed;
1209                         t_surface->drip_vel = surface->drip_vel;
1210                         t_surface->drip_acc = surface->drip_acc;
1211
1212                         t_surface->influence_scale = surface->influence_scale;
1213                         t_surface->radius_scale = surface->radius_scale;
1214
1215                         t_surface->wave_damping = surface->wave_damping;
1216                         t_surface->wave_speed = surface->wave_speed;
1217                         t_surface->wave_timescale = surface->wave_timescale;
1218                         t_surface->wave_spring = surface->wave_spring;
1219                         t_surface->wave_smoothness = surface->wave_smoothness;
1220
1221                         BLI_strncpy(t_surface->uvlayer_name, surface->uvlayer_name, sizeof(t_surface->uvlayer_name));
1222                         BLI_strncpy(t_surface->image_output_path, surface->image_output_path, sizeof(t_surface->image_output_path));
1223                         BLI_strncpy(t_surface->output_name, surface->output_name, sizeof(t_surface->output_name));
1224                         BLI_strncpy(t_surface->output_name2, surface->output_name2, sizeof(t_surface->output_name2));
1225                 }
1226                 dynamicPaint_resetPreview(tpmd->canvas);
1227         }
1228         else if (tpmd->brush) {
1229                 DynamicPaintBrushSettings *brush = pmd->brush, *t_brush = tpmd->brush;
1230                 t_brush->pmd = tpmd;
1231
1232                 t_brush->flags = brush->flags;
1233                 t_brush->collision = brush->collision;
1234
1235                 t_brush->r = brush->r;
1236                 t_brush->g = brush->g;
1237                 t_brush->b = brush->b;
1238                 t_brush->alpha = brush->alpha;
1239                 t_brush->wetness = brush->wetness;
1240
1241                 t_brush->particle_radius = brush->particle_radius;
1242                 t_brush->particle_smooth = brush->particle_smooth;
1243                 t_brush->paint_distance = brush->paint_distance;
1244                 t_brush->psys = brush->psys;
1245
1246                 if (brush->paint_ramp)
1247                         memcpy(t_brush->paint_ramp, brush->paint_ramp, sizeof(ColorBand));
1248                 if (brush->vel_ramp)
1249                         memcpy(t_brush->vel_ramp, brush->vel_ramp, sizeof(ColorBand));
1250
1251                 t_brush->proximity_falloff = brush->proximity_falloff;
1252                 t_brush->wave_type = brush->wave_type;
1253                 t_brush->ray_dir = brush->ray_dir;
1254
1255                 t_brush->wave_factor = brush->wave_factor;
1256                 t_brush->wave_clamp = brush->wave_clamp;
1257                 t_brush->max_velocity = brush->max_velocity;
1258                 t_brush->smudge_strength = brush->smudge_strength;
1259         }
1260 }
1261
1262 /* allocates surface data depending on surface type */
1263 static void dynamicPaint_allocateSurfaceType(DynamicPaintSurface *surface)
1264 {
1265         PaintSurfaceData *sData = surface->data;
1266
1267         switch (surface->type) {
1268                 case MOD_DPAINT_SURFACE_T_PAINT:
1269                         sData->type_data = MEM_callocN(sizeof(PaintPoint) * sData->total_points, "DynamicPaintSurface Data");
1270                         break;
1271                 case MOD_DPAINT_SURFACE_T_DISPLACE:
1272                         sData->type_data = MEM_callocN(sizeof(float) * sData->total_points, "DynamicPaintSurface DepthData");
1273                         break;
1274                 case MOD_DPAINT_SURFACE_T_WEIGHT:
1275                         sData->type_data = MEM_callocN(sizeof(float) * sData->total_points, "DynamicPaintSurface WeightData");
1276                         break;
1277                 case MOD_DPAINT_SURFACE_T_WAVE:
1278                         sData->type_data = MEM_callocN(sizeof(PaintWavePoint) * sData->total_points, "DynamicPaintSurface WaveData");
1279                         break;
1280         }
1281
1282         if (sData->type_data == NULL)
1283                 setError(surface->canvas, N_("Not enough free memory"));
1284 }
1285
1286 static bool surface_usesAdjDistance(DynamicPaintSurface *surface)
1287 {
1288         return ((surface->type == MOD_DPAINT_SURFACE_T_PAINT && surface->effect) ||
1289                 (surface->type == MOD_DPAINT_SURFACE_T_WAVE));
1290 }
1291
1292 static bool surface_usesAdjData(DynamicPaintSurface *surface)
1293 {
1294         return (surface_usesAdjDistance(surface) ||
1295                 (surface->format == MOD_DPAINT_SURFACE_F_VERTEX && surface->flags & MOD_DPAINT_ANTIALIAS));
1296 }
1297
1298 /* initialize surface adjacency data */
1299 static void dynamicPaint_initAdjacencyData(DynamicPaintSurface *surface, const bool force_init)
1300 {
1301         PaintSurfaceData *sData = surface->data;
1302         Mesh *mesh = surface->canvas->mesh;
1303         PaintAdjData *ad;
1304         int *temp_data;
1305         int neigh_points = 0;
1306
1307         if (!force_init && !surface_usesAdjData(surface))
1308                 return;
1309
1310         if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1311                 /* For vertex format, neighbors are connected by edges */
1312                 neigh_points = 2 * mesh->totedge;
1313         }
1314         else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1315                 neigh_points = sData->total_points * 8;
1316         }
1317
1318         if (!neigh_points)
1319                 return;
1320
1321         /* allocate memory */
1322         ad = sData->adj_data = MEM_callocN(sizeof(PaintAdjData), "Surface Adj Data");
1323         if (!ad)
1324                 return;
1325         ad->n_index = MEM_callocN(sizeof(int) * sData->total_points, "Surface Adj Index");
1326         ad->n_num = MEM_callocN(sizeof(int) * sData->total_points, "Surface Adj Counts");
1327         temp_data = MEM_callocN(sizeof(int) * sData->total_points, "Temp Adj Data");
1328         ad->n_target = MEM_callocN(sizeof(int) * neigh_points, "Surface Adj Targets");
1329         ad->flags = MEM_callocN(sizeof(int) * sData->total_points, "Surface Adj Flags");
1330         ad->total_targets = neigh_points;
1331         ad->border = NULL;
1332         ad->total_border = 0;
1333
1334         /* in case of allocation error, free memory */
1335         if (!ad->n_index || !ad->n_num || !ad->n_target || !temp_data) {
1336                 dynamicPaint_freeAdjData(sData);
1337                 if (temp_data)
1338                         MEM_freeN(temp_data);
1339                 setError(surface->canvas, N_("Not enough free memory"));
1340                 return;
1341         }
1342
1343         if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1344                 int i;
1345                 int n_pos;
1346
1347                 /* For vertex format, count every vertex that is connected by an edge */
1348                 int numOfEdges = mesh->totedge;
1349                 int numOfPolys = mesh->totpoly;
1350                 struct MEdge *edge =  mesh->medge;
1351                 struct MPoly *mpoly = mesh->mpoly;
1352                 struct MLoop *mloop = mesh->mloop;
1353
1354                 /* count number of edges per vertex */
1355                 for (i = 0; i < numOfEdges; i++) {
1356                         ad->n_num[edge[i].v1]++;
1357                         ad->n_num[edge[i].v2]++;
1358
1359                         temp_data[edge[i].v1]++;
1360                         temp_data[edge[i].v2]++;
1361                 }
1362
1363                 /* also add number of vertices to temp_data
1364                  * to locate points on "mesh edge" */
1365                 for (i = 0; i < numOfPolys; i++) {
1366                         for (int j = 0; j < mpoly[i].totloop; j++) {
1367                                 temp_data[mloop[mpoly[i].loopstart + j].v]++;
1368                         }
1369                 }
1370
1371                 /* now check if total number of edges+faces for
1372                  * each vertex is even, if not -> vertex is on mesh edge */
1373                 for (i = 0; i < sData->total_points; i++) {
1374                         if ((temp_data[i] % 2) || (temp_data[i] < 4)) {
1375                                 ad->flags[i] |= ADJ_ON_MESH_EDGE;
1376                         }
1377
1378                         /* reset temp data */
1379                         temp_data[i] = 0;
1380                 }
1381
1382                 /* order n_index array */
1383                 n_pos = 0;
1384                 for (i = 0; i < sData->total_points; i++) {
1385                         ad->n_index[i] = n_pos;
1386                         n_pos += ad->n_num[i];
1387                 }
1388
1389                 /* and now add neighbor data using that info */
1390                 for (i = 0; i < numOfEdges; i++) {
1391                         /* first vertex */
1392                         int index = edge[i].v1;
1393                         n_pos = ad->n_index[index] + temp_data[index];
1394                         ad->n_target[n_pos] = edge[i].v2;
1395                         temp_data[index]++;
1396
1397                         /* second vertex */
1398                         index = edge[i].v2;
1399                         n_pos = ad->n_index[index] + temp_data[index];
1400                         ad->n_target[n_pos] = edge[i].v1;
1401                         temp_data[index]++;
1402                 }
1403         }
1404         else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1405                 /* for image sequences, only allocate memory.
1406                  * bake initialization takes care of rest */
1407         }
1408
1409         MEM_freeN(temp_data);
1410 }
1411
1412 typedef struct DynamicPaintSetInitColorData {
1413         const DynamicPaintSurface *surface;
1414
1415         const MLoop *mloop;
1416         const MLoopUV *mloopuv;
1417         const MLoopTri *mlooptri;
1418         const MLoopCol *mloopcol;
1419         struct ImagePool *pool;
1420
1421         const bool scene_color_manage;
1422 } DynamicPaintSetInitColorData;
1423
1424 static void dynamic_paint_set_init_color_tex_to_vcol_cb(
1425         void *__restrict userdata,
1426         const int i,
1427         const ParallelRangeTLS *__restrict UNUSED(tls))
1428 {
1429         const DynamicPaintSetInitColorData *data = userdata;
1430
1431         const PaintSurfaceData *sData = data->surface->data;
1432         PaintPoint *pPoint = (PaintPoint *)sData->type_data;
1433
1434         const MLoop *mloop = data->mloop;
1435         const MLoopTri *mlooptri = data->mlooptri;
1436         const MLoopUV *mloopuv = data->mloopuv;
1437         struct ImagePool *pool = data->pool;
1438         Tex *tex = data->surface->init_texture;
1439
1440         const bool scene_color_manage = data->scene_color_manage;
1441
1442         float uv[3] = {0.0f};
1443
1444         for (int j = 3; j--;) {
1445                 TexResult texres = {0};
1446                 const unsigned int vert = mloop[mlooptri[i].tri[j]].v;
1447
1448                 /* remap to [-1.0, 1.0] */
1449                 uv[0] = mloopuv[mlooptri[i].tri[j]].uv[0] * 2.0f - 1.0f;
1450                 uv[1] = mloopuv[mlooptri[i].tri[j]].uv[1] * 2.0f - 1.0f;
1451
1452                 multitex_ext_safe(tex, uv, &texres, pool, scene_color_manage, false);
1453
1454                 if (texres.tin > pPoint[vert].color[3]) {
1455                         copy_v3_v3(pPoint[vert].color, &texres.tr);
1456                         pPoint[vert].color[3] = texres.tin;
1457                 }
1458         }
1459 }
1460
1461 static void dynamic_paint_set_init_color_tex_to_imseq_cb(
1462         void *__restrict userdata,
1463         const int i,
1464         const ParallelRangeTLS *__restrict UNUSED(tls))
1465 {
1466         const DynamicPaintSetInitColorData *data = userdata;
1467
1468         const PaintSurfaceData *sData = data->surface->data;
1469         PaintPoint *pPoint = (PaintPoint *)sData->type_data;
1470
1471         const MLoopTri *mlooptri = data->mlooptri;
1472         const MLoopUV *mloopuv = data->mloopuv;
1473         Tex *tex = data->surface->init_texture;
1474         ImgSeqFormatData *f_data = (ImgSeqFormatData *)sData->format_data;
1475         const int samples = (data->surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
1476
1477         const bool scene_color_manage = data->scene_color_manage;
1478
1479         float uv[9] = {0.0f};
1480         float uv_final[3] = {0.0f};
1481
1482         TexResult texres = {0};
1483
1484         /* collect all uvs */
1485         for (int j = 3; j--;) {
1486                 copy_v2_v2(&uv[j * 3], mloopuv[mlooptri[f_data->uv_p[i].tri_index].tri[j]].uv);
1487         }
1488
1489         /* interpolate final uv pos */
1490         interp_v3_v3v3v3(uv_final, &uv[0], &uv[3], &uv[6], f_data->barycentricWeights[i * samples].v);
1491         /* remap to [-1.0, 1.0] */
1492         uv_final[0] = uv_final[0] * 2.0f - 1.0f;
1493         uv_final[1] = uv_final[1] * 2.0f - 1.0f;
1494
1495         multitex_ext_safe(tex, uv_final, &texres, NULL, scene_color_manage, false);
1496
1497         /* apply color */
1498         copy_v3_v3(pPoint[i].color, &texres.tr);
1499         pPoint[i].color[3] = texres.tin;
1500 }
1501
1502 static void dynamic_paint_set_init_color_vcol_to_imseq_cb(
1503         void *__restrict userdata,
1504         const int i,
1505         const ParallelRangeTLS *__restrict UNUSED(tls))
1506 {
1507         const DynamicPaintSetInitColorData *data = userdata;
1508
1509         const PaintSurfaceData *sData = data->surface->data;
1510         PaintPoint *pPoint = (PaintPoint *)sData->type_data;
1511
1512         const MLoopTri *mlooptri = data->mlooptri;
1513         const MLoopCol *mloopcol = data->mloopcol;
1514         ImgSeqFormatData *f_data = (ImgSeqFormatData *)sData->format_data;
1515         const int samples = (data->surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
1516
1517         const int tri_idx = f_data->uv_p[i].tri_index;
1518         float colors[3][4];
1519         float final_color[4];
1520
1521         /* collect color values */
1522         for (int j = 3; j--;) {
1523                 rgba_uchar_to_float(colors[j], (const unsigned char *)&mloopcol[mlooptri[tri_idx].tri[j]].r);
1524         }
1525
1526         /* interpolate final color */
1527         interp_v4_v4v4v4(final_color, UNPACK3(colors), f_data->barycentricWeights[i * samples].v);
1528
1529         copy_v4_v4(pPoint[i].color, final_color);
1530 }
1531
1532 static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface *surface)
1533 {
1534         PaintSurfaceData *sData = surface->data;
1535         PaintPoint *pPoint = (PaintPoint *)sData->type_data;
1536         Mesh *mesh = surface->canvas->mesh;
1537         int i;
1538         const bool scene_color_manage = BKE_scene_check_color_management_enabled(scene);
1539
1540         if (surface->type != MOD_DPAINT_SURFACE_T_PAINT)
1541                 return;
1542
1543         if (surface->init_color_type == MOD_DPAINT_INITIAL_NONE)
1544                 return;
1545
1546         /* Single color */
1547         if (surface->init_color_type == MOD_DPAINT_INITIAL_COLOR) {
1548                 /* apply color to every surface point */
1549                 for (i = 0; i < sData->total_points; i++) {
1550                         copy_v4_v4(pPoint[i].color, surface->init_color);
1551                 }
1552         }
1553         /* UV mapped texture */
1554         else if (surface->init_color_type == MOD_DPAINT_INITIAL_TEXTURE) {
1555                 Tex *tex = surface->init_texture;
1556
1557                 const MLoop *mloop = mesh->mloop;
1558                 const MLoopTri *mlooptri = BKE_mesh_runtime_looptri_ensure(mesh);
1559                 const int tottri = BKE_mesh_runtime_looptri_len(mesh);
1560                 const MLoopUV *mloopuv = NULL;
1561
1562                 char uvname[MAX_CUSTOMDATA_LAYER_NAME];
1563
1564                 if (!tex)
1565                         return;
1566
1567                 /* get uv map */
1568                 CustomData_validate_layer_name(&mesh->ldata, CD_MLOOPUV, surface->init_layername, uvname);
1569                 mloopuv = CustomData_get_layer_named(&mesh->ldata, CD_MLOOPUV, uvname);
1570                 if (!mloopuv)
1571                         return;
1572
1573                 /* for vertex surface loop through tfaces and find uv color
1574                  * that provides highest alpha */
1575                 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1576                         struct ImagePool *pool = BKE_image_pool_new();
1577
1578                         DynamicPaintSetInitColorData data = {
1579                             .surface = surface,
1580                             .mloop = mloop, .mlooptri = mlooptri, .mloopuv = mloopuv, .pool = pool,
1581                             .scene_color_manage = scene_color_manage,
1582                         };
1583                         ParallelRangeSettings settings;
1584                         BLI_parallel_range_settings_defaults(&settings);
1585                         settings.use_threading = (tottri > 1000);
1586                         BLI_task_parallel_range(0, tottri,
1587                                                 &data,
1588                                                 dynamic_paint_set_init_color_tex_to_vcol_cb,
1589                                                 &settings);
1590                         BKE_image_pool_free(pool);
1591                 }
1592                 else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1593                         DynamicPaintSetInitColorData data = {
1594                             .surface = surface,
1595                             .mlooptri = mlooptri, .mloopuv = mloopuv,
1596                             .scene_color_manage = scene_color_manage,
1597                         };
1598                         ParallelRangeSettings settings;
1599                         BLI_parallel_range_settings_defaults(&settings);
1600                         settings.use_threading = (sData->total_points > 1000);
1601                         BLI_task_parallel_range(0, sData->total_points,
1602                                                 &data,
1603                                                 dynamic_paint_set_init_color_tex_to_imseq_cb,
1604                                                 &settings);
1605                 }
1606         }
1607         /* vertex color layer */
1608         else if (surface->init_color_type == MOD_DPAINT_INITIAL_VERTEXCOLOR) {
1609
1610                 /* for vertex surface, just copy colors from mcol */
1611                 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1612                         const MLoop *mloop = mesh->mloop;
1613                         const int totloop = mesh->totloop;
1614                         const MLoopCol *col = CustomData_get_layer_named(&mesh->ldata, CD_MLOOPCOL, surface->init_layername);
1615                         if (!col)
1616                                 return;
1617
1618                         for (i = 0; i < totloop; i++) {
1619                                 rgba_uchar_to_float(pPoint[mloop[i].v].color, (const unsigned char *)&col[mloop[i].v].r);
1620                         }
1621                 }
1622                 else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1623                         const MLoopTri *mlooptri = BKE_mesh_runtime_looptri_ensure(mesh);
1624                         MLoopCol *col = CustomData_get_layer_named(&mesh->ldata, CD_MLOOPCOL, surface->init_layername);
1625                         if (!col)
1626                                 return;
1627
1628                         DynamicPaintSetInitColorData data = {
1629                             .surface = surface,
1630                             .mlooptri = mlooptri, .mloopcol = col,
1631                         };
1632                         ParallelRangeSettings settings;
1633                         BLI_parallel_range_settings_defaults(&settings);
1634                         settings.use_threading = (sData->total_points > 1000);
1635                         BLI_task_parallel_range(0, sData->total_points,
1636                                                 &data,
1637                                                 dynamic_paint_set_init_color_vcol_to_imseq_cb,
1638                                                 &settings);
1639                 }
1640         }
1641 }
1642
1643 /* clears surface data back to zero */
1644 void dynamicPaint_clearSurface(const Scene *scene, DynamicPaintSurface *surface)
1645 {
1646         PaintSurfaceData *sData = surface->data;
1647         if (sData && sData->type_data) {
1648                 unsigned int data_size;
1649
1650                 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT)
1651                         data_size = sizeof(PaintPoint);
1652                 else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE)
1653                         data_size = sizeof(PaintWavePoint);
1654                 else
1655                         data_size = sizeof(float);
1656
1657                 memset(sData->type_data, 0, data_size * sData->total_points);
1658
1659                 /* set initial color */
1660                 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT)
1661                         dynamicPaint_setInitialColor(scene, surface);
1662
1663                 if (sData->bData)
1664                         sData->bData->clear = 1;
1665         }
1666 }
1667
1668 /* completely (re)initializes surface (only for point cache types)*/
1669 bool dynamicPaint_resetSurface(const Scene *scene, DynamicPaintSurface *surface)
1670 {
1671         int numOfPoints = dynamicPaint_surfaceNumOfPoints(surface);
1672         /* free existing data */
1673         if (surface->data)
1674                 dynamicPaint_freeSurfaceData(surface);
1675
1676         /* don't reallocate for image sequence types. they get handled only on bake */
1677         if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ)
1678                 return true;
1679         if (numOfPoints < 1)
1680                 return false;
1681
1682         /* allocate memory */
1683         surface->data = MEM_callocN(sizeof(PaintSurfaceData), "PaintSurfaceData");
1684         if (!surface->data)
1685                 return false;
1686
1687         /* allocate data depending on surface type and format */
1688         surface->data->total_points = numOfPoints;
1689         dynamicPaint_allocateSurfaceType(surface);
1690         dynamicPaint_initAdjacencyData(surface, false);
1691
1692         /* set initial color */
1693         if (surface->type == MOD_DPAINT_SURFACE_T_PAINT)
1694                 dynamicPaint_setInitialColor(scene, surface);
1695
1696         return true;
1697 }
1698
1699 /* make sure allocated surface size matches current requirements */
1700 static bool dynamicPaint_checkSurfaceData(const Scene *scene, DynamicPaintSurface *surface)
1701 {
1702         if (!surface->data || ((dynamicPaint_surfaceNumOfPoints(surface) != surface->data->total_points))) {
1703                 return dynamicPaint_resetSurface(scene, surface);
1704         }
1705         return true;
1706 }
1707
1708
1709 /***************************** Modifier processing ******************************/
1710
1711 typedef struct DynamicPaintModifierApplyData {
1712         const DynamicPaintSurface *surface;
1713         Object *ob;
1714
1715         MVert *mvert;
1716         const MLoop *mloop;
1717         const MPoly *mpoly;
1718
1719         float (*fcolor)[4];
1720         MLoopCol *mloopcol;
1721         MLoopCol *mloopcol_wet;
1722         MLoopCol *mloopcol_preview;
1723 } DynamicPaintModifierApplyData;
1724
1725 static void dynamic_paint_apply_surface_displace_cb(
1726         void *__restrict userdata,
1727         const int i,
1728         const ParallelRangeTLS *__restrict UNUSED(tls))
1729 {
1730         const DynamicPaintModifierApplyData *data = userdata;
1731
1732         const DynamicPaintSurface *surface = data->surface;
1733         MVert *mvert = data->mvert;
1734
1735         float normal[3];
1736         const float *value = (float *)surface->data->type_data;
1737         const float val = value[i] * surface->disp_factor;
1738
1739         normal_short_to_float_v3(normal, mvert[i].no);
1740
1741         /* same as 'mvert[i].co[0] -= normal[0] * val' etc. */
1742         madd_v3_v3fl(mvert[i].co, normal, -val);
1743 }
1744
1745 /* apply displacing vertex surface to the derived mesh */
1746 static void dynamicPaint_applySurfaceDisplace(DynamicPaintSurface *surface, Mesh *result)
1747 {
1748         PaintSurfaceData *sData = surface->data;
1749
1750         if (!sData || surface->format != MOD_DPAINT_SURFACE_F_VERTEX)
1751                 return;
1752
1753         /* displace paint */
1754         if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
1755                 MVert *mvert = result->mvert;
1756
1757                 DynamicPaintModifierApplyData data = { .surface = surface, .mvert = mvert, };
1758                 ParallelRangeSettings settings;
1759                 BLI_parallel_range_settings_defaults(&settings);
1760                 settings.use_threading = (sData->total_points > 10000);
1761                 BLI_task_parallel_range(0, sData->total_points,
1762                                         &data,
1763                                         dynamic_paint_apply_surface_displace_cb,
1764                                         &settings);
1765         }
1766 }
1767
1768 static void dynamic_paint_apply_surface_vpaint_blend_cb(
1769         void *__restrict userdata,
1770         const int i,
1771         const ParallelRangeTLS *__restrict UNUSED(tls))
1772 {
1773         const DynamicPaintModifierApplyData *data = userdata;
1774
1775         PaintPoint *pPoint = (PaintPoint *)data->surface->data->type_data;
1776         float (*fcolor)[4] = data->fcolor;
1777
1778         /* blend dry and wet layer */
1779         blendColors(pPoint[i].color, pPoint[i].color[3], pPoint[i].e_color, pPoint[i].e_color[3], fcolor[i]);
1780 }
1781
1782 static void dynamic_paint_apply_surface_vpaint_cb(
1783         void *__restrict userdata,
1784         const int p_index,
1785         const ParallelRangeTLS *__restrict UNUSED(tls))
1786 {
1787         const DynamicPaintModifierApplyData *data = userdata;
1788         Object *ob = data->ob;
1789
1790         const MLoop *mloop = data->mloop;
1791         const MPoly *mpoly = data->mpoly;
1792
1793         const DynamicPaintSurface *surface = data->surface;
1794         PaintPoint *pPoint = (PaintPoint *)surface->data->type_data;
1795         float (*fcolor)[4] = data->fcolor;
1796
1797         MLoopCol *mloopcol = data->mloopcol;
1798         MLoopCol *mloopcol_wet = data->mloopcol_wet;
1799         MLoopCol *mloopcol_preview = data->mloopcol_preview;
1800
1801         const Material *material = mloopcol_preview ?
1802                                        give_current_material(ob, mpoly[p_index].mat_nr + 1) : NULL;
1803
1804         for (int j = 0; j < mpoly[p_index].totloop; j++) {
1805                 const int l_index = mpoly[p_index].loopstart + j;
1806                 const int v_index = mloop[l_index].v;
1807
1808                 /* save layer data to output layer */
1809                 /* apply color */
1810                 if (mloopcol) {
1811                         rgba_float_to_uchar((unsigned char *)&mloopcol[l_index].r, fcolor[v_index]);
1812                 }
1813                 /* apply wetness */
1814                 if (mloopcol_wet) {
1815                         const char c = unit_float_to_uchar_clamp(pPoint[v_index].wetness);
1816                         mloopcol_wet[l_index].r = c;
1817                         mloopcol_wet[l_index].g = c;
1818                         mloopcol_wet[l_index].b = c;
1819                         mloopcol_wet[l_index].a = 255;
1820                 }
1821
1822                 /* viewport preview */
1823                 if (mloopcol_preview) {
1824                         if (surface->preview_id == MOD_DPAINT_SURFACE_PREV_PAINT) {
1825                                 float c[3];
1826
1827                                 /* Apply material color as base vertex color for preview */
1828                                 mloopcol_preview[l_index].a = 255;
1829                                 if (material) {
1830                                         c[0] = material->r;
1831                                         c[1] = material->g;
1832                                         c[2] = material->b;
1833                                 }
1834                                 else { /* default gray */
1835                                         c[0] = 0.65f;
1836                                         c[1] = 0.65f;
1837                                         c[2] = 0.65f;
1838                                 }
1839                                 /* mix surface color */
1840                                 interp_v3_v3v3(c, c, fcolor[v_index], fcolor[v_index][3]);
1841
1842                                 rgb_float_to_uchar((unsigned char *)&mloopcol_preview[l_index].r, c);
1843                         }
1844                         else {
1845                                 const char c = unit_float_to_uchar_clamp(pPoint[v_index].wetness);
1846                                 mloopcol_preview[l_index].r = c;
1847                                 mloopcol_preview[l_index].g = c;
1848                                 mloopcol_preview[l_index].b = c;
1849                                 mloopcol_preview[l_index].a = 255;
1850                         }
1851                 }
1852         }
1853 }
1854
1855 static void dynamic_paint_apply_surface_wave_cb(
1856         void *__restrict userdata,
1857         const int i,
1858         const ParallelRangeTLS *__restrict UNUSED(tls))
1859 {
1860         const DynamicPaintModifierApplyData *data = userdata;
1861
1862         PaintWavePoint *wPoint = (PaintWavePoint *)data->surface->data->type_data;
1863         MVert *mvert = data->mvert;
1864         float normal[3];
1865
1866         normal_short_to_float_v3(normal, mvert[i].no);
1867         madd_v3_v3fl(mvert[i].co, normal, wPoint[i].height);
1868 }
1869
1870 /*
1871  * Apply canvas data to the object derived mesh
1872  */
1873 static Mesh *dynamicPaint_Modifier_apply(
1874         DynamicPaintModifierData *pmd, Object *ob, Mesh *mesh)
1875 {
1876         Mesh *result = BKE_mesh_copy_for_eval(mesh, false);
1877
1878         if (pmd->canvas && !(pmd->canvas->flags & MOD_DPAINT_BAKING)) {
1879
1880                 DynamicPaintSurface *surface;
1881                 bool update_normals = false;
1882
1883                 /* loop through surfaces */
1884                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1885                         PaintSurfaceData *sData = surface->data;
1886
1887                         if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ && sData) {
1888                                 if (!(surface->flags & MOD_DPAINT_ACTIVE))
1889                                         continue;
1890
1891                                 /* process vertex surface previews */
1892                                 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1893
1894                                         /* vertex color paint */
1895                                         if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
1896                                                 MLoop *mloop = result->mloop;
1897                                                 const int totloop = result->totloop;
1898                                                 MPoly *mpoly = result->mpoly;
1899                                                 const int totpoly = result->totpoly;
1900
1901                                                 /* paint is stored on dry and wet layers, so mix final color first */
1902                                                 float (*fcolor)[4] = MEM_callocN(sizeof(*fcolor) * sData->total_points, "Temp paint color");
1903
1904                                                 DynamicPaintModifierApplyData data = { .surface = surface, .fcolor = fcolor, };
1905                                                 {
1906                                                         ParallelRangeSettings settings;
1907                                                         BLI_parallel_range_settings_defaults(&settings);
1908                                                         settings.use_threading = (sData->total_points > 1000);
1909                                                         BLI_task_parallel_range(
1910                                                                 0, sData->total_points,
1911                                                                 &data,
1912                                                                 dynamic_paint_apply_surface_vpaint_blend_cb,
1913                                                                 &settings);
1914                                                 }
1915
1916                                                 /* paint layer */
1917                                                 MLoopCol *mloopcol = CustomData_get_layer_named(&result->ldata, CD_MLOOPCOL, surface->output_name);
1918                                                 /* if output layer is lost from a constructive modifier, re-add it */
1919                                                 if (!mloopcol && dynamicPaint_outputLayerExists(surface, ob, 0)) {
1920                                                         mloopcol = CustomData_add_layer_named(
1921                                                                 &result->ldata, CD_MLOOPCOL, CD_CALLOC, NULL, totloop, surface->output_name);
1922                                                 }
1923
1924                                                 /* wet layer */
1925                                                 MLoopCol *mloopcol_wet = CustomData_get_layer_named(&result->ldata, CD_MLOOPCOL, surface->output_name2);
1926                                                 /* if output layer is lost from a constructive modifier, re-add it */
1927                                                 if (!mloopcol_wet && dynamicPaint_outputLayerExists(surface, ob, 1)) {
1928                                                         mloopcol_wet = CustomData_add_layer_named(
1929                                                                 &result->ldata, CD_MLOOPCOL, CD_CALLOC, NULL, totloop, surface->output_name2);
1930                                                 }
1931
1932                                                 /* Save preview results to weight layer to be able to share same drawing methods */
1933                                                 MLoopCol *mloopcol_preview = NULL;
1934                                                 if (surface->flags & MOD_DPAINT_PREVIEW) {
1935                                                         mloopcol_preview = CustomData_get_layer(&result->ldata, CD_PREVIEW_MLOOPCOL);
1936                                                         if (!mloopcol_preview) {
1937                                                                 mloopcol_preview = CustomData_add_layer(
1938                                                                         &result->ldata, CD_PREVIEW_MLOOPCOL, CD_CALLOC, NULL, totloop);
1939                                                         }
1940                                                 }
1941
1942                                                 data.ob = ob;
1943                                                 data.mloop = mloop;
1944                                                 data.mpoly = mpoly;
1945                                                 data.mloopcol = mloopcol;
1946                                                 data.mloopcol_wet = mloopcol_wet;
1947                                                 data.mloopcol_preview = mloopcol_preview;
1948
1949                                                 {
1950                                                         ParallelRangeSettings settings;
1951                                                         BLI_parallel_range_settings_defaults(&settings);
1952                                                         settings.use_threading = (totpoly > 1000);
1953                                                         BLI_task_parallel_range(
1954                                                                 0, totpoly,
1955                                                                 &data,
1956                                                                 dynamic_paint_apply_surface_vpaint_cb,
1957                                                                 &settings);
1958                                                 }
1959
1960                                                 MEM_freeN(fcolor);
1961
1962                                                 /* Mark tessellated CD layers as dirty. */
1963                                                 //result->dirty |= DM_DIRTY_TESS_CDLAYERS;
1964                                         }
1965                                         /* vertex group paint */
1966                                         else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) {
1967                                                 int defgrp_index = defgroup_name_index(ob, surface->output_name);
1968                                                 MDeformVert *dvert = CustomData_get_layer(&result->vdata, CD_MDEFORMVERT);
1969                                                 float *weight = (float *)sData->type_data;
1970
1971                                                 /* viewport preview */
1972                                                 if (surface->flags & MOD_DPAINT_PREVIEW) {
1973                                                         /* Save preview results to weight layer to be
1974                                                          * able to share same drawing methods.
1975                                                          * Note this func also sets DM_DIRTY_TESS_CDLAYERS flag! */
1976                                                         //TODO port this function
1977                                                         //DM_update_weight_mcol(ob, result, 0, weight, 0, NULL);
1978                                                 }
1979
1980                                                 /* apply weights into a vertex group, if doesn't exists add a new layer */
1981                                                 if (defgrp_index != -1 && !dvert && (surface->output_name[0] != '\0')) {
1982                                                         dvert = CustomData_add_layer(&result->vdata, CD_MDEFORMVERT, CD_CALLOC,
1983                                                                                      NULL, sData->total_points);
1984                                                 }
1985                                                 if (defgrp_index != -1 && dvert) {
1986                                                         int i;
1987                                                         for (i = 0; i < sData->total_points; i++) {
1988                                                                 MDeformVert *dv = &dvert[i];
1989                                                                 MDeformWeight *def_weight = defvert_find_index(dv, defgrp_index);
1990
1991                                                                 /* skip if weight value is 0 and no existing weight is found */
1992                                                                 if ((def_weight != NULL) || (weight[i] != 0.0f)) {
1993                                                                         /* if not found, add a weight for it */
1994                                                                         if (def_weight == NULL) {
1995                                                                                 def_weight = defvert_verify_index(dv, defgrp_index);
1996                                                                         }
1997
1998                                                                         /* set weight value */
1999                                                                         def_weight->weight = weight[i];
2000                                                                 }
2001                                                         }
2002                                                 }
2003                                         }
2004                                         /* wave simulation */
2005                                         else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
2006                                                 MVert *mvert = result->mvert;
2007
2008                                                 DynamicPaintModifierApplyData data = { .surface = surface, .mvert = mvert, };
2009                                                 ParallelRangeSettings settings;
2010                                                 BLI_parallel_range_settings_defaults(&settings);
2011                                                 settings.use_threading = (sData->total_points > 1000);
2012                                                 BLI_task_parallel_range(
2013                                                         0, sData->total_points,
2014                                                         &data,
2015                                                         dynamic_paint_apply_surface_wave_cb,
2016                                                         &settings);
2017                                                 update_normals = true;
2018                                         }
2019
2020                                         /* displace */
2021                                         if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
2022                                                 dynamicPaint_applySurfaceDisplace(surface, result);
2023                                                 update_normals = true;
2024                                         }
2025                                 }
2026                         }
2027                 }
2028
2029                 if (update_normals) {
2030                         //result->dirty |= DM_DIRTY_NORMALS;
2031                 }
2032         }
2033         /* make a copy of mesh to use as brush data */
2034         if (pmd->brush) {
2035                 if (pmd->brush->mesh) {
2036                         BKE_id_free(NULL, pmd->brush->mesh);
2037                 }
2038                 pmd->brush->mesh = BKE_mesh_copy_for_eval(result, false);
2039         }
2040
2041         return result;
2042 }
2043
2044 /* update cache frame range */
2045 void dynamicPaint_cacheUpdateFrames(DynamicPaintSurface *surface)
2046 {
2047         if (surface->pointcache) {
2048                 surface->pointcache->startframe = surface->start_frame;
2049                 surface->pointcache->endframe = surface->end_frame;
2050         }
2051 }
2052
2053 static void canvas_copyMesh(DynamicPaintCanvasSettings *canvas, Mesh *mesh)
2054 {
2055         if (canvas->mesh) {
2056                 BKE_id_free(NULL, canvas->mesh);
2057         }
2058
2059         canvas->mesh = BKE_mesh_copy_for_eval(mesh, false);
2060 }
2061
2062 /*
2063  * Updates derived mesh copy and processes dynamic paint step / caches.
2064  */
2065 static void dynamicPaint_frameUpdate(
2066         DynamicPaintModifierData *pmd, struct Depsgraph *depsgraph, Scene *scene,
2067         Object *ob, Mesh *mesh)
2068 {
2069         if (pmd->canvas) {
2070                 DynamicPaintCanvasSettings *canvas = pmd->canvas;
2071                 DynamicPaintSurface *surface = canvas->surfaces.first;
2072
2073                 /* update derived mesh copy */
2074                 canvas_copyMesh(canvas, mesh);
2075
2076                 /* in case image sequence baking, stop here */
2077                 if (canvas->flags & MOD_DPAINT_BAKING)
2078                         return;
2079
2080                 /* loop through surfaces */
2081                 for (; surface; surface = surface->next) {
2082                         int current_frame = (int)scene->r.cfra;
2083                         bool no_surface_data;
2084
2085                         /* free bake data if not required anymore */
2086                         surface_freeUnusedData(surface);
2087
2088                         /* image sequences are handled by bake operator */
2089                         if ((surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) || !(surface->flags & MOD_DPAINT_ACTIVE))
2090                                 continue;
2091
2092                         /* make sure surface is valid */
2093                         no_surface_data = surface->data == NULL;
2094                         if (!dynamicPaint_checkSurfaceData(scene, surface))
2095                                 continue;
2096
2097                         /* limit frame range */
2098                         CLAMP(current_frame, surface->start_frame, surface->end_frame);
2099
2100                         if (no_surface_data || current_frame != surface->current_frame ||
2101                             (int)scene->r.cfra == surface->start_frame)
2102                         {
2103                                 PointCache *cache = surface->pointcache;
2104                                 PTCacheID pid;
2105                                 surface->current_frame = current_frame;
2106
2107                                 /* read point cache */
2108                                 BKE_ptcache_id_from_dynamicpaint(&pid, ob, surface);
2109                                 pid.cache->startframe = surface->start_frame;
2110                                 pid.cache->endframe = surface->end_frame;
2111                                 BKE_ptcache_id_time(&pid, scene, (float)scene->r.cfra, NULL, NULL, NULL);
2112
2113                                 /* reset non-baked cache at first frame */
2114                                 if ((int)scene->r.cfra == surface->start_frame && !(cache->flag & PTCACHE_BAKED)) {
2115                                         cache->flag |= PTCACHE_REDO_NEEDED;
2116                                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
2117                                         cache->flag &= ~PTCACHE_REDO_NEEDED;
2118                                 }
2119
2120                                 /* try to read from cache */
2121                                 bool can_simulate = ((int)scene->r.cfra == current_frame) && !(cache->flag & PTCACHE_BAKED);
2122
2123                                 if (BKE_ptcache_read(&pid, (float)scene->r.cfra, can_simulate)) {
2124                                         BKE_ptcache_validate(cache, (int)scene->r.cfra);
2125                                 }
2126                                 /* if read failed and we're on surface range do recalculate */
2127                                 else if (can_simulate) {
2128                                         /* calculate surface frame */
2129                                         canvas->flags |= MOD_DPAINT_BAKING;
2130                                         dynamicPaint_calculateFrame(surface, depsgraph, scene, ob, current_frame);
2131                                         canvas->flags &= ~MOD_DPAINT_BAKING;
2132
2133                                         /* restore canvas mesh if required */
2134                                         if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE &&
2135                                             surface->flags & MOD_DPAINT_DISP_INCREMENTAL && surface->next)
2136                                         {
2137                                                 canvas_copyMesh(canvas, mesh);
2138                                         }
2139
2140                                         BKE_ptcache_validate(cache, surface->current_frame);
2141                                         BKE_ptcache_write(&pid, surface->current_frame);
2142                                 }
2143                         }
2144                 }
2145         }
2146 }
2147
2148 /* Modifier call. Processes dynamic paint modifier step. */
2149 Mesh *dynamicPaint_Modifier_do(
2150         DynamicPaintModifierData *pmd, struct Depsgraph *depsgraph, Scene *scene,
2151         Object *ob, Mesh *mesh)
2152 {
2153         if (pmd->canvas) {
2154                 Mesh *ret;
2155
2156                 /* Update canvas data for a new frame */
2157                 dynamicPaint_frameUpdate(pmd, depsgraph, scene, ob, mesh);
2158
2159                 /* Return output mesh */
2160                 ret = dynamicPaint_Modifier_apply(pmd, ob, mesh);
2161
2162                 return ret;
2163         }
2164         else {
2165                 /* Update canvas data for a new frame */
2166                 dynamicPaint_frameUpdate(pmd, depsgraph, scene, ob, mesh);
2167
2168                 /* Return output mesh */
2169                 return dynamicPaint_Modifier_apply(pmd, ob, mesh);
2170         }
2171 }
2172
2173
2174 /***************************** Image Sequence / UV Image Surface Calls ******************************/
2175
2176 /*
2177  * Create a surface for uv image sequence format
2178  */
2179 #define JITTER_SAMPLES { \
2180         0.0f, 0.0f, \
2181         -0.2f, -0.4f, \
2182         0.2f, 0.4f, \
2183         0.4f, -0.2f, \
2184         -0.4f, 0.3f, \
2185 }
2186
2187 typedef struct DynamicPaintCreateUVSurfaceData {
2188         const DynamicPaintSurface *surface;
2189
2190         PaintUVPoint *tempPoints;
2191         Vec3f *tempWeights;
2192
2193         const MLoopTri *mlooptri;
2194         const MLoopUV *mloopuv;
2195         const MLoop *mloop;
2196         const int tottri;
2197
2198         const Bounds2D *faceBB;
2199         uint32_t *active_points;
2200 } DynamicPaintCreateUVSurfaceData;
2201
2202 static void dynamic_paint_create_uv_surface_direct_cb(
2203         void *__restrict userdata,
2204         const int ty,
2205         const ParallelRangeTLS *__restrict UNUSED(tls))
2206 {
2207         const DynamicPaintCreateUVSurfaceData *data = userdata;
2208
2209         const DynamicPaintSurface *surface = data->surface;
2210         PaintUVPoint *tempPoints = data->tempPoints;
2211         Vec3f *tempWeights = data->tempWeights;
2212
2213         const MLoopTri *mlooptri = data->mlooptri;
2214         const MLoopUV *mloopuv = data->mloopuv;
2215         const MLoop *mloop = data->mloop;
2216         const int tottri = data->tottri;
2217
2218         const Bounds2D *faceBB = data->faceBB;
2219
2220         const float jitter5sample[10] = JITTER_SAMPLES;
2221         const int aa_samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
2222         const int w = surface->image_resolution;
2223         const int h = w;
2224
2225         for (int tx = 0; tx < w; tx++) {
2226                 const int index = tx + w * ty;
2227                 PaintUVPoint *tPoint = &tempPoints[index];
2228                 float point[5][2];
2229
2230                 /* Init per pixel settings */
2231                 tPoint->tri_index = -1;
2232                 tPoint->neighbour_pixel = -1;
2233                 tPoint->pixel_index = index;
2234
2235                 /* Actual pixel center, used when collision is found */
2236                 point[0][0] = ((float)tx + 0.5f) / w;
2237                 point[0][1] = ((float)ty + 0.5f) / h;
2238
2239                 /*
2240                  * A pixel middle sample isn't enough to find very narrow polygons
2241                  * So using 4 samples of each corner too
2242                  */
2243                 point[1][0] = ((float)tx) / w;
2244                 point[1][1] = ((float)ty) / h;
2245
2246                 point[2][0] = ((float)tx + 1) / w;
2247                 point[2][1] = ((float)ty) / h;
2248
2249                 point[3][0] = ((float)tx) / w;
2250                 point[3][1] = ((float)ty + 1) / h;
2251
2252                 point[4][0] = ((float)tx + 1) / w;
2253                 point[4][1] = ((float)ty + 1) / h;
2254
2255
2256                 /* Loop through samples, starting from middle point */
2257                 for (int sample = 0; sample < 5; sample++) {
2258                         /* Loop through every face in the mesh */
2259                         /* XXX TODO This is *horrible* with big meshes, should use a 2D BVHTree over UV tris here! */
2260                         for (int i = 0; i < tottri; i++) {
2261                                 /* Check uv bb */
2262                                 if ((faceBB[i].min[0] > point[sample][0]) ||
2263                                     (faceBB[i].min[1] > point[sample][1]) ||
2264                                     (faceBB[i].max[0] < point[sample][0]) ||
2265                                     (faceBB[i].max[1] < point[sample][1]))
2266                                 {
2267                                         continue;
2268                                 }
2269
2270                                 const float *uv1 = mloopuv[mlooptri[i].tri[0]].uv;
2271                                 const float *uv2 = mloopuv[mlooptri[i].tri[1]].uv;
2272                                 const float *uv3 = mloopuv[mlooptri[i].tri[2]].uv;
2273
2274                                 /* If point is inside the face */
2275                                 if (isect_point_tri_v2(point[sample], uv1, uv2, uv3) != 0) {
2276                                         float uv[2];
2277
2278                                         /* Add b-weights per anti-aliasing sample */
2279                                         for (int j = 0; j < aa_samples; j++) {
2280                                                 uv[0] = point[0][0] + jitter5sample[j * 2] / w;
2281                                                 uv[1] = point[0][1] + jitter5sample[j * 2 + 1] / h;
2282
2283                                                 barycentric_weights_v2(uv1, uv2, uv3, uv, tempWeights[index * aa_samples + j].v);
2284                                         }
2285
2286                                         /* Set surface point face values */
2287                                         tPoint->tri_index = i;
2288
2289                                         /* save vertex indexes */
2290                                         tPoint->v1 = mloop[mlooptri[i].tri[0]].v;
2291                                         tPoint->v2 = mloop[mlooptri[i].tri[1]].v;
2292                                         tPoint->v3 = mloop[mlooptri[i].tri[2]].v;
2293
2294                                         sample = 5; /* make sure we exit sample loop as well */
2295                                         break;
2296                                 }
2297                         }
2298                 }
2299         }
2300 }
2301
2302 static void dynamic_paint_create_uv_surface_neighbor_cb(
2303         void *__restrict userdata,
2304         const int ty,
2305         const ParallelRangeTLS *__restrict UNUSED(tls))
2306 {
2307         const DynamicPaintCreateUVSurfaceData *data = userdata;
2308
2309         const DynamicPaintSurface *surface = data->surface;
2310         PaintUVPoint *tempPoints = data->tempPoints;
2311         Vec3f *tempWeights = data->tempWeights;
2312
2313         const MLoopTri *mlooptri = data->mlooptri;
2314         const MLoopUV *mloopuv = data->mloopuv;
2315         const MLoop *mloop = data->mloop;
2316
2317         uint32_t *active_points = data->active_points;
2318
2319         const float jitter5sample[10] = JITTER_SAMPLES;
2320         const int aa_samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
2321         const int w = surface->image_resolution;
2322         const int h = w;
2323
2324         for (int tx = 0; tx < w; tx++) {
2325                 const int index = tx + w * ty;
2326                 PaintUVPoint *tPoint = &tempPoints[index];
2327
2328                 /* If point isn't on canvas mesh */
2329                 if (tPoint->tri_index == -1) {
2330                         float point[2];
2331
2332                         /* get loop area */
2333                         const int u_min = (tx > 0) ? -1 : 0;
2334                         const int u_max = (tx < (w - 1)) ? 1 : 0;
2335                         const int v_min = (ty > 0) ? -1 : 0;
2336                         const int v_max = (ty < (h - 1)) ? 1 : 0;
2337
2338                         point[0] = ((float)tx + 0.5f) / w;
2339                         point[1] = ((float)ty + 0.5f) / h;
2340
2341                         /* search through defined area for neighbor, checking grid directions first */
2342                         for (int ni = 0; ni < 8; ni++) {
2343                                 int u = neighStraightX[ni];
2344                                 int v = neighStraightY[ni];
2345
2346                                 if (u >= u_min && u <= u_max && v >= v_min && v <= v_max) {
2347                                         /* if not this pixel itself */
2348                                         if (u != 0 || v != 0) {
2349                                                 const int ind = (tx + u) + w * (ty + v);
2350
2351                                                 /* if neighbor has index */
2352                                                 if (tempPoints[ind].neighbour_pixel == -1 && tempPoints[ind].tri_index != -1) {
2353                                                         float uv[2];
2354                                                         const int i = tempPoints[ind].tri_index;
2355                                                         const float *uv1 = mloopuv[mlooptri[i].tri[0]].uv;
2356                                                         const float *uv2 = mloopuv[mlooptri[i].tri[1]].uv;
2357                                                         const float *uv3 = mloopuv[mlooptri[i].tri[2]].uv;
2358
2359                                                         /* tri index */
2360                                                         /* There is a low possibility of actually having a neighbor point which tri is
2361                                                          * already set from another neighbor in a separate thread here.
2362                                                          * Checking for both tri_index and neighbour_pixel above reduces that probability
2363                                                          * but it remains possible.
2364                                                          * That atomic op (and its memory fence) ensures tPoint->neighbour_pixel is set
2365                                                          * to non--1 *before* its tri_index is set (i.e. that it cannot be used a neighbour).
2366                                                          */
2367                                                         tPoint->neighbour_pixel = ind - 1;
2368                                                         atomic_add_and_fetch_uint32(&tPoint->neighbour_pixel, 1);
2369                                                         tPoint->tri_index = i;
2370
2371                                                         /* Now calculate pixel data for this pixel as it was on polygon surface */
2372                                                         /* Add b-weights per anti-aliasing sample */
2373                                                         for (int j = 0; j < aa_samples; j++) {
2374                                                                 uv[0] = point[0] + jitter5sample[j * 2] / w;
2375                                                                 uv[1] = point[1] + jitter5sample[j * 2 + 1] / h;
2376                                                                 barycentric_weights_v2(uv1, uv2, uv3, uv, tempWeights[index * aa_samples + j].v);
2377                                                         }
2378
2379                                                         /* save vertex indexes */
2380                                                         tPoint->v1 = mloop[mlooptri[i].tri[0]].v;
2381                                                         tPoint->v2 = mloop[mlooptri[i].tri[1]].v;
2382                                                         tPoint->v3 = mloop[mlooptri[i].tri[2]].v;
2383
2384                                                         break;
2385                                                 }
2386                                         }
2387                                 }
2388                         }
2389                 }
2390
2391                 /* Increase the final number of active surface points if relevant. */
2392                 if (tPoint->tri_index != -1)
2393                         atomic_add_and_fetch_uint32(active_points, 1);
2394         }
2395 }
2396
2397 #undef JITTER_SAMPLES
2398
2399 static float dist_squared_to_looptri_uv_edges(const MLoopTri *mlooptri, const MLoopUV *mloopuv, int tri_index, const float point[2])
2400 {
2401         float min_distance = FLT_MAX;
2402
2403         for (int i = 0; i < 3; i++) {
2404                 const float dist_squared = dist_squared_to_line_segment_v2(
2405                         point,
2406                         mloopuv[mlooptri[tri_index].tri[(i + 0)]].uv,
2407                         mloopuv[mlooptri[tri_index].tri[(i + 1) % 3]].uv
2408                 );
2409
2410                 if (dist_squared < min_distance)
2411                         min_distance = dist_squared;
2412         }
2413
2414         return min_distance;
2415 }
2416
2417 typedef struct DynamicPaintFindIslandBorderData {
2418         const MeshElemMap *vert_to_looptri_map;
2419         int w, h, px, py;
2420
2421         int best_index;
2422         float best_weight;
2423 } DynamicPaintFindIslandBorderData;
2424
2425 static void dynamic_paint_find_island_border(
2426         const DynamicPaintCreateUVSurfaceData *data, DynamicPaintFindIslandBorderData *bdata,
2427         int tri_index, const float pixel[2], int in_edge, int depth);
2428
2429 /* Tries to find the neighboring pixel in given (uv space) direction.
2430  * Result is used by effect system to move paint on the surface.
2431  *
2432  * px, py : origin pixel x and y
2433  * n_index : lookup direction index (use neighX, neighY to get final index)
2434  */
2435 static int dynamic_paint_find_neighbour_pixel(
2436         const DynamicPaintCreateUVSurfaceData *data, const MeshElemMap *vert_to_looptri_map,
2437         const int w, const int h, const int px, const int py, const int n_index)
2438 {
2439         /* Note: Current method only uses polygon edges to detect neighboring pixels.
2440          *       -> It doesn't always lead to the optimum pixel but is accurate enough
2441          *          and faster/simpler than including possible face tip point links)
2442          */
2443
2444         /* shift position by given n_index */
2445         const int x = px + neighX[n_index];
2446         const int y = py + neighY[n_index];
2447
2448         if (x < 0 || x >= w || y < 0 || y >= h)
2449                 return OUT_OF_TEXTURE;
2450
2451         const PaintUVPoint *tempPoints = data->tempPoints;
2452         const PaintUVPoint *tPoint = &tempPoints[x + w * y];        /* UV neighbor */
2453         const PaintUVPoint *cPoint = &tempPoints[px + w * py];      /* Origin point */
2454
2455         /* Check if shifted point is on same face -> it's a correct neighbor (and if it isn't marked as an "edge pixel") */
2456         if ((tPoint->tri_index == cPoint->tri_index) && (tPoint->neighbour_pixel == -1))
2457                 return (x + w * y);
2458
2459         /* Even if shifted point is on another face
2460          * -> use this point.
2461          *
2462          * !! Replace with "is uv faces linked" check !!
2463          * This should work fine as long as uv island margin is > 1 pixel.
2464          */
2465         if ((tPoint->tri_index != -1) && (tPoint->neighbour_pixel == -1)) {
2466                 return (x + w * y);
2467         }
2468
2469         /* If we get here, the actual neighboring pixel is located on a non-linked uv face,
2470          * and we have to find its "real" position.
2471          *
2472          * Simple neighboring face finding algorithm:
2473          *   - find closest uv edge to shifted pixel and get the another face that shares that edge
2474          *   - find corresponding position of that new face edge in uv space
2475          *
2476          * TODO: Implement something more accurate / optimized?
2477          */
2478         {
2479                 DynamicPaintFindIslandBorderData bdata = {
2480                         .vert_to_looptri_map = vert_to_looptri_map,
2481                         .w = w, .h = h, .px = px, .py = py,
2482                         .best_index = NOT_FOUND, .best_weight = 1.0f,
2483                 };
2484
2485                 float pixel[2];
2486
2487                 pixel[0] = ((float)(px + neighX[n_index]) + 0.5f) / (float)w;
2488                 pixel[1] = ((float)(py + neighY[n_index]) + 0.5f) / (float)h;
2489
2490                 /* Do a small recursive search for the best island edge. */
2491                 dynamic_paint_find_island_border(data, &bdata, cPoint->tri_index, pixel, -1, 5);
2492
2493                 return bdata.best_index;
2494         }
2495 }
2496
2497 static void dynamic_paint_find_island_border(
2498         const DynamicPaintCreateUVSurfaceData *data, DynamicPaintFindIslandBorderData *bdata,
2499         int tri_index, const float pixel[2], int in_edge, int depth)
2500 {
2501         const MLoop *mloop = data->mloop;
2502         const MLoopTri *mlooptri = data->mlooptri;
2503         const MLoopUV *mloopuv = data->mloopuv;
2504
2505         const unsigned int *loop_idx = mlooptri[tri_index].tri;
2506
2507         /* Enumerate all edges of the triangle, rotating the vertex list accordingly. */
2508         for (int edge_idx = 0; edge_idx < 3; edge_idx++) {
2509                 /* but not the edge we have just recursed through */
2510                 if (edge_idx == in_edge)
2511                         continue;
2512
2513                 float uv0[2], uv1[2], uv2[2];
2514
2515                 copy_v2_v2(uv0, mloopuv[loop_idx[(edge_idx + 0)]].uv);
2516                 copy_v2_v2(uv1, mloopuv[loop_idx[(edge_idx + 1) % 3]].uv);
2517                 copy_v2_v2(uv2, mloopuv[loop_idx[(edge_idx + 2) % 3]].uv);
2518
2519                 /* Verify the target point is on the opposite side of the edge from the third triangle
2520                  * vertex, to ensure that we always move closer to the goal point. */
2521                 const float sidep = line_point_side_v2(uv0, uv1, pixel);
2522                 const float side2 = line_point_side_v2(uv0, uv1, uv2);
2523
2524                 if (side2 == 0.0f)
2525                         continue;
2526
2527                 /* Hack: allow all edges of the original triangle */
2528                 const bool correct_side = (in_edge == -1) || (sidep < 0 && side2 > 0) || (sidep > 0 && side2 < 0);
2529
2530                 /* Allow exactly on edge for the non-recursive case */
2531                 if (!correct_side && sidep != 0.0f)
2532                         continue;
2533
2534                 /* Now find another face that is linked to that edge. */
2535                 const int vert0 = mloop[loop_idx[(edge_idx + 0)]].v;
2536                 const int vert1 = mloop[loop_idx[(edge_idx + 1) % 3]].v;
2537
2538                 /* Use a pre-computed vert-to-looptri mapping, speeds up things a lot compared to looping over all loopti. */
2539                 const MeshElemMap *map = &bdata->vert_to_looptri_map[vert0];
2540
2541                 bool found_other = false;
2542                 int target_tri = -1;
2543                 int target_edge = -1;
2544
2545                 float ouv0[2], ouv1[2];
2546
2547                 for (int i = 0; i < map->count && !found_other; i++) {
2548                         const int lt_index = map->indices[i];
2549
2550                         if (lt_index == tri_index)
2551                                 continue;
2552
2553                         const unsigned int *other_loop_idx = mlooptri[lt_index].tri;
2554
2555                         /* Check edges for match, looping in the same order as the outer loop. */
2556                         for (int j = 0; j < 3; j++) {
2557                                 const int overt0 = mloop[other_loop_idx[(j + 0)]].v;
2558                                 const int overt1 = mloop[other_loop_idx[(j + 1) % 3]].v;
2559
2560                                 /* Allow for swapped vertex order */
2561                                 if (overt0 == vert0 && overt1 == vert1) {
2562                                         found_other = true;
2563                                         copy_v2_v2(ouv0, mloopuv[other_loop_idx[(j + 0)]].uv);
2564                                         copy_v2_v2(ouv1, mloopuv[other_loop_idx[(j + 1) % 3]].uv);
2565                                 }
2566                                 else if (overt0 == vert1 && overt1 == vert0) {
2567                                         found_other = true;
2568                                         copy_v2_v2(ouv1, mloopuv[other_loop_idx[(j + 0)]].uv);
2569                                         copy_v2_v2(ouv0, mloopuv[other_loop_idx[(j + 1) % 3]].uv);
2570                                 }
2571
2572                                 if (found_other) {
2573                                         target_tri = lt_index;
2574                                         target_edge = j;
2575                                         break;
2576                                 }
2577                         }
2578                 }
2579
2580                 if (!found_other) {
2581                         if (bdata->best_index < 0)
2582                                 bdata->best_index = ON_MESH_EDGE;
2583
2584                         continue;
2585                 }
2586
2587                 /* If this edge is connected in UV space too, recurse */
2588                 if (equals_v2v2(uv0, ouv0) && equals_v2v2(uv1, ouv1)) {
2589                         if (depth > 0 && correct_side) {
2590                                 dynamic_paint_find_island_border(data, bdata, target_tri, pixel, target_edge, depth - 1);
2591                         }
2592
2593                         continue;
2594                 }
2595
2596                 /* Otherwise try to map to the other side of the edge.
2597                  * First check if there already is a better solution. */
2598                 const float dist_squared = dist_squared_to_line_segment_v2(pixel, uv0, uv1);
2599
2600                 if (bdata->best_index >= 0 && dist_squared >= bdata->best_weight)
2601                         continue;
2602
2603                 /*
2604                  * Find a point that is relatively at same edge position
2605                  * on this other face UV
2606                  */
2607                 float closest_point[2], dir_vec[2], tgt_pixel[2];
2608
2609                 float lambda = closest_to_line_v2(closest_point, pixel, uv0, uv1);
2610                 CLAMP(lambda, 0.0f, 1.0f);
2611
2612                 sub_v2_v2v2(dir_vec, ouv1, ouv0);
2613                 madd_v2_v2v2fl(tgt_pixel, ouv0, dir_vec, lambda);
2614
2615                 int w = bdata->w, h = bdata->h, px = bdata->px, py = bdata->py;
2616
2617                 int final_pixel[2] = { (int)floorf(tgt_pixel[0] * w), (int)floorf(tgt_pixel[1] * h) };
2618
2619                 /* If current pixel uv is outside of texture */
2620                 if (final_pixel[0] < 0 || final_pixel[0] >= w || final_pixel[1] < 0 || final_pixel[1] >= h) {
2621                         if (bdata->best_index == NOT_FOUND)
2622                                 bdata->best_index = OUT_OF_TEXTURE;
2623
2624                         continue;
2625                 }
2626
2627                 const PaintUVPoint *tempPoints = data->tempPoints;
2628                 int final_index = final_pixel[0] + w * final_pixel[1];
2629
2630                 /* If we ended up to our origin point ( mesh has smaller than pixel sized faces) */
2631                 if (final_index == (px + w * py))
2632                         continue;
2633
2634                 /* If final point is an "edge pixel", use it's "real" neighbor instead */
2635                 if (tempPoints[final_index].neighbour_pixel != -1) {
2636                         final_index = tempPoints[final_index].neighbour_pixel;
2637
2638                         /* If we ended up to our origin point */
2639                         if (final_index == (px + w * py))
2640                                 continue;
2641                 }
2642
2643                 /* If found pixel still lies on wrong face ( mesh has smaller than pixel sized faces) */
2644                 if (tempPoints[final_index].tri_index != target_tri) {
2645                         /* Check if it's close enough to likely touch the intended triangle. Any triangle
2646                          * becomes thinner than a pixel at its vertices, so robustness requires some margin. */
2647                         const float final_pt[2] = { ((final_index % w) + 0.5f) / w, ((final_index / w) + 0.5f) / h };
2648                         const float threshold = SQUARE(0.7f) / (w * h);
2649
2650                         if (dist_squared_to_looptri_uv_edges(mlooptri, mloopuv, tempPoints[final_index].tri_index, final_pt) > threshold)
2651                                 continue;
2652                 }
2653
2654                 bdata->best_index = final_index;
2655                 bdata->best_weight = dist_squared;
2656         }
2657 }
2658
2659 static bool dynamicPaint_pointHasNeighbor(PaintAdjData *ed, int index, int neighbor)
2660 {
2661         const int idx = ed->n_index[index];
2662
2663         for (int i = 0; i < ed->n_num[index]; i++) {
2664                 if (ed->n_target[idx + i] == neighbor) {
2665                         return true;
2666                 }
2667         }
2668
2669         return false;
2670 }
2671
2672 /* Makes the adjacency data symmetric, except for border pixels. I.e. if A is neighbor of B, B is neighbor of A. */
2673 static bool dynamicPaint_symmetrizeAdjData(PaintAdjData *ed, int active_points)
2674 {
2675         int *new_n_index = MEM_callocN(sizeof(int) * active_points, "Surface Adj Index");
2676         int *new_n_num = MEM_callocN(sizeof(int) * active_points, "Surface Adj Counts");
2677
2678         if (new_n_num && new_n_index) {
2679                 /* Count symmetrized neigbors */
2680                 int total_targets = 0;
2681
2682                 for (int index = 0; index < active_points; index++) {
2683                         total_targets += ed->n_num[index];
2684                         new_n_num[index] = ed->n_num[index];
2685                 }
2686
2687                 for (int index = 0; index < active_points; index++) {
2688                         if (ed->flags[index] & ADJ_BORDER_PIXEL) {
2689                                 continue;
2690                         }
2691
2692                         for (int i = 0, idx = ed->n_index[index]; i < ed->n_num[index]; i++) {
2693                                 const int target = ed->n_target[idx + i];
2694
2695                                 assert(!(ed->flags[target] & ADJ_BORDER_PIXEL));
2696
2697                                 if (!dynamicPaint_pointHasNeighbor(ed, target, index)) {
2698                                         new_n_num[target]++;
2699                                         total_targets++;
2700                                 }
2701                         }
2702                 }
2703
2704                 /* Allocate a new target map */
2705                 int *new_n_target = MEM_callocN(sizeof(int) * total_targets, "Surface Adj Targets");
2706
2707                 if (new_n_target) {
2708                         /* Copy existing neighbors to the new map */
2709                         int n_pos = 0;
2710
2711                         for (int index = 0; index < active_points; index++) {
2712                                 new_n_index[index] = n_pos;
2713                                 memcpy(&new_n_target[n_pos], &ed->n_target[ed->n_index[index]], sizeof(int) * ed->n_num[index]);
2714
2715                                 /* Reset count to old, but advance position by new, leaving a gap to fill below. */
2716                                 n_pos += new_n_num[index];
2717                                 new_n_num[index] = ed->n_num[index];
2718                         }
2719
2720                         assert(n_pos == total_targets);
2721
2722                         /* Add symmetrized - this loop behavior must exactly match the count pass above */
2723                         for (int index = 0; index < active_points; index++) {
2724                                 if (ed->flags[index] & ADJ_BORDER_PIXEL) {
2725                                         continue;
2726                                 }
2727
2728                                 for (int i = 0, idx = ed->n_index[index]; i < ed->n_num[index]; i++) {
2729                                         const int target = ed->n_target[idx + i];
2730
2731                                         if (!dynamicPaint_pointHasNeighbor(ed, target, index)) {
2732                                                 const int num = new_n_num[target]++;
2733                                                 new_n_target[new_n_index[target] + num] = index;
2734                                         }
2735                                 }
2736                         }
2737
2738                         /* Swap maps */
2739                         MEM_freeN(ed->n_target);
2740                         ed->n_target = new_n_target;
2741
2742                         MEM_freeN(ed->n_index);
2743                         ed->n_index = new_n_index;
2744
2745                         MEM_freeN(ed->n_num);
2746                         ed->n_num = new_n_num;
2747
2748                         ed->total_targets = total_targets;
2749                         return true;
2750                 }
2751         }
2752
2753         if (new_n_index)
2754                 MEM_freeN(new_n_index);
2755         if (new_n_num)
2756                 MEM_freeN(new_n_num);
2757
2758         return false;
2759 }
2760
2761 int dynamicPaint_createUVSurface(Scene *scene, DynamicPaintSurface *surface, float *progress, short *do_update)
2762 {
2763         /* Antialias jitter point relative coords */
2764         const int aa_samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
2765         char uvname[MAX_CUSTOMDATA_LAYER_NAME];
2766         uint32_t active_points = 0;
2767         bool error = false;
2768
2769         PaintSurfaceData *sData;
2770         DynamicPaintCanvasSettings *canvas = surface->canvas;
2771         Mesh *mesh = canvas->mesh;
2772
2773         PaintUVPoint *tempPoints = NULL;
2774         Vec3f *tempWeights = NULL;
2775         const MLoopTri *mlooptri = NULL;
2776         const MLoopUV *mloopuv = NULL;
2777         const MLoop *mloop = NULL;
2778
2779         Bounds2D *faceBB = NULL;
2780         int *final_index;
2781
2782         *progress = 0.0f;
2783         *do_update = true;
2784
2785         if (!mesh)
2786                 return setError(canvas, N_("Canvas mesh not updated"));
2787         if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ)
2788                 return setError(canvas, N_("Cannot bake non-'image sequence' formats"));
2789
2790         mloop = mesh->mloop;
2791         mlooptri = BKE_mesh_runtime_looptri_ensure(mesh);
2792         const int tottri = BKE_mesh_runtime_looptri_len(mesh);
2793
2794         /* get uv map */
2795         if (CustomData_has_layer(&mesh->ldata, CD_MLOOPUV)) {
2796                 CustomData_validate_layer_name(&mesh->ldata, CD_MLOOPUV, surface->uvlayer_name, uvname);
2797                 mloopuv = CustomData_get_layer_named(&mesh->ldata, CD_MLOOPUV, uvname);
2798         }
2799
2800         /* Check for validity */
2801         if (!mloopuv)
2802                 return setError(canvas, N_("No UV data on canvas"));
2803         if (surface->image_resolution < 16 || surface->image_resolution > 8192)
2804                 return setError(canvas, N_("Invalid resolution"));
2805
2806         const int w = surface->image_resolution;
2807         const int h = w;
2808
2809         /*
2810          * Start generating the surface
2811          */
2812         CLOG_INFO(&LOG, 1, "Preparing UV surface of %ix%i pixels and %i tris.", w, h, tottri);
2813
2814         /* Init data struct */
2815         if (surface->data)
2816                 dynamicPaint_freeSurfaceData(surface);
2817         sData = surface->data = MEM_callocN(sizeof(PaintSurfaceData), "PaintSurfaceData");
2818         if (!surface->data)
2819                 return setError(canvas, N_("Not enough free memory"));
2820
2821         tempPoints = MEM_callocN(w * h * sizeof(*tempPoints), "Temp PaintUVPoint");
2822         if (!tempPoints)
2823                 error = true;
2824
2825         final_index = MEM_callocN(w * h * sizeof(*final_index), "Temp UV Final Indexes");
2826         if (!final_index)
2827                 error = true;
2828
2829         tempWeights = MEM_mallocN(w * h * aa_samples * sizeof(*tempWeights), "Temp bWeights");
2830         if (!tempWeights)
2831                 error = true;
2832
2833         /*
2834          * Generate a temporary bounding box array for UV faces to optimize
2835          * the pixel-inside-a-face search.
2836          */
2837         if (!error) {
2838                 faceBB = MEM_mallocN(tottri * sizeof(*faceBB), "MPCanvasFaceBB");
2839                 if (!faceBB)
2840                         error = true;
2841         }
2842
2843         *progress = 0.01f;
2844         *do_update = true;
2845
2846         if (!error) {
2847                 for (int i = 0; i < tottri; i++) {
2848                         copy_v2_v2(faceBB[i].min, mloopuv[mlooptri[i].tri[0]].uv);
2849                         copy_v2_v2(faceBB[i].max, mloopuv[mlooptri[i].tri[0]].uv);
2850
2851                         for (int j = 1; j < 3; j++) {
2852                                 minmax_v2v2_v2(faceBB[i].min, faceBB[i].max, mloopuv[mlooptri[i].tri[j]].uv);
2853                         }
2854                 }
2855
2856                 *progress = 0.02f;
2857                 *do_update = true;
2858
2859                 /* Loop through every pixel and check if pixel is uv-mapped on a canvas face. */
2860                 DynamicPaintCreateUVSurfaceData data = {
2861                     .surface = surface, .tempPoints = tempPoints, .tempWeights = tempWeights,
2862                     .mlooptri = mlooptri, .mloopuv = mloopuv, .mloop = mloop, .tottri = tottri,
2863                     .faceBB = faceBB,
2864                 };
2865                 {
2866                         ParallelRangeSettings settings;
2867                         BLI_parallel_range_settings_defaults(&settings);
2868                         settings.use_threading = (h > 64 || tottri > 1000);
2869                         BLI_task_parallel_range(0, h,
2870                                                 &data,
2871                                                 dynamic_paint_create_uv_surface_direct_cb,
2872                                                 &settings);
2873                 }
2874
2875                 *progress = 0.04f;
2876                 *do_update = true;
2877
2878                 /*
2879                  * Now loop through every pixel that was left without index
2880                  * and find if they have neighboring pixels that have an index.
2881                  * If so use that polygon as pixel surface.
2882                  * (To avoid seams on uv island edges)
2883                  */
2884                 data.active_points = &active_points;
2885                 {
2886                         ParallelRangeSettings settings;
2887                         BLI_parallel_range_settings_defaults(&settings);
2888                         settings.use_threading = (h > 64);
2889                         BLI_task_parallel_range(0, h,
2890                                                 &data,
2891                                                 dynamic_paint_create_uv_surface_neighbor_cb,
2892                                                 &settings);
2893                 }
2894
2895                 *progress = 0.06f;
2896                 *do_update = true;
2897
2898                 /* Generate surface adjacency data. */
2899                 {
2900                         int cursor = 0;
2901
2902                         /* Create a temporary array of final indexes (before unassigned
2903                          * pixels have been dropped) */
2904                         for (int i = 0; i < w * h; i++) {
2905                                 if (tempPoints[i].tri_index != -1) {
2906                                         final_index[i] = cursor;
2907                                         cursor++;
2908                                 }
2909                         }
2910                         /* allocate memory */
2911                         sData->total_points = w * h;
2912                         dynamicPaint_initAdjacencyData(surface, true);
2913
2914                         if (sData->adj_data) {
2915                                 PaintAdjData *ed = sData->adj_data;
2916                                 int n_pos = 0;
2917
2918                                 MeshElemMap *vert_to_looptri_map;
2919                                 int *vert_to_looptri_map_mem;
2920
2921                                 BKE_mesh_vert_looptri_map_create(
2922                                         &vert_to_looptri_map, &vert_to_looptri_map_mem,
2923                                         mesh->mvert, mesh->totvert, mlooptri, tottri, mloop, mesh->totloop);
2924
2925                                 int total_border = 0;
2926
2927                                 for (int ty = 0; ty < h; ty++) {
2928                                         for (int tx = 0; tx < w; tx++) {
2929                                                 const int index = tx + w * ty;
2930
2931                                                 if (tempPoints[index].tri_index != -1) {
2932                                                         ed->n_index[final_index[index]] = n_pos;
2933                                                         ed->n_num[final_index[index]] = 0;
2934
2935                                                         if (tempPoints[index].neighbour_pixel != -1) {
2936                                                                 ed->flags[final_index[index]] |= ADJ_BORDER_PIXEL;
2937                                                                 total_border++;
2938                                                         }
2939
2940                                                         for (int i = 0; i < 8; i++) {
2941                                                                 /* Try to find a neighboring pixel in defined direction. If not found, -1 is returned */
2942                                                                 const int n_target = dynamic_paint_find_neighbour_pixel(
2943                                                                                          &data, vert_to_looptri_map, w, h, tx, ty, i);
2944
2945                                                                 if (n_target >= 0 && n_target != index) {
2946                                                                         if (!dynamicPaint_pointHasNeighbor(ed, final_index[index], final_index[n_target])) {
2947                                                                                 ed->n_target[n_pos] = final_index[n_target];
2948                                                                                 ed->n_num[final_index[index]]++;
2949                                                                                 n_pos++;
2950                                                                         }
2951                                                                 }
2952                                                                 else if (n_target == ON_MESH_EDGE || n_target == OUT_OF_TEXTURE) {
2953                                                                         ed->flags[final_index[index]] |= ADJ_ON_MESH_EDGE;
2954                                                                 }
2955                                                         }
2956                                                 }
2957                                         }
2958                                 }
2959
2960                                 MEM_freeN(vert_to_looptri_map);
2961                                 MEM_freeN(vert_to_looptri_map_mem);
2962
2963                                 /* Make neighbors symmetric */
2964                                 if (!dynamicPaint_symmetrizeAdjData(ed, active_points)) {
2965                                         error = true;
2966                                 }
2967
2968                                 /* Create a list of border pixels */
2969                                 ed->border = MEM_callocN(sizeof(int) * total_border, "Border Pixel Index");
2970