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