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