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