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