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