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