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