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