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