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