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