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