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