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