fix for crash in point comparison when one of the arrays is NULL
[blender.git] / source / blender / blenkernel / intern / mask.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  * The Original Code is Copyright (C) 2012 Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation,
22  *                 Sergey Sharybin
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenkernel/intern/mask.c
28  *  \ingroup bke
29  */
30
31 #include <stddef.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "BLI_utildefines.h"
37 #include "BLI_path_util.h"
38 #include "BLI_string.h"
39 #include "BLI_listbase.h"
40 #include "BLI_math.h"
41
42 #include "DNA_mask_types.h"
43 #include "DNA_scene_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_movieclip_types.h"
48 #include "DNA_tracking_types.h"
49
50 #include "BKE_curve.h"
51 #include "BKE_global.h"
52 #include "BKE_library.h"
53 #include "BKE_main.h"
54 #include "BKE_mask.h"
55 #include "BKE_tracking.h"
56 #include "BKE_movieclip.h"
57 #include "BKE_utildefines.h"
58
59 #include "raskter.h"
60
61 #ifdef USE_MANGO_MASK_CACHE_HACK
62 typedef struct MaskRasterCache {
63         float *buffer;
64         int width, height;
65         short do_aspect_correct;
66         short do_mask_aa;
67         short do_feather;
68
69         ListBase layers;
70 } MaskRasterCache;
71 #endif
72
73 static MaskSplinePoint *mask_spline_point_next(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
74 {
75         if (point == &points_array[spline->tot_point - 1]) {
76                 if (spline->flag & MASK_SPLINE_CYCLIC) {
77                         return &points_array[0];
78                 }
79                 else {
80                         return NULL;
81                 }
82         }
83         else {
84                 return point + 1;
85         }
86 }
87
88 static MaskSplinePoint *mask_spline_point_prev(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
89 {
90         if (point == points_array) {
91                 if (spline->flag & MASK_SPLINE_CYCLIC) {
92                         return &points_array[spline->tot_point - 1];
93                 }
94                 else {
95                         return NULL;
96                 }
97         }
98         else {
99                 return point - 1;
100         }
101 }
102
103 static BezTriple *mask_spline_point_next_bezt(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
104 {
105         if (point == &points_array[spline->tot_point - 1]) {
106                 if (spline->flag & MASK_SPLINE_CYCLIC) {
107                         return &(points_array[0].bezt);
108                 }
109                 else {
110                         return NULL;
111                 }
112         }
113         else {
114                 return &((point + 1))->bezt;
115         }
116 }
117
118 #if 0
119 static BezTriple *mask_spline_point_prev_bezt(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
120 {
121         if (point == points_array) {
122                 if (spline->flag & MASK_SPLINE_CYCLIC) {
123                         return &(points_array[0].bezt);
124                 }
125                 else  {
126                         return NULL;
127                 }
128         }
129         else {
130                 return &((point - 1))->bezt;
131         }
132 }
133 #endif
134
135 MaskSplinePoint *BKE_mask_spline_point_array(MaskSpline *spline)
136 {
137         return spline->points_deform ? spline->points_deform : spline->points;
138 }
139
140 MaskSplinePoint *BKE_mask_spline_point_array_from_point(MaskSpline *spline, MaskSplinePoint *point_ref)
141 {
142         if ((point_ref >= spline->points) && (point_ref < &spline->points[spline->tot_point])) {
143                 return spline->points;
144         }
145
146         if ((point_ref >= spline->points_deform) && (point_ref < &spline->points_deform[spline->tot_point])) {
147                 return spline->points_deform;
148         }
149
150         BLI_assert(!"wrong array");
151         return NULL;
152 }
153
154 /* mask layers */
155
156 MaskLayer *BKE_mask_layer_new(Mask *mask, const char *name)
157 {
158         MaskLayer *masklay = MEM_callocN(sizeof(MaskLayer), __func__);
159
160         if (name && name[0])
161                 BLI_strncpy(masklay->name, name, sizeof(masklay->name));
162         else
163                 strcpy(masklay->name, "MaskLayer");
164
165         BLI_addtail(&mask->masklayers, masklay);
166
167         BKE_mask_layer_unique_name(mask, masklay);
168
169         mask->masklay_tot++;
170
171         masklay->alpha = 1.0f;
172
173         return masklay;
174 }
175
176 /* note: may still be hidden, caller needs to check */
177 MaskLayer *BKE_mask_layer_active(Mask *mask)
178 {
179         return BLI_findlink(&mask->masklayers, mask->masklay_act);
180 }
181
182 void BKE_mask_layer_active_set(Mask *mask, MaskLayer *masklay)
183 {
184         mask->masklay_act = BLI_findindex(&mask->masklayers, masklay);
185 }
186
187 void BKE_mask_layer_remove(Mask *mask, MaskLayer *masklay)
188 {
189         BLI_remlink(&mask->masklayers, masklay);
190         BKE_mask_layer_free(masklay);
191
192         mask->masklay_tot--;
193
194         if (mask->masklay_act >= mask->masklay_tot)
195                 mask->masklay_act = mask->masklay_tot - 1;
196 }
197
198 void BKE_mask_layer_unique_name(Mask *mask, MaskLayer *masklay)
199 {
200         BLI_uniquename(&mask->masklayers, masklay, "MaskLayer", '.', offsetof(MaskLayer, name), sizeof(masklay->name));
201 }
202
203 MaskLayer *BKE_mask_layer_copy(MaskLayer *layer)
204 {
205         MaskLayer *layer_new;
206         MaskSpline *spline;
207
208         layer_new = MEM_callocN(sizeof(MaskLayer), "new mask layer");
209
210         BLI_strncpy(layer_new->name, layer->name, sizeof(layer_new->name));
211
212         layer_new->alpha = layer->alpha;
213         layer_new->blend = layer->blend;
214         layer_new->blend_flag = layer->blend_flag;
215         layer_new->flag = layer->flag;
216         layer_new->restrictflag = layer->restrictflag;
217
218         for (spline = layer->splines.first; spline; spline = spline->next) {
219                 MaskSpline *spline_new = BKE_mask_spline_copy(spline);
220
221                 BLI_addtail(&layer_new->splines, spline_new);
222         }
223
224         return layer_new;
225 }
226
227 void BKE_mask_layer_copy_list(ListBase *masklayers_new, ListBase *masklayers)
228 {
229         MaskLayer *layer;
230
231         for (layer = masklayers->first; layer; layer = layer->next) {
232                 MaskLayer *layer_new = BKE_mask_layer_copy(layer);
233
234                 BLI_addtail(masklayers_new, layer_new);
235         }
236 }
237
238 /* splines */
239
240 MaskSpline *BKE_mask_spline_add(MaskLayer *masklay)
241 {
242         MaskSpline *spline;
243
244         spline = MEM_callocN(sizeof(MaskSpline), "new mask spline");
245         BLI_addtail(&masklay->splines, spline);
246
247         /* spline shall have one point at least */
248         spline->points = MEM_callocN(sizeof(MaskSplinePoint), "new mask spline point");
249         spline->tot_point = 1;
250
251         /* cyclic shapes are more usually used */
252         // spline->flag |= MASK_SPLINE_CYCLIC; // disable because its not so nice for drawing. could be done differently
253
254         spline->weight_interp = MASK_SPLINE_INTERP_LINEAR;
255
256         BKE_mask_parent_init(&spline->parent);
257
258         return spline;
259 }
260
261 static int BKE_mask_spline_resolution(MaskSpline *spline, int width, int height)
262 {
263         float max_segment = 0.01f;
264         int i, resol = 1;
265
266         if (width != 0 && height != 0) {
267                 if (width >= height)
268                         max_segment = 1.0f / (float) width;
269                 else
270                         max_segment = 1.0f / (float) height;
271         }
272
273         for (i = 0; i < spline->tot_point; i++) {
274                 MaskSplinePoint *point = &spline->points[i];
275                 BezTriple *bezt, *bezt_next;
276                 float a, b, c, len;
277                 int cur_resol;
278
279                 bezt = &point->bezt;
280                 bezt_next = mask_spline_point_next_bezt(spline, spline->points, point);
281
282                 if (bezt_next == NULL) {
283                         break;
284                 }
285
286                 a = len_v3v3(bezt->vec[1], bezt->vec[2]);
287                 b = len_v3v3(bezt->vec[2], bezt_next->vec[0]);
288                 c = len_v3v3(bezt_next->vec[0], bezt_next->vec[1]);
289
290                 len = a + b + c;
291                 cur_resol = len / max_segment;
292
293                 resol = MAX2(resol, cur_resol);
294         }
295
296         return resol;
297 }
298
299 static int BKE_mask_spline_feather_resolution(MaskSpline *spline, int width, int height)
300 {
301         const float max_segment = 0.005;
302         int resol = BKE_mask_spline_resolution(spline, width, height);
303         float max_jump = 0.0f;
304         int i;
305
306         for (i = 0; i < spline->tot_point; i++) {
307                 MaskSplinePoint *point = &spline->points[i];
308                 float prev_u, prev_w;
309                 int j;
310
311                 prev_u = 0.0f;
312                 prev_w = point->bezt.weight;
313
314                 for (j = 0; j < point->tot_uw; j++) {
315                         float jump = fabsf((point->uw[j].w - prev_w) / (point->uw[j].u - prev_u));
316
317                         max_jump = MAX2(max_jump, jump);
318
319                         prev_u = point->uw[j].u;
320                         prev_w = point->uw[j].w;
321                 }
322         }
323
324         resol += max_jump / max_segment;
325
326         return resol;
327 }
328
329 float (*BKE_mask_spline_differentiate_with_resolution(MaskSpline *spline, int width, int height,
330                                                       int *tot_diff_point))[2]
331 {
332         MaskSplinePoint *points_array = BKE_mask_spline_point_array(spline);
333
334         MaskSplinePoint *point, *prev;
335         float (*diff_points)[2], (*fp)[2];
336         int a, len, resol = BKE_mask_spline_resolution(spline, width, height);
337
338         if (spline->tot_point <= 1) {
339                 /* nothing to differentiate */
340                 *tot_diff_point = 0;
341                 return NULL;
342         }
343
344         /* count */
345         len = (spline->tot_point - 1) * resol;
346
347         if (spline->flag & MASK_SPLINE_CYCLIC)
348                 len += resol;
349         else
350                 len++;
351
352         /* len+1 because of 'forward_diff_bezier' function */
353         *tot_diff_point = len;
354         diff_points = fp = MEM_mallocN((len + 1) * sizeof(*diff_points), "mask spline vets");
355
356         a = spline->tot_point - 1;
357         if (spline->flag & MASK_SPLINE_CYCLIC)
358                 a++;
359
360         prev = points_array;
361         point = prev + 1;
362
363         while (a--) {
364                 BezTriple *prevbezt;
365                 BezTriple *bezt;
366                 int j;
367
368                 if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC))
369                         point = points_array;
370
371                 prevbezt = &prev->bezt;
372                 bezt = &point->bezt;
373
374                 for (j = 0; j < 2; j++) {
375                         BKE_curve_forward_diff_bezier(prevbezt->vec[1][j], prevbezt->vec[2][j],
376                                                       bezt->vec[0][j], bezt->vec[1][j],
377                                                       &(*fp)[j], resol, 2 * sizeof(float));
378                 }
379
380                 fp += resol;
381
382                 if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC) == 0) {
383                         copy_v2_v2(*fp, bezt->vec[1]);
384                 }
385
386                 prev = point;
387                 point++;
388         }
389
390         return diff_points;
391 }
392
393 float (*BKE_mask_spline_differentiate(MaskSpline *spline, int *tot_diff_point))[2]
394 {
395         return BKE_mask_spline_differentiate_with_resolution(spline, 0, 0, tot_diff_point);
396 }
397
398 float (*BKE_mask_spline_feather_differentiated_points_with_resolution(MaskSpline *spline, int width, int height,
399                                                                       int *tot_feather_point))[2]
400 {
401         MaskSplinePoint *points_array = BKE_mask_spline_point_array(spline);
402
403         float (*feather)[2], (*fp)[2];
404         int i, j, tot, resol = BKE_mask_spline_feather_resolution(spline, width, height);
405
406         tot = resol * spline->tot_point;
407         feather = fp = MEM_mallocN(tot * sizeof(*feather), "mask spline feather diff points");
408
409         for (i = 0; i < spline->tot_point; i++) {
410                 MaskSplinePoint *point = &points_array[i];
411
412                 for (j = 0; j < resol; j++, fp++) {
413                         float u = (float) j / resol, weight;
414                         float co[2], n[2];
415
416                         /* TODO - these calls all calculate similar things
417                          * could be unified for some speed */
418                         BKE_mask_point_segment_co(spline, point, u, co);
419                         BKE_mask_point_normal(spline, point, u, n);
420                         weight = BKE_mask_point_weight(spline, point, u);
421
422                         madd_v2_v2v2fl(*fp, co, n, weight);
423                 }
424         }
425
426         *tot_feather_point = tot;
427
428         return feather;
429 }
430
431 float (*BKE_mask_spline_feather_differentiated_points(MaskSpline *spline, int *tot_feather_point))[2]
432 {
433         return BKE_mask_spline_feather_differentiated_points_with_resolution(spline, 0, 0, tot_feather_point);
434 }
435
436 float (*BKE_mask_spline_feather_points(MaskSpline *spline, int *tot_feather_point))[2]
437 {
438         MaskSplinePoint *points_array = BKE_mask_spline_point_array(spline);
439
440         int i, tot = 0;
441         float (*feather)[2], (*fp)[2];
442
443         /* count */
444         for (i = 0; i < spline->tot_point; i++) {
445                 MaskSplinePoint *point = &points_array[i];
446
447                 tot += point->tot_uw + 1;
448         }
449
450         /* create data */
451         feather = fp = MEM_mallocN(tot * sizeof(*feather), "mask spline feather points");
452
453         for (i = 0; i < spline->tot_point; i++) {
454                 MaskSplinePoint *point = &points_array[i];
455                 BezTriple *bezt = &point->bezt;
456                 float weight, n[2];
457                 int j;
458
459                 BKE_mask_point_normal(spline, point, 0.0f, n);
460                 weight = BKE_mask_point_weight(spline, point, 0.0f);
461
462                 madd_v2_v2v2fl(*fp, bezt->vec[1], n, weight);
463                 fp++;
464
465                 for (j = 0; j < point->tot_uw; j++) {
466                         float u = point->uw[j].u;
467                         float co[2];
468
469                         BKE_mask_point_segment_co(spline, point, u, co);
470                         BKE_mask_point_normal(spline, point, u, n);
471                         weight = BKE_mask_point_weight(spline, point, u);
472
473                         madd_v2_v2v2fl(*fp, co, n, weight);
474                         fp++;
475                 }
476         }
477
478         *tot_feather_point = tot;
479
480         return feather;
481 }
482
483 void BKE_mask_point_direction_switch(MaskSplinePoint *point)
484 {
485         const int tot_uw = point->tot_uw;
486         const int tot_uw_half = tot_uw / 2;
487         int i;
488
489         float co_tmp[2];
490
491         /* swap handles */
492         copy_v2_v2(co_tmp, point->bezt.vec[0]);
493         copy_v2_v2(point->bezt.vec[0], point->bezt.vec[2]);
494         copy_v2_v2(point->bezt.vec[2], co_tmp);
495         /* in this case the flags are unlikely to be different but swap anyway */
496         SWAP(char, point->bezt.f1, point->bezt.f3);
497         SWAP(char, point->bezt.h1, point->bezt.h2);
498
499
500         /* swap UW's */
501         if (tot_uw > 1) {
502                 /* count */
503                 for (i = 0; i < tot_uw_half; i++) {
504                         MaskSplinePointUW *uw_a = &point->uw[i];
505                         MaskSplinePointUW *uw_b = &point->uw[tot_uw - (i + 1)];
506                         SWAP(MaskSplinePointUW, *uw_a, *uw_b);
507                 }
508         }
509
510         for (i = 0; i < tot_uw; i++) {
511                 MaskSplinePointUW *uw = &point->uw[i];
512                 uw->u = 1.0f - uw->u;
513         }
514 }
515
516 void BKE_mask_spline_direction_switch(MaskLayer *masklay, MaskSpline *spline)
517 {
518         const int tot_point = spline->tot_point;
519         const int tot_point_half = tot_point / 2;
520         int i, i_prev;
521
522         if (tot_point < 2) {
523                 return;
524         }
525
526         /* count */
527         for (i = 0; i < tot_point_half; i++) {
528                 MaskSplinePoint *point_a = &spline->points[i];
529                 MaskSplinePoint *point_b = &spline->points[tot_point - (i + 1)];
530                 SWAP(MaskSplinePoint, *point_a, *point_b);
531         }
532
533         /* correct UW's */
534         i_prev = tot_point - 1;
535         for (i = 0; i < tot_point; i++) {
536
537                 BKE_mask_point_direction_switch(&spline->points[i]);
538
539                 SWAP(MaskSplinePointUW *, spline->points[i].uw,     spline->points[i_prev].uw);
540                 SWAP(int,                 spline->points[i].tot_uw, spline->points[i_prev].tot_uw);
541
542                 i_prev = i;
543         }
544
545         /* correct animation */
546         if (masklay->splines_shapes.first) {
547                 MaskLayerShape *masklay_shape;
548
549                 const int spline_index = BKE_mask_layer_shape_spline_to_index(masklay, spline);
550
551                 for (masklay_shape = masklay->splines_shapes.first;
552                      masklay_shape;
553                      masklay_shape = masklay_shape->next)
554                 {
555                         MaskLayerShapeElem *fp_arr = (MaskLayerShapeElem *)masklay_shape->data;
556
557                         for (i = 0; i < tot_point_half; i++) {
558                                 MaskLayerShapeElem *fp_a = &fp_arr[spline_index +              (i)     ];
559                                 MaskLayerShapeElem *fp_b = &fp_arr[spline_index + (tot_point - (i + 1))];
560                                 SWAP(MaskLayerShapeElem, *fp_a, *fp_b);
561                         }
562                 }
563         }
564 }
565
566
567 float BKE_mask_spline_project_co(MaskSpline *spline, MaskSplinePoint *point,
568                                  float start_u, const float co[2], const eMaskSign sign)
569 {
570         const float proj_eps         = 1e-3;
571         const float proj_eps_squared = proj_eps * proj_eps;
572         const int N = 1000;
573         float u = -1.0f, du = 1.0f / N, u1 = start_u, u2 = start_u;
574         float ang = -1.0f;
575
576         BLI_assert(ABS(sign) <= 1); /* (-1, 0, 1) */
577
578         while (u1 > 0.0f || u2 < 1.0f) {
579                 float n1[2], n2[2], co1[2], co2[2];
580                 float v1[2], v2[2];
581                 float ang1, ang2;
582
583                 if (u1 >= 0.0f) {
584                         BKE_mask_point_segment_co(spline, point, u1, co1);
585                         BKE_mask_point_normal(spline, point, u1, n1);
586                         sub_v2_v2v2(v1, co, co1);
587
588                         if ((sign == MASK_PROJ_ANY) ||
589                             ((sign == MASK_PROJ_NEG) && (dot_v2v2(v1, n1) <= 0.0f)) ||
590                             ((sign == MASK_PROJ_POS) && (dot_v2v2(v1, n1) >= 0.0f)))
591                         {
592
593                                 if (len_squared_v2(v1) > proj_eps_squared) {
594                                         ang1 = angle_v2v2(v1, n1);
595                                         if (ang1 > M_PI / 2.0f)
596                                                 ang1 = M_PI  - ang1;
597
598                                         if (ang < 0.0f || ang1 < ang) {
599                                                 ang = ang1;
600                                                 u = u1;
601                                         }
602                                 }
603                                 else {
604                                         u = u1;
605                                         break;
606                                 }
607                         }
608                 }
609
610                 if (u2 <= 1.0f) {
611                         BKE_mask_point_segment_co(spline, point, u2, co2);
612                         BKE_mask_point_normal(spline, point, u2, n2);
613                         sub_v2_v2v2(v2, co, co2);
614
615                         if ((sign == MASK_PROJ_ANY) ||
616                             ((sign == MASK_PROJ_NEG) && (dot_v2v2(v2, n2) <= 0.0f)) ||
617                             ((sign == MASK_PROJ_POS) && (dot_v2v2(v2, n2) >= 0.0f)))
618                         {
619
620                                 if (len_squared_v2(v2) > proj_eps_squared) {
621                                         ang2 = angle_v2v2(v2, n2);
622                                         if (ang2 > M_PI / 2.0f)
623                                                 ang2 = M_PI  - ang2;
624
625                                         if (ang2 < ang) {
626                                                 ang = ang2;
627                                                 u = u2;
628                                         }
629                                 }
630                                 else {
631                                         u = u2;
632                                         break;
633                                 }
634                         }
635                 }
636
637                 u1 -= du;
638                 u2 += du;
639         }
640
641         return u;
642 }
643
644 /* point */
645
646 int BKE_mask_point_has_handle(MaskSplinePoint *point)
647 {
648         BezTriple *bezt = &point->bezt;
649
650         return bezt->h1 == HD_ALIGN;
651 }
652
653 void BKE_mask_point_handle(MaskSplinePoint *point, float handle[2])
654 {
655         float vec[2];
656
657         sub_v2_v2v2(vec, point->bezt.vec[0], point->bezt.vec[1]);
658
659         handle[0] = (point->bezt.vec[1][0] + vec[1]);
660         handle[1] = (point->bezt.vec[1][1] - vec[0]);
661 }
662
663 void BKE_mask_point_set_handle(MaskSplinePoint *point, float loc[2], int keep_direction,
664                                float orig_handle[2], float orig_vec[3][3])
665 {
666         BezTriple *bezt = &point->bezt;
667         float v1[2], v2[2], vec[2];
668
669         if (keep_direction) {
670                 sub_v2_v2v2(v1, loc, orig_vec[1]);
671                 sub_v2_v2v2(v2, orig_handle, orig_vec[1]);
672
673                 project_v2_v2v2(vec, v1, v2);
674
675                 if (dot_v2v2(v2, vec) > 0) {
676                         float len = len_v2(vec);
677
678                         sub_v2_v2v2(v1, orig_vec[0], orig_vec[1]);
679
680                         mul_v2_fl(v1, len / len_v2(v1));
681
682                         add_v2_v2v2(bezt->vec[0], bezt->vec[1], v1);
683                         sub_v2_v2v2(bezt->vec[2], bezt->vec[1], v1);
684                 }
685                 else {
686                         copy_v3_v3(bezt->vec[0], bezt->vec[1]);
687                         copy_v3_v3(bezt->vec[2], bezt->vec[1]);
688                 }
689         }
690         else {
691                 sub_v2_v2v2(v1, loc, bezt->vec[1]);
692
693                 v2[0] = -v1[1];
694                 v2[1] =  v1[0];
695
696                 add_v2_v2v2(bezt->vec[0], bezt->vec[1], v2);
697                 sub_v2_v2v2(bezt->vec[2], bezt->vec[1], v2);
698         }
699 }
700
701 float *BKE_mask_point_segment_feather_diff_with_resolution(MaskSpline *spline, MaskSplinePoint *point,
702                                                            int width, int height,
703                                                            int *tot_feather_point)
704 {
705         float *feather, *fp;
706         int i, resol = BKE_mask_spline_feather_resolution(spline, width, height);
707
708         feather = fp = MEM_callocN(2 * resol * sizeof(float), "mask point spline feather diff points");
709
710         for (i = 0; i < resol; i++, fp += 2) {
711                 float u = (float)(i % resol) / resol, weight;
712                 float co[2], n[2];
713
714                 BKE_mask_point_segment_co(spline, point, u, co);
715                 BKE_mask_point_normal(spline, point, u, n);
716                 weight = BKE_mask_point_weight(spline, point, u);
717
718                 fp[0] = co[0] + n[0] * weight;
719                 fp[1] = co[1] + n[1] * weight;
720         }
721
722         *tot_feather_point = resol;
723
724         return feather;
725 }
726
727 float *BKE_mask_point_segment_feather_diff(MaskSpline *spline, MaskSplinePoint *point, int *tot_feather_point)
728 {
729         return BKE_mask_point_segment_feather_diff_with_resolution(spline, point, 0, 0, tot_feather_point);
730 }
731
732 float *BKE_mask_point_segment_diff_with_resolution(MaskSpline *spline, MaskSplinePoint *point,
733                                                    int width, int height, int *tot_diff_point)
734 {
735         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
736
737         BezTriple *bezt, *bezt_next;
738         float *diff_points, *fp;
739         int j, resol = BKE_mask_spline_resolution(spline, width, height);
740
741         bezt = &point->bezt;
742         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
743
744         if (!bezt_next)
745                 return NULL;
746
747         /* resol+1 because of 'forward_diff_bezier' function */
748         *tot_diff_point = resol + 1;
749         diff_points = fp = MEM_callocN((resol + 1) * 2 * sizeof(float), "mask segment vets");
750
751         for (j = 0; j < 2; j++) {
752                 BKE_curve_forward_diff_bezier(bezt->vec[1][j], bezt->vec[2][j],
753                                               bezt_next->vec[0][j], bezt_next->vec[1][j],
754                                               fp + j, resol, 2 * sizeof(float));
755         }
756
757         copy_v2_v2(fp + 2 * resol, bezt_next->vec[1]);
758
759         return diff_points;
760 }
761
762 float *BKE_mask_point_segment_diff(MaskSpline *spline, MaskSplinePoint *point, int *tot_diff_point)
763 {
764         return BKE_mask_point_segment_diff_with_resolution(spline, point, 0, 0, tot_diff_point);
765 }
766
767 void BKE_mask_point_segment_co(MaskSpline *spline, MaskSplinePoint *point, float u, float co[2])
768 {
769         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
770
771         BezTriple *bezt = &point->bezt, *bezt_next;
772         float q0[2], q1[2], q2[2], r0[2], r1[2];
773
774         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
775
776         if (!bezt_next) {
777                 copy_v2_v2(co, bezt->vec[1]);
778                 return;
779         }
780
781         interp_v2_v2v2(q0, bezt->vec[1], bezt->vec[2], u);
782         interp_v2_v2v2(q1, bezt->vec[2], bezt_next->vec[0], u);
783         interp_v2_v2v2(q2, bezt_next->vec[0], bezt_next->vec[1], u);
784
785         interp_v2_v2v2(r0, q0, q1, u);
786         interp_v2_v2v2(r1, q1, q2, u);
787
788         interp_v2_v2v2(co, r0, r1, u);
789 }
790
791 void BKE_mask_point_normal(MaskSpline *spline, MaskSplinePoint *point, float u, float n[2])
792 {
793         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
794
795         BezTriple *bezt = &point->bezt, *bezt_next;
796         float q0[2], q1[2], q2[2], r0[2], r1[2], vec[2];
797
798         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
799
800         if (!bezt_next) {
801                 BKE_mask_point_handle(point, vec);
802
803                 sub_v2_v2v2(n, vec, bezt->vec[1]);
804                 normalize_v2(n);
805                 return;
806         }
807
808         interp_v2_v2v2(q0, bezt->vec[1], bezt->vec[2], u);
809         interp_v2_v2v2(q1, bezt->vec[2], bezt_next->vec[0], u);
810         interp_v2_v2v2(q2, bezt_next->vec[0], bezt_next->vec[1], u);
811
812         interp_v2_v2v2(r0, q0, q1, u);
813         interp_v2_v2v2(r1, q1, q2, u);
814
815         sub_v2_v2v2(vec, r1, r0);
816
817         n[0] = -vec[1];
818         n[1] =  vec[0];
819
820         normalize_v2(n);
821 }
822
823 static float mask_point_interp_weight(BezTriple *bezt, BezTriple *bezt_next, const float u)
824 {
825         return (bezt->weight * (1.0f - u)) + (bezt_next->weight * u);
826 }
827
828 float BKE_mask_point_weight_scalar(MaskSpline *spline, MaskSplinePoint *point, const float u)
829 {
830         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
831         BezTriple *bezt = &point->bezt, *bezt_next;
832
833         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
834
835         if (!bezt_next) {
836                 return bezt->weight;
837         }
838         else if (u <= 0.0) {
839                 return bezt->weight;
840         }
841         else if (u >= 1.0f) {
842                 return bezt_next->weight;
843         }
844         else {
845                 return mask_point_interp_weight(bezt, bezt_next, u);
846         }
847 }
848
849 float BKE_mask_point_weight(MaskSpline *spline, MaskSplinePoint *point, const float u)
850 {
851         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
852         BezTriple *bezt = &point->bezt, *bezt_next;
853
854         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
855
856         if (!bezt_next) {
857                 return bezt->weight;
858         }
859         else if (u <= 0.0) {
860                 return bezt->weight;
861         }
862         else if (u >= 1.0f) {
863                 return bezt_next->weight;
864         }
865         else {
866                 float cur_u = 0.0f, cur_w = 0.0f, next_u = 0.0f, next_w = 0.0f, fac; /* Quite warnings */
867                 int i;
868
869                 for (i = 0; i < point->tot_uw + 1; i++) {
870
871                         if (i == 0) {
872                                 cur_u = 0.0f;
873                                 cur_w = 1.0f; /* mask_point_interp_weight will scale it */
874                         }
875                         else {
876                                 cur_u = point->uw[i - 1].u;
877                                 cur_w = point->uw[i - 1].w;
878                         }
879
880                         if (i == point->tot_uw) {
881                                 next_u = 1.0f;
882                                 next_w = 1.0f; /* mask_point_interp_weight will scale it */
883                         }
884                         else {
885                                 next_u = point->uw[i].u;
886                                 next_w = point->uw[i].w;
887                         }
888
889                         if (u >= cur_u && u <= next_u) {
890                                 break;
891                         }
892                 }
893
894                 fac = (u - cur_u) / (next_u - cur_u);
895
896                 cur_w  *= mask_point_interp_weight(bezt, bezt_next, cur_u);
897                 next_w *= mask_point_interp_weight(bezt, bezt_next, next_u);
898
899                 if (spline->weight_interp == MASK_SPLINE_INTERP_EASE) {
900                         return cur_w + (next_w - cur_w) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
901                 }
902                 else {
903                         return (1.0f - fac) * cur_w + fac * next_w;
904                 }
905         }
906 }
907
908 MaskSplinePointUW *BKE_mask_point_sort_uw(MaskSplinePoint *point, MaskSplinePointUW *uw)
909 {
910         if (point->tot_uw > 1) {
911                 int idx = uw - point->uw;
912
913                 if (idx > 0 && point->uw[idx - 1].u > uw->u) {
914                         while (idx > 0 && point->uw[idx - 1].u > point->uw[idx].u) {
915                                 SWAP(MaskSplinePointUW, point->uw[idx - 1], point->uw[idx]);
916                                 idx--;
917                         }
918                 }
919
920                 if (idx < point->tot_uw - 1 && point->uw[idx + 1].u < uw->u) {
921                         while (idx < point->tot_uw - 1 && point->uw[idx + 1].u < point->uw[idx].u) {
922                                 SWAP(MaskSplinePointUW, point->uw[idx + 1], point->uw[idx]);
923                                 idx++;
924                         }
925                 }
926
927                 return &point->uw[idx];
928         }
929
930         return uw;
931 }
932
933 void BKE_mask_point_add_uw(MaskSplinePoint *point, float u, float w)
934 {
935         if (!point->uw)
936                 point->uw = MEM_callocN(sizeof(*point->uw), "mask point uw");
937         else
938                 point->uw = MEM_reallocN(point->uw, (point->tot_uw + 1) * sizeof(*point->uw));
939
940         point->uw[point->tot_uw].u = u;
941         point->uw[point->tot_uw].w = w;
942
943         point->tot_uw++;
944
945         BKE_mask_point_sort_uw(point, &point->uw[point->tot_uw - 1]);
946 }
947
948 void BKE_mask_point_select_set(MaskSplinePoint *point, const short do_select)
949 {
950         int i;
951
952         if (do_select) {
953                 MASKPOINT_SEL_ALL(point);
954         }
955         else {
956                 MASKPOINT_DESEL_ALL(point);
957         }
958
959         for (i = 0; i < point->tot_uw; i++) {
960                 if (do_select) {
961                         point->uw[i].flag |= SELECT;
962                 }
963                 else {
964                         point->uw[i].flag &= ~SELECT;
965                 }
966         }
967 }
968
969 void BKE_mask_point_select_set_handle(MaskSplinePoint *point, const short do_select)
970 {
971         if (do_select) {
972                 MASKPOINT_SEL_HANDLE(point);
973         }
974         else {
975                 MASKPOINT_DESEL_HANDLE(point);
976         }
977 }
978
979 /* only mask block itself */
980 static Mask *mask_alloc(const char *name)
981 {
982         Mask *mask;
983
984         mask = BKE_libblock_alloc(&G.main->mask, ID_MSK, name);
985
986         return mask;
987 }
988
989 Mask *BKE_mask_new(const char *name)
990 {
991         Mask *mask;
992         char mask_name[MAX_ID_NAME - 2];
993
994         if (name && name[0])
995                 BLI_strncpy(mask_name, name, sizeof(mask_name));
996         else
997                 strcpy(mask_name, "Mask");
998
999         mask = mask_alloc(mask_name);
1000
1001         /* arbitrary defaults */
1002         mask->sfra = 1;
1003         mask->efra = 100;
1004
1005         return mask;
1006 }
1007
1008 void BKE_mask_point_free(MaskSplinePoint *point)
1009 {
1010         if (point->uw)
1011                 MEM_freeN(point->uw);
1012 }
1013
1014 void BKE_mask_spline_free(MaskSpline *spline)
1015 {
1016         int i = 0;
1017
1018         for (i = 0; i < spline->tot_point; i++) {
1019                 MaskSplinePoint *point;
1020                 point = &spline->points[i];
1021                 BKE_mask_point_free(point);
1022
1023                 if (spline->points_deform) {
1024                         point = &spline->points_deform[i];
1025                         BKE_mask_point_free(point);
1026                 }
1027         }
1028
1029         MEM_freeN(spline->points);
1030
1031         if (spline->points_deform) {
1032                 MEM_freeN(spline->points_deform);
1033         }
1034
1035         MEM_freeN(spline);
1036 }
1037
1038 static MaskSplinePoint *mask_spline_points_copy(MaskSplinePoint *points, int tot_point)
1039 {
1040         MaskSplinePoint *npoints;
1041         int i;
1042
1043         npoints = MEM_dupallocN(points);
1044
1045         for (i = 0; i < tot_point; i++) {
1046                 MaskSplinePoint *point = &npoints[i];
1047
1048                 if (point->uw)
1049                         point->uw = MEM_dupallocN(point->uw);
1050         }
1051
1052         return npoints;
1053 }
1054
1055 MaskSpline *BKE_mask_spline_copy(MaskSpline *spline)
1056 {
1057         MaskSpline *nspline = MEM_callocN(sizeof(MaskSpline), "new spline");
1058
1059         *nspline = *spline;
1060
1061         nspline->points_deform = NULL;
1062         nspline->points = mask_spline_points_copy(spline->points, spline->tot_point);
1063
1064         if (spline->points_deform) {
1065                 nspline->points_deform = mask_spline_points_copy(spline->points_deform, spline->tot_point);
1066         }
1067
1068         return nspline;
1069 }
1070
1071 /* note: does NOT add to the list */
1072 MaskLayerShape *BKE_mask_layer_shape_alloc(MaskLayer *masklay, const int frame)
1073 {
1074         MaskLayerShape *masklay_shape;
1075         int tot_vert = BKE_mask_layer_shape_totvert(masklay);
1076
1077         masklay_shape = MEM_mallocN(sizeof(MaskLayerShape), __func__);
1078         masklay_shape->frame = frame;
1079         masklay_shape->tot_vert = tot_vert;
1080         masklay_shape->data = MEM_mallocN(tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, __func__);
1081
1082         return masklay_shape;
1083 }
1084
1085 void BKE_mask_layer_shape_free(MaskLayerShape *masklay_shape)
1086 {
1087         MEM_freeN(masklay_shape->data);
1088
1089         MEM_freeN(masklay_shape);
1090 }
1091
1092 /** \brief Free all animation keys for a mask layer
1093  */
1094 void BKE_mask_layer_free_shapes(MaskLayer *masklay)
1095 {
1096         MaskLayerShape *masklay_shape;
1097
1098         /* free animation data */
1099         masklay_shape = masklay->splines_shapes.first;
1100         while (masklay_shape) {
1101                 MaskLayerShape *next_masklay_shape = masklay_shape->next;
1102
1103                 BLI_remlink(&masklay->splines_shapes, masklay_shape);
1104                 BKE_mask_layer_shape_free(masklay_shape);
1105
1106                 masklay_shape = next_masklay_shape;
1107         }
1108 }
1109
1110 void BKE_mask_layer_free(MaskLayer *masklay)
1111 {
1112         MaskSpline *spline;
1113
1114         /* free splines */
1115         spline = masklay->splines.first;
1116         while (spline) {
1117                 MaskSpline *next_spline = spline->next;
1118
1119                 BLI_remlink(&masklay->splines, spline);
1120                 BKE_mask_spline_free(spline);
1121
1122                 spline = next_spline;
1123         }
1124
1125         /* free animation data */
1126         BKE_mask_layer_free_shapes(masklay);
1127
1128         MEM_freeN(masklay);
1129 }
1130
1131
1132 void BKE_mask_layer_free_list(ListBase *masklayers)
1133 {
1134         MaskLayer *masklay = masklayers->first;
1135
1136         while (masklay) {
1137                 MaskLayer *masklay_next = masklay->next;
1138
1139                 BLI_remlink(masklayers, masklay);
1140                 BKE_mask_layer_free(masklay);
1141
1142                 masklay = masklay_next;
1143         }
1144
1145 }
1146
1147 #ifdef USE_MANGO_MASK_CACHE_HACK
1148 void BKE_mask_raster_cache_free(Mask *mask)
1149 {
1150         MaskRasterCache *cache = mask->raster_cache;
1151
1152         if (cache) {
1153                 MaskLayer *layer;
1154
1155                 layer = cache->layers.first;
1156                 while (layer) {
1157                         MaskLayer *layer_next = layer->next;
1158
1159                         BKE_mask_layer_free(layer);
1160                         layer = layer_next;
1161                 }
1162
1163                 MEM_freeN(cache->buffer);
1164                 MEM_freeN(cache);
1165
1166                 mask->raster_cache = NULL;
1167         }
1168 }
1169 #endif
1170
1171 void BKE_mask_free(Mask *mask)
1172 {
1173         BKE_mask_layer_free_list(&mask->masklayers);
1174
1175 #ifdef USE_MANGO_MASK_CACHE_HACK
1176         if (mask->raster_cache) {
1177                 BKE_mask_raster_cache_free(mask);
1178
1179                 mask->raster_cache = NULL;
1180         }
1181 #endif
1182 }
1183
1184 void BKE_mask_unlink(Main *bmain, Mask *mask)
1185 {
1186         bScreen *scr;
1187         ScrArea *area;
1188         SpaceLink *sl;
1189
1190         for (scr = bmain->screen.first; scr; scr = scr->id.next) {
1191                 for (area = scr->areabase.first; area; area = area->next) {
1192                         for (sl = area->spacedata.first; sl; sl = sl->next) {
1193                                 if (sl->spacetype == SPACE_CLIP) {
1194                                         SpaceClip *sc = (SpaceClip *) sl;
1195
1196                                         if (sc->mask == mask)
1197                                                 sc->mask = NULL;
1198                                 }
1199                         }
1200                 }
1201         }
1202
1203         mask->id.us = 0;
1204 }
1205
1206 void BKE_mask_coord_from_movieclip(MovieClip *clip, MovieClipUser *user, float r_co[2], const float co[2])
1207 {
1208         int width, height;
1209
1210         /* scaling for the clip */
1211         BKE_movieclip_get_size(clip, user, &width, &height);
1212
1213         if (width == height) {
1214                 r_co[0] = co[0];
1215                 r_co[1] = co[1];
1216         }
1217         else if (width < height) {
1218                 r_co[0] = ((co[0] - 0.5f) * ((float)width / (float)height)) + 0.5f;
1219                 r_co[1] = co[1];
1220         }
1221         else { /* (width > height) */
1222                 r_co[0] = co[0];
1223                 r_co[1] = ((co[1] - 0.5f) * ((float)height / (float)width)) + 0.5f;
1224         }
1225 }
1226
1227 /* as above but divide */
1228 void BKE_mask_coord_to_movieclip(MovieClip *clip, MovieClipUser *user, float r_co[2], const float co[2])
1229 {
1230         int width, height;
1231
1232         /* scaling for the clip */
1233         BKE_movieclip_get_size(clip, user, &width, &height);
1234
1235         if (width == height) {
1236                 r_co[0] = co[0];
1237                 r_co[1] = co[1];
1238         }
1239         else if (width < height) {
1240                 r_co[0] = ((co[0] - 0.5f) / ((float)width / (float)height)) + 0.5f;
1241                 r_co[1] = co[1];
1242         }
1243         else { /* (width > height) */
1244                 r_co[0] = co[0];
1245                 r_co[1] = ((co[1] - 0.5f) / ((float)height / (float)width)) + 0.5f;
1246         }
1247 }
1248
1249 static int BKE_mask_evaluate_parent(MaskParent *parent, float ctime, float r_co[2])
1250 {
1251         if (!parent)
1252                 return FALSE;
1253
1254         if (parent->id_type == ID_MC) {
1255                 if (parent->id) {
1256                         MovieClip *clip = (MovieClip *) parent->id;
1257                         MovieTracking *tracking = (MovieTracking *) &clip->tracking;
1258                         MovieTrackingObject *ob = BKE_tracking_object_get_named(tracking, parent->parent);
1259
1260                         if (ob) {
1261                                 MovieTrackingTrack *track = BKE_tracking_track_get_named(tracking, ob, parent->sub_parent);
1262                                 float clip_framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, ctime);
1263
1264                                 MovieClipUser user = {0};
1265                                 user.framenr = ctime;
1266
1267                                 if (track) {
1268                                         MovieTrackingMarker *marker = BKE_tracking_marker_get(track, clip_framenr);
1269                                         float marker_pos_ofs[2];
1270                                         add_v2_v2v2(marker_pos_ofs, marker->pos, track->offset);
1271                                         BKE_mask_coord_from_movieclip(clip, &user, r_co, marker_pos_ofs);
1272
1273                                         return TRUE;
1274                                 }
1275                         }
1276                 }
1277         }
1278
1279         return FALSE;
1280 }
1281
1282 int BKE_mask_evaluate_parent_delta(MaskParent *parent, float ctime, float r_delta[2])
1283 {
1284         float parent_co[2];
1285
1286         if (BKE_mask_evaluate_parent(parent, ctime, parent_co)) {
1287                 sub_v2_v2v2(r_delta, parent_co, parent->parent_orig);
1288                 return TRUE;
1289         }
1290         else {
1291                 return FALSE;
1292         }
1293 }
1294
1295 static void mask_calc_point_handle(MaskSplinePoint *point, MaskSplinePoint *point_prev, MaskSplinePoint *point_next)
1296 {
1297         BezTriple *bezt = &point->bezt;
1298         BezTriple *bezt_prev = NULL, *bezt_next = NULL;
1299         //int handle_type = bezt->h1;
1300
1301         if (point_prev)
1302                 bezt_prev = &point_prev->bezt;
1303
1304         if (point_next)
1305                 bezt_next = &point_next->bezt;
1306
1307 #if 1
1308         if (bezt_prev || bezt_next) {
1309                 BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
1310         }
1311 #else
1312         if (handle_type == HD_VECT) {
1313                 BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
1314         }
1315         else if (handle_type == HD_AUTO) {
1316                 BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
1317         }
1318         else if (handle_type == HD_ALIGN) {
1319                 float v1[3], v2[3];
1320                 float vec[3], h[3];
1321
1322                 sub_v3_v3v3(v1, bezt->vec[0], bezt->vec[1]);
1323                 sub_v3_v3v3(v2, bezt->vec[2], bezt->vec[1]);
1324                 add_v3_v3v3(vec, v1, v2);
1325
1326                 if (len_v3(vec) > 1e-3) {
1327                         h[0] = vec[1];
1328                         h[1] = -vec[0];
1329                         h[2] = 0.0f;
1330                 }
1331                 else {
1332                         copy_v3_v3(h, v1);
1333                 }
1334
1335                 add_v3_v3v3(bezt->vec[0], bezt->vec[1], h);
1336                 sub_v3_v3v3(bezt->vec[2], bezt->vec[1], h);
1337         }
1338 #endif
1339 }
1340
1341 void BKE_mask_get_handle_point_adjacent(MaskSpline *spline, MaskSplinePoint *point,
1342                                         MaskSplinePoint **r_point_prev, MaskSplinePoint **r_point_next)
1343 {
1344         /* TODO, could avoid calling this at such low level */
1345         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
1346
1347         *r_point_prev = mask_spline_point_prev(spline, points_array, point);
1348         *r_point_next = mask_spline_point_next(spline, points_array, point);
1349 }
1350
1351 /* calculates the tanget of a point by its previous and next
1352  * (ignoring handles - as if its a poly line) */
1353 void BKE_mask_calc_tangent_polyline(MaskSpline *spline, MaskSplinePoint *point, float t[2])
1354 {
1355         float tvec_a[2], tvec_b[2];
1356
1357         MaskSplinePoint *point_prev, *point_next;
1358
1359         BKE_mask_get_handle_point_adjacent(spline, point,
1360                                            &point_prev, &point_next);
1361
1362         if (point_prev) {
1363                 sub_v2_v2v2(tvec_a, point->bezt.vec[1], point_prev->bezt.vec[1]);
1364                 normalize_v2(tvec_a);
1365         }
1366         else {
1367                 zero_v2(tvec_a);
1368         }
1369
1370         if (point_next) {
1371                 sub_v2_v2v2(tvec_b, point_next->bezt.vec[1], point->bezt.vec[1]);
1372                 normalize_v2(tvec_b);
1373         }
1374         else {
1375                 zero_v2(tvec_b);
1376         }
1377
1378         add_v2_v2v2(t, tvec_a, tvec_b);
1379         normalize_v2(t);
1380 }
1381
1382 void BKE_mask_calc_handle_point(MaskSpline *spline, MaskSplinePoint *point)
1383 {
1384         MaskSplinePoint *point_prev, *point_next;
1385
1386         BKE_mask_get_handle_point_adjacent(spline, point,
1387                                            &point_prev, &point_next);
1388
1389         mask_calc_point_handle(point, point_prev, point_next);
1390 }
1391
1392 static void enforce_dist_v2_v2fl(float v1[2], const float v2[2], const float dist)
1393 {
1394         if (!equals_v2v2(v2, v1)) {
1395                 float nor[2];
1396
1397                 sub_v2_v2v2(nor, v1, v2);
1398                 normalize_v2(nor);
1399                 madd_v2_v2v2fl(v1, v2, nor, dist);
1400         }
1401 }
1402
1403 void BKE_mask_calc_handle_adjacent_interp(MaskSpline *spline, MaskSplinePoint *point, const float u)
1404 {
1405         /* TODO! - make this interpolate between siblings - not always midpoint! */
1406         int length_tot = 0;
1407         float length_average = 0.0f;
1408         float weight_average = 0.0f;
1409
1410
1411         MaskSplinePoint *point_prev, *point_next;
1412
1413         BLI_assert(u >= 0.0f && u <= 1.0f);
1414
1415         BKE_mask_get_handle_point_adjacent(spline, point,
1416                                            &point_prev, &point_next);
1417
1418         if (point_prev && point_next) {
1419                 length_average = ((len_v2v2(point_prev->bezt.vec[0], point_prev->bezt.vec[1]) * (1.0f - u)) +
1420                                   (len_v2v2(point_next->bezt.vec[2], point_next->bezt.vec[1]) * u));
1421
1422                 weight_average = (point_prev->bezt.weight * (1.0f - u) +
1423                                   point_next->bezt.weight * u);
1424                 length_tot = 1;
1425         }
1426         else {
1427                 if (point_prev) {
1428                         length_average += len_v2v2(point_prev->bezt.vec[0], point_prev->bezt.vec[1]);
1429                         weight_average += point_prev->bezt.weight;
1430                         length_tot++;
1431                 }
1432
1433                 if (point_next) {
1434                         length_average += len_v2v2(point_next->bezt.vec[2], point_next->bezt.vec[1]);
1435                         weight_average += point_next->bezt.weight;
1436                         length_tot++;
1437                 }
1438         }
1439
1440         if (length_tot) {
1441                 length_average /= (float)length_tot;
1442                 weight_average /= (float)length_tot;
1443
1444                 enforce_dist_v2_v2fl(point->bezt.vec[0], point->bezt.vec[1], length_average);
1445                 enforce_dist_v2_v2fl(point->bezt.vec[2], point->bezt.vec[1], length_average);
1446                 point->bezt.weight = weight_average;
1447         }
1448 }
1449
1450
1451 /**
1452  * \brief Resets auto handles even for non-auto bezier points
1453  *
1454  * Useful for giving sane defaults.
1455  */
1456 void BKE_mask_calc_handle_point_auto(MaskSpline *spline, MaskSplinePoint *point,
1457                                      const short do_recalc_length)
1458 {
1459         MaskSplinePoint *point_prev, *point_next;
1460         const char h_back[2] = {point->bezt.h1, point->bezt.h2};
1461         const float length_average = (do_recalc_length) ? 0.0f /* dummy value */ :
1462                                      (len_v3v3(point->bezt.vec[0], point->bezt.vec[1]) +
1463                                       len_v3v3(point->bezt.vec[1], point->bezt.vec[2])) / 2.0f;
1464
1465         BKE_mask_get_handle_point_adjacent(spline, point,
1466                                            &point_prev, &point_next);
1467
1468         point->bezt.h1 = HD_AUTO;
1469         point->bezt.h2 = HD_AUTO;
1470         mask_calc_point_handle(point, point_prev, point_next);
1471
1472         point->bezt.h1 = h_back[0];
1473         point->bezt.h2 = h_back[1];
1474
1475         /* preserve length by applying it back */
1476         if (do_recalc_length == FALSE) {
1477                 enforce_dist_v2_v2fl(point->bezt.vec[0], point->bezt.vec[1], length_average);
1478                 enforce_dist_v2_v2fl(point->bezt.vec[2], point->bezt.vec[1], length_average);
1479         }
1480 }
1481
1482 void BKE_mask_layer_calc_handles(MaskLayer *masklay)
1483 {
1484         MaskSpline *spline;
1485         for (spline = masklay->splines.first; spline; spline = spline->next) {
1486                 int i;
1487                 for (i = 0; i < spline->tot_point; i++) {
1488                         BKE_mask_calc_handle_point(spline, &spline->points[i]);
1489                 }
1490         }
1491 }
1492
1493 void BKE_mask_layer_calc_handles_deform(MaskLayer *masklay)
1494 {
1495         MaskSpline *spline;
1496         for (spline = masklay->splines.first; spline; spline = spline->next) {
1497                 int i;
1498                 for (i = 0; i < spline->tot_point; i++) {
1499                         BKE_mask_calc_handle_point(spline, &spline->points_deform[i]);
1500                 }
1501         }
1502 }
1503
1504 void BKE_mask_calc_handles(Mask *mask)
1505 {
1506         MaskLayer *masklay;
1507         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1508                 BKE_mask_layer_calc_handles(masklay);
1509         }
1510 }
1511
1512 void BKE_mask_update_deform(Mask *mask)
1513 {
1514         MaskLayer *masklay;
1515
1516         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1517                 MaskSpline *spline;
1518
1519                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1520                         int i;
1521
1522                         for (i = 0; i < spline->tot_point; i++) {
1523                                 const int i_prev = (i - 1) % spline->tot_point;
1524                                 const int i_next = (i + 1) % spline->tot_point;
1525
1526                                 BezTriple *bezt_prev = &spline->points[i_prev].bezt;
1527                                 BezTriple *bezt      = &spline->points[i].bezt;
1528                                 BezTriple *bezt_next = &spline->points[i_next].bezt;
1529
1530                                 BezTriple *bezt_def_prev = &spline->points_deform[i_prev].bezt;
1531                                 BezTriple *bezt_def      = &spline->points_deform[i].bezt;
1532                                 BezTriple *bezt_def_next = &spline->points_deform[i_next].bezt;
1533
1534                                 float w_src[4];
1535                                 int j;
1536
1537                                 for (j = 0; j <= 2; j += 2) { /* (0, 2) */
1538                                         printf("--- %d %d, %d, %d\n", i, j, i_prev, i_next);
1539                                         barycentric_weights_v2(bezt_prev->vec[1], bezt->vec[1], bezt_next->vec[1],
1540                                                                bezt->vec[j], w_src);
1541                                         interp_v3_v3v3v3(bezt_def->vec[j],
1542                                                          bezt_def_prev->vec[1], bezt_def->vec[1], bezt_def_next->vec[1], w_src);
1543                                 }
1544                         }
1545                 }
1546         }
1547 }
1548
1549 void BKE_mask_spline_ensure_deform(MaskSpline *spline)
1550 {
1551         int allocated_points = (MEM_allocN_len(spline->points_deform) / sizeof(*spline->points_deform));
1552         // printf("SPLINE ALLOC %p %d\n", spline->points_deform, allocated_points);
1553
1554         if (spline->points_deform == NULL || allocated_points != spline->tot_point) {
1555                 // printf("alloc new deform spline\n");
1556
1557                 if (spline->points_deform) {
1558                         int i;
1559
1560                         for (i = 0; i < allocated_points; i++) {
1561                                 MaskSplinePoint *point = &spline->points_deform[i];
1562                                 BKE_mask_point_free(point);
1563                         }
1564
1565                         MEM_freeN(spline->points_deform);
1566                 }
1567
1568                 spline->points_deform = MEM_callocN(sizeof(*spline->points_deform) * spline->tot_point, __func__);
1569         }
1570         else {
1571                 // printf("alloc spline done\n");
1572         }
1573 }
1574
1575 void BKE_mask_layer_evaluate(MaskLayer *masklay, const float ctime, const int do_newframe)
1576 {
1577         /* animation if available */
1578         if (do_newframe) {
1579                 MaskLayerShape *masklay_shape_a;
1580                 MaskLayerShape *masklay_shape_b;
1581                 int found;
1582
1583                 if ((found = BKE_mask_layer_shape_find_frame_range(masklay, ctime,
1584                                                                    &masklay_shape_a, &masklay_shape_b)))
1585                 {
1586                         if (found == 1) {
1587 #if 0
1588                                 printf("%s: exact %d %d (%d)\n", __func__, (int)ctime, BLI_countlist(&masklay->splines_shapes),
1589                                        masklay_shape_a->frame);
1590 #endif
1591
1592                                 BKE_mask_layer_shape_to_mask(masklay, masklay_shape_a);
1593                         }
1594                         else if (found == 2) {
1595                                 float w = masklay_shape_b->frame - masklay_shape_a->frame;
1596 #if 0
1597                                 printf("%s: tween %d %d (%d %d)\n", __func__, (int)ctime, BLI_countlist(&masklay->splines_shapes),
1598                                        masklay_shape_a->frame, masklay_shape_b->frame);
1599 #endif
1600                                 BKE_mask_layer_shape_to_mask_interp(masklay, masklay_shape_a, masklay_shape_b,
1601                                                                     (ctime - masklay_shape_a->frame) / w);
1602                         }
1603                         else {
1604                                 /* always fail, should never happen */
1605                                 BLI_assert(found == 2);
1606                         }
1607                 }
1608         }
1609         /* animation done... */
1610
1611         BKE_mask_layer_calc_handles(masklay);
1612
1613         /* update deform */
1614         {
1615                 MaskSpline *spline;
1616
1617                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1618                         int i;
1619                         int has_auto = FALSE;
1620
1621                         BKE_mask_spline_ensure_deform(spline);
1622
1623                         for (i = 0; i < spline->tot_point; i++) {
1624                                 MaskSplinePoint *point = &spline->points[i];
1625                                 MaskSplinePoint *point_deform = &spline->points_deform[i];
1626                                 float delta[2];
1627
1628                                 BKE_mask_point_free(point_deform);
1629
1630                                 *point_deform = *point;
1631                                 point_deform->uw = point->uw ? MEM_dupallocN(point->uw) : NULL;
1632
1633                                 if (BKE_mask_evaluate_parent_delta(&point->parent, ctime, delta)) {
1634                                         add_v2_v2(point_deform->bezt.vec[0], delta);
1635                                         add_v2_v2(point_deform->bezt.vec[1], delta);
1636                                         add_v2_v2(point_deform->bezt.vec[2], delta);
1637                                 }
1638
1639                                 if (point->bezt.h1 == HD_AUTO) {
1640                                         has_auto = TRUE;
1641                                 }
1642                         }
1643
1644                         /* if the spline has auto handles, these need to be recalculated after deformation */
1645                         if (has_auto) {
1646                                 for (i = 0; i < spline->tot_point; i++) {
1647                                         MaskSplinePoint *point_deform = &spline->points_deform[i];
1648                                         if (point_deform->bezt.h1 == HD_AUTO) {
1649                                                 BKE_mask_calc_handle_point(spline, point_deform);
1650                                         }
1651                                 }
1652                         }
1653                         /* end extra calc handles loop */
1654                 }
1655         }
1656 }
1657
1658 void BKE_mask_evaluate(Mask *mask, const float ctime, const int do_newframe)
1659 {
1660         MaskLayer *masklay;
1661
1662         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1663                 BKE_mask_layer_evaluate(masklay, ctime, do_newframe);
1664         }
1665 }
1666
1667 /* the purpose of this function is to ensure spline->points_deform is never out of date.
1668  * for now re-evaluate all. eventually this might work differently */
1669 void BKE_mask_update_display(Mask *mask, float ctime)
1670 {
1671 #if 0
1672         MaskLayer *masklay;
1673
1674         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1675                 MaskSpline *spline;
1676
1677                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1678                         if (spline->points_deform) {
1679                                 int i = 0;
1680
1681                                 for (i = 0; i < spline->tot_point; i++) {
1682                                         MaskSplinePoint *point;
1683
1684                                         if (spline->points_deform) {
1685                                                 point = &spline->points_deform[i];
1686                                                 BKE_mask_point_free(point);
1687                                         }
1688                                 }
1689                                 if (spline->points_deform) {
1690                                         MEM_freeN(spline->points_deform);
1691                                 }
1692
1693                                 spline->points_deform = NULL;
1694                         }
1695                 }
1696         }
1697 #endif
1698
1699         BKE_mask_evaluate(mask, ctime, FALSE);
1700 }
1701
1702 void BKE_mask_evaluate_all_masks(Main *bmain, float ctime, const int do_newframe)
1703 {
1704         Mask *mask;
1705
1706         for (mask = bmain->mask.first; mask; mask = mask->id.next) {
1707                 BKE_mask_evaluate(mask, ctime, do_newframe);
1708         }
1709 }
1710
1711 void BKE_mask_update_scene(Main *bmain, Scene *scene, const int do_newframe)
1712 {
1713         Mask *mask;
1714
1715         for (mask = bmain->mask.first; mask; mask = mask->id.next) {
1716                 if (mask->id.flag & LIB_ID_RECALC) {
1717                         BKE_mask_evaluate_all_masks(bmain, CFRA, do_newframe);
1718                 }
1719         }
1720 }
1721
1722 void BKE_mask_parent_init(MaskParent *parent)
1723 {
1724         parent->id_type = ID_MC;
1725 }
1726
1727
1728 /* *** own animation/shapekey implimentation ***
1729  * BKE_mask_layer_shape_XXX */
1730
1731 int BKE_mask_layer_shape_totvert(MaskLayer *masklay)
1732 {
1733         int tot = 0;
1734         MaskSpline *spline;
1735
1736         for (spline = masklay->splines.first; spline; spline = spline->next) {
1737                 tot += spline->tot_point;
1738         }
1739
1740         return tot;
1741 }
1742
1743 static void mask_layer_shape_from_mask_point(BezTriple *bezt, float fp[MASK_OBJECT_SHAPE_ELEM_SIZE])
1744 {
1745         copy_v2_v2(&fp[0], bezt->vec[0]);
1746         copy_v2_v2(&fp[2], bezt->vec[1]);
1747         copy_v2_v2(&fp[4], bezt->vec[2]);
1748         fp[6] = bezt->weight;
1749         fp[7] = bezt->radius;
1750 }
1751
1752 static void mask_layer_shape_to_mask_point(BezTriple *bezt, float fp[MASK_OBJECT_SHAPE_ELEM_SIZE])
1753 {
1754         copy_v2_v2(bezt->vec[0], &fp[0]);
1755         copy_v2_v2(bezt->vec[1], &fp[2]);
1756         copy_v2_v2(bezt->vec[2], &fp[4]);
1757         bezt->weight = fp[6];
1758         bezt->radius = fp[7];
1759 }
1760
1761 /* these functions match. copy is swapped */
1762 void BKE_mask_layer_shape_from_mask(MaskLayer *masklay, MaskLayerShape *masklay_shape)
1763 {
1764         int tot = BKE_mask_layer_shape_totvert(masklay);
1765
1766         if (masklay_shape->tot_vert == tot) {
1767                 float *fp = masklay_shape->data;
1768
1769                 MaskSpline *spline;
1770                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1771                         int i;
1772                         for (i = 0; i < spline->tot_point; i++) {
1773                                 mask_layer_shape_from_mask_point(&spline->points[i].bezt, fp);
1774                                 fp += MASK_OBJECT_SHAPE_ELEM_SIZE;
1775                         }
1776                 }
1777         }
1778         else {
1779                 printf("%s: vert mismatch %d != %d (frame %d)\n",
1780                        __func__, masklay_shape->tot_vert, tot, masklay_shape->frame);
1781         }
1782 }
1783
1784 void BKE_mask_layer_shape_to_mask(MaskLayer *masklay, MaskLayerShape *masklay_shape)
1785 {
1786         int tot = BKE_mask_layer_shape_totvert(masklay);
1787
1788         if (masklay_shape->tot_vert == tot) {
1789                 float *fp = masklay_shape->data;
1790
1791                 MaskSpline *spline;
1792                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1793                         int i;
1794                         for (i = 0; i < spline->tot_point; i++) {
1795                                 mask_layer_shape_to_mask_point(&spline->points[i].bezt, fp);
1796                                 fp += MASK_OBJECT_SHAPE_ELEM_SIZE;
1797                         }
1798                 }
1799         }
1800         else {
1801                 printf("%s: vert mismatch %d != %d (frame %d)\n",
1802                        __func__, masklay_shape->tot_vert, tot, masklay_shape->frame);
1803         }
1804 }
1805
1806 BLI_INLINE void interp_v2_v2v2_flfl(float target[2], const float a[2], const float b[2],
1807                                     const float t, const float s)
1808 {
1809         target[0] = s * a[0] + t * b[0];
1810         target[1] = s * a[1] + t * b[1];
1811 }
1812
1813 /* linear interpolation only */
1814 void BKE_mask_layer_shape_to_mask_interp(MaskLayer *masklay,
1815                                          MaskLayerShape *masklay_shape_a,
1816                                          MaskLayerShape *masklay_shape_b,
1817                                          const float fac)
1818 {
1819         int tot = BKE_mask_layer_shape_totvert(masklay);
1820         if (masklay_shape_a->tot_vert == tot && masklay_shape_b->tot_vert == tot) {
1821                 float *fp_a = masklay_shape_a->data;
1822                 float *fp_b = masklay_shape_b->data;
1823                 const float ifac = 1.0f - fac;
1824
1825                 MaskSpline *spline;
1826                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1827                         int i;
1828                         for (i = 0; i < spline->tot_point; i++) {
1829                                 BezTriple *bezt = &spline->points[i].bezt;
1830                                 /* *** BKE_mask_layer_shape_from_mask - swapped *** */
1831                                 interp_v2_v2v2_flfl(bezt->vec[0], fp_a, fp_b, fac, ifac); fp_a += 2; fp_b += 2;
1832                                 interp_v2_v2v2_flfl(bezt->vec[1], fp_a, fp_b, fac, ifac); fp_a += 2; fp_b += 2;
1833                                 interp_v2_v2v2_flfl(bezt->vec[2], fp_a, fp_b, fac, ifac); fp_a += 2; fp_b += 2;
1834                                 bezt->weight = (fp_a[0] * ifac) + (fp_b[0] * fac);
1835                                 bezt->radius = (fp_a[1] * ifac) + (fp_b[1] * fac); fp_a += 2; fp_b += 2;
1836                         }
1837                 }
1838         }
1839         else {
1840                 printf("%s: vert mismatch %d != %d != %d (frame %d - %d)\n",
1841                        __func__, masklay_shape_a->tot_vert, masklay_shape_b->tot_vert, tot,
1842                        masklay_shape_a->frame, masklay_shape_b->frame);
1843         }
1844 }
1845
1846 MaskLayerShape *BKE_mask_layer_shape_find_frame(MaskLayer *masklay, const int frame)
1847 {
1848         MaskLayerShape *masklay_shape;
1849
1850         for (masklay_shape = masklay->splines_shapes.first;
1851              masklay_shape;
1852              masklay_shape = masklay_shape->next)
1853         {
1854                 if (frame == masklay_shape->frame) {
1855                         return masklay_shape;
1856                 }
1857                 else if (frame < masklay_shape->frame) {
1858                         break;
1859                 }
1860         }
1861
1862         return NULL;
1863 }
1864
1865 /* when returning 2 - the frame isnt found but before/after frames are */
1866 int BKE_mask_layer_shape_find_frame_range(MaskLayer *masklay, const float frame,
1867                                           MaskLayerShape **r_masklay_shape_a,
1868                                           MaskLayerShape **r_masklay_shape_b)
1869 {
1870         MaskLayerShape *masklay_shape;
1871
1872         for (masklay_shape = masklay->splines_shapes.first;
1873              masklay_shape;
1874              masklay_shape = masklay_shape->next)
1875         {
1876                 if (frame == masklay_shape->frame) {
1877                         *r_masklay_shape_a = masklay_shape;
1878                         *r_masklay_shape_b = NULL;
1879                         return 1;
1880                 }
1881                 else if (frame < masklay_shape->frame) {
1882                         if (masklay_shape->prev) {
1883                                 *r_masklay_shape_a = masklay_shape->prev;
1884                                 *r_masklay_shape_b = masklay_shape;
1885                                 return 2;
1886                         }
1887                         else {
1888                                 *r_masklay_shape_a = masklay_shape;
1889                                 *r_masklay_shape_b = NULL;
1890                                 return 1;
1891                         }
1892                 }
1893         }
1894
1895         if ((masklay_shape = masklay->splines_shapes.last)) {
1896                 *r_masklay_shape_a = masklay_shape;
1897                 *r_masklay_shape_b = NULL;
1898                 return 1;
1899         }
1900         else {
1901                 *r_masklay_shape_a = NULL;
1902                 *r_masklay_shape_b = NULL;
1903
1904                 return 0;
1905         }
1906 }
1907
1908 MaskLayerShape *BKE_mask_layer_shape_varify_frame(MaskLayer *masklay, const int frame)
1909 {
1910         MaskLayerShape *masklay_shape;
1911
1912         masklay_shape = BKE_mask_layer_shape_find_frame(masklay, frame);
1913
1914         if (masklay_shape == NULL) {
1915                 masklay_shape = BKE_mask_layer_shape_alloc(masklay, frame);
1916                 BLI_addtail(&masklay->splines_shapes, masklay_shape);
1917                 BKE_mask_layer_shape_sort(masklay);
1918         }
1919
1920 #if 0
1921         {
1922                 MaskLayerShape *masklay_shape;
1923                 int i = 0;
1924                 for (masklay_shape = masklay->splines_shapes.first;
1925                      masklay_shape;
1926                      masklay_shape = masklay_shape->next)
1927                 {
1928                         printf("mask %d, %d\n", i++, masklay_shape->frame);
1929                 }
1930         }
1931 #endif
1932
1933         return masklay_shape;
1934 }
1935
1936 MaskLayerShape *BKE_mask_layer_shape_duplicate(MaskLayerShape *masklay_shape)
1937 {
1938         MaskLayerShape *masklay_shape_copy;
1939
1940         masklay_shape_copy = MEM_dupallocN(masklay_shape);
1941
1942         if (LIKELY(masklay_shape_copy->data)) {
1943                 masklay_shape_copy->data = MEM_dupallocN(masklay_shape_copy->data);
1944         }
1945
1946         return masklay_shape_copy;
1947 }
1948
1949 void BKE_mask_layer_shape_unlink(MaskLayer *masklay, MaskLayerShape *masklay_shape)
1950 {
1951         BLI_remlink(&masklay->splines_shapes, masklay_shape);
1952
1953         BKE_mask_layer_shape_free(masklay_shape);
1954 }
1955
1956 static int mask_layer_shape_sort_cb(void *masklay_shape_a_ptr, void *masklay_shape_b_ptr)
1957 {
1958         MaskLayerShape *masklay_shape_a = (MaskLayerShape *)masklay_shape_a_ptr;
1959         MaskLayerShape *masklay_shape_b = (MaskLayerShape *)masklay_shape_b_ptr;
1960
1961         if      (masklay_shape_a->frame < masklay_shape_b->frame)  return -1;
1962         else if (masklay_shape_a->frame > masklay_shape_b->frame)  return  1;
1963         else                                                       return  0;
1964 }
1965
1966 void BKE_mask_layer_shape_sort(MaskLayer *masklay)
1967 {
1968         BLI_sortlist(&masklay->splines_shapes, mask_layer_shape_sort_cb);
1969 }
1970
1971 int BKE_mask_layer_shape_spline_from_index(MaskLayer *masklay, int index,
1972                                            MaskSpline **r_masklay_shape, int *r_index)
1973 {
1974         MaskSpline *spline;
1975
1976         for (spline = masklay->splines.first; spline; spline = spline->next) {
1977                 if (index < spline->tot_point) {
1978                         *r_masklay_shape = spline;
1979                         *r_index = index;
1980                         return TRUE;
1981                 }
1982                 index -= spline->tot_point;
1983         }
1984
1985         return FALSE;
1986 }
1987
1988 int BKE_mask_layer_shape_spline_to_index(MaskLayer *masklay, MaskSpline *spline)
1989 {
1990         MaskSpline *spline_iter;
1991         int i_abs = 0;
1992         for (spline_iter = masklay->splines.first;
1993              spline_iter && spline_iter != spline;
1994              i_abs += spline_iter->tot_point, spline_iter = spline_iter->next)
1995         {
1996                 /* pass */
1997         }
1998
1999         return i_abs;
2000 }
2001
2002 /* basic 2D interpolation functions, could make more comprehensive later */
2003 static void interp_weights_uv_v2_calc(float r_uv[2], const float pt[2], const float pt_a[2], const float pt_b[2])
2004 {
2005         float pt_on_line[2];
2006         r_uv[0] = closest_to_line_v2(pt_on_line, pt, pt_a, pt_b);
2007         r_uv[1] = (len_v2v2(pt_on_line, pt) / len_v2v2(pt_a, pt_b)) *
2008                   ((line_point_side_v2(pt_a, pt_b, pt) < 0.0f) ? -1.0 : 1.0);  /* this line only sets the sign */
2009 }
2010
2011
2012 static void interp_weights_uv_v2_apply(const float uv[2], float r_pt[2], const float pt_a[2], const float pt_b[2])
2013 {
2014         const float dvec[2] = {pt_b[0] - pt_a[0],
2015                                pt_b[1] - pt_a[1]};
2016
2017         /* u */
2018         madd_v2_v2v2fl(r_pt, pt_a, dvec, uv[0]);
2019
2020         /* v */
2021         r_pt[0] += -dvec[1] * uv[1];
2022         r_pt[1] +=  dvec[0] * uv[1];
2023 }
2024
2025 /* when a now points added - resize all shapekey array  */
2026 void BKE_mask_layer_shape_changed_add(MaskLayer *masklay, int index,
2027                                       int do_init, int do_init_interpolate)
2028 {
2029         MaskLayerShape *masklay_shape;
2030
2031         /* spline index from masklay */
2032         MaskSpline *spline;
2033         int spline_point_index;
2034
2035         if (BKE_mask_layer_shape_spline_from_index(masklay, index,
2036                                                    &spline, &spline_point_index))
2037         {
2038                 /* sanity check */
2039                 /* the point has already been removed in this array so subtract one when comparing with the shapes */
2040                 int tot = BKE_mask_layer_shape_totvert(masklay) - 1;
2041
2042                 /* for interpolation */
2043                 /* TODO - assumes closed curve for now */
2044                 float uv[3][2]; /* 3x 2D handles */
2045                 const int pi_curr =   spline_point_index;
2046                 const int pi_prev = ((spline_point_index - 1) + spline->tot_point) % spline->tot_point;
2047                 const int pi_next =  (spline_point_index + 1)                      % spline->tot_point;
2048
2049                 const int index_offset = index - spline_point_index;
2050                 /* const int pi_curr_abs = index; */
2051                 const int pi_prev_abs = pi_prev + index_offset;
2052                 const int pi_next_abs = pi_next + index_offset;
2053
2054                 int i;
2055                 if (do_init_interpolate) {
2056                         for (i = 0; i < 3; i++) {
2057                                 interp_weights_uv_v2_calc(uv[i],
2058                                                           spline->points[pi_curr].bezt.vec[i],
2059                                                           spline->points[pi_prev].bezt.vec[i],
2060                                                           spline->points[pi_next].bezt.vec[i]);
2061                         }
2062                 }
2063
2064                 for (masklay_shape = masklay->splines_shapes.first;
2065                      masklay_shape;
2066                      masklay_shape = masklay_shape->next)
2067                 {
2068                         if (tot == masklay_shape->tot_vert) {
2069                                 float *data_resized;
2070
2071                                 masklay_shape->tot_vert++;
2072                                 data_resized = MEM_mallocN(masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, __func__);
2073                                 if (index > 0) {
2074                                         memcpy(data_resized,
2075                                                masklay_shape->data,
2076                                                index * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2077                                 }
2078
2079                                 if (index != masklay_shape->tot_vert - 1) {
2080                                         memcpy(&data_resized[(index + 1) * MASK_OBJECT_SHAPE_ELEM_SIZE],
2081                                                masklay_shape->data + (index * MASK_OBJECT_SHAPE_ELEM_SIZE),
2082                                                (masklay_shape->tot_vert - (index + 1)) * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2083                                 }
2084
2085                                 if (do_init) {
2086                                         float *fp = &data_resized[index * MASK_OBJECT_SHAPE_ELEM_SIZE];
2087
2088                                         mask_layer_shape_from_mask_point(&spline->points[spline_point_index].bezt, fp);
2089
2090                                         if (do_init_interpolate && spline->tot_point > 2) {
2091                                                 for (i = 0; i < 3; i++) {
2092                                                         interp_weights_uv_v2_apply(uv[i],
2093                                                                                    &fp[i * 2],
2094                                                                                    &data_resized[(pi_prev_abs * MASK_OBJECT_SHAPE_ELEM_SIZE) + (i * 2)],
2095                                                                                    &data_resized[(pi_next_abs * MASK_OBJECT_SHAPE_ELEM_SIZE) + (i * 2)]);
2096                                                 }
2097                                         }
2098                                 }
2099                                 else {
2100                                         memset(&data_resized[index * MASK_OBJECT_SHAPE_ELEM_SIZE],
2101                                                0,
2102                                                sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2103                                 }
2104
2105                                 MEM_freeN(masklay_shape->data);
2106                                 masklay_shape->data = data_resized;
2107                         }
2108                         else {
2109                                 printf("%s: vert mismatch %d != %d (frame %d)\n",
2110                                        __func__, masklay_shape->tot_vert, tot, masklay_shape->frame);
2111                         }
2112                 }
2113         }
2114 }
2115
2116
2117 /* move array to account for removed point */
2118 void BKE_mask_layer_shape_changed_remove(MaskLayer *masklay, int index, int count)
2119 {
2120         MaskLayerShape *masklay_shape;
2121
2122         /* the point has already been removed in this array so add one when comparing with the shapes */
2123         int tot = BKE_mask_layer_shape_totvert(masklay);
2124
2125         for (masklay_shape = masklay->splines_shapes.first;
2126              masklay_shape;
2127              masklay_shape = masklay_shape->next)
2128         {
2129                 if (tot == masklay_shape->tot_vert - count) {
2130                         float *data_resized;
2131
2132                         masklay_shape->tot_vert -= count;
2133                         data_resized = MEM_mallocN(masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, __func__);
2134                         if (index > 0) {
2135                                 memcpy(data_resized,
2136                                        masklay_shape->data,
2137                                        index * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2138                         }
2139
2140                         if (index != masklay_shape->tot_vert) {
2141                                 memcpy(&data_resized[index * MASK_OBJECT_SHAPE_ELEM_SIZE],
2142                                        masklay_shape->data + ((index + count) * MASK_OBJECT_SHAPE_ELEM_SIZE),
2143                                        (masklay_shape->tot_vert - index) * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2144                         }
2145
2146                         MEM_freeN(masklay_shape->data);
2147                         masklay_shape->data = data_resized;
2148                 }
2149                 else {
2150                         printf("%s: vert mismatch %d != %d (frame %d)\n",
2151                                __func__, masklay_shape->tot_vert - count, tot, masklay_shape->frame);
2152                 }
2153         }
2154 }
2155
2156 /* local functions */
2157 static void invert_vn_vn(float *array, const int size)
2158 {
2159         float *arr = array + (size - 1);
2160         int i = size;
2161         while (i--) {
2162                 *(arr) = 1.0f - *(arr);
2163                 arr--;
2164         }
2165 }
2166
2167 static void m_invert_vn_vn(float *array, const float f, const int size)
2168 {
2169         float *arr = array + (size - 1);
2170         int i = size;
2171         while (i--) {
2172                 *(arr) = 1.0f - (*(arr) * f);
2173                 arr--;
2174         }
2175 }
2176
2177 static void clamp_vn_vn(float *array, const int size)
2178 {
2179         float *arr = array + (size - 1);
2180
2181         int i = size;
2182         while (i--) {
2183                 if      (*arr < 0.0f) *arr = 0.0f;
2184                 else if (*arr > 1.0f) *arr = 1.0f;
2185                 arr--;
2186         }
2187 }
2188
2189 int BKE_mask_get_duration(Mask *mask)
2190 {
2191         return MAX2(1, mask->efra - mask->sfra);
2192 }
2193
2194 #ifdef USE_MANGO_MASK_CACHE_HACK
2195 static int mask_point_compare(MaskSplinePoint *point_a, MaskSplinePoint *point_b)
2196 {
2197         if (point_a->tot_uw != point_b->tot_uw) {
2198                 return FALSE;
2199         }
2200
2201         if (memcmp(&point_a->bezt, &point_b->bezt, sizeof(BezTriple))) {
2202                 return FALSE;
2203         }
2204
2205         if (memcmp(&point_a->uw, &point_b->uw, 2 * point_a->tot_uw * sizeof(float))) {
2206                 return FALSE;
2207         }
2208
2209         return TRUE;
2210 }
2211
2212 static int mask_points_compare(MaskSplinePoint *points_a, MaskSplinePoint *points_b, int tot_point)
2213 {
2214         MaskSplinePoint *point_a = points_a;
2215         MaskSplinePoint *point_b = points_b;
2216         int a = tot_point;
2217
2218         /* deform points can be NULL */
2219         if (point_a == NULL || point_b == NULL) {
2220                 return ((point_a == NULL) && (point_b == NULL));
2221         }
2222
2223         while (a--) {
2224                 if (!mask_point_compare(point_a, point_b)) {
2225                         return FALSE;
2226                 }
2227
2228                 point_a++;
2229                 point_b++;
2230         }
2231
2232         return TRUE;
2233 }
2234
2235 static int mask_spline_compare(MaskSpline *spline_a, MaskSpline *spline_b)
2236 {
2237         if (spline_a->flag != spline_b->flag ||
2238             spline_a->tot_point != spline_b->tot_point ||
2239             spline_a->weight_interp != spline_b->weight_interp)
2240         {
2241                 return FALSE;
2242         }
2243
2244         if (!mask_points_compare(spline_a->points, spline_b->points, spline_a->tot_point)) {
2245                 return FALSE;
2246         }
2247
2248         return mask_points_compare(spline_a->points_deform, spline_b->points_deform, spline_a->tot_point);
2249 }
2250
2251 static int mask_splines_compare(ListBase *base_a, ListBase *base_b)
2252 {
2253         MaskSpline *spline_a, *spline_b;
2254
2255         for (spline_a = base_a->first, spline_b = base_b->first;
2256              spline_a && spline_b;
2257              spline_a = spline_a->next, spline_b = spline_b->next)
2258         {
2259                 if (!mask_spline_compare(spline_a, spline_b)) {
2260                         return FALSE;
2261                 }
2262         }
2263
2264         if (spline_a || spline_b)
2265                 return FALSE;
2266
2267         return TRUE;
2268 }
2269
2270 static int mask_layer_compare(MaskLayer *layer_a, MaskLayer *layer_b)
2271 {
2272         if (layer_a->alpha != layer_b->alpha ||
2273             layer_a->blend != layer_b->blend ||
2274             layer_a->blend_flag != layer_b->blend_flag ||
2275             layer_a->flag != layer_b->flag ||
2276             layer_a->restrictflag != layer_b->restrictflag)
2277         {
2278                 return FALSE;
2279         }
2280
2281         if (strcmp(layer_a->name, layer_b->name))
2282                 return FALSE;
2283
2284         return mask_splines_compare(&layer_a->splines, &layer_b->splines);
2285 }
2286
2287 static int mask_layers_compare(ListBase *base_a, ListBase *base_b)
2288 {
2289         MaskLayer *layer_a, *layer_b;
2290
2291         for (layer_a = base_a->first, layer_b = base_b->first;
2292              layer_a && layer_b;
2293              layer_a = layer_a->next, layer_b = layer_b->next)
2294         {
2295                 if (!mask_layer_compare(layer_a, layer_b)) {
2296                         return FALSE;
2297                 }
2298         }
2299
2300         if (layer_a || layer_b)
2301                 return FALSE;
2302
2303         return TRUE;
2304 }
2305 #endif
2306
2307 /* rasterization */
2308
2309 /* XXX: mask is only passed here to access rasterization cache
2310  *      this MUST be removed as soon as tile-based rasterization would be here
2311  */
2312 void BKE_mask_rasterize_layers(Mask *mask, ListBase *masklayers, int width, int height, float *buffer,
2313                                const short do_aspect_correct, const short do_mask_aa,
2314                                const short do_feather)
2315 {
2316         MaskRasterCache *cache = mask->raster_cache;
2317         MaskLayer *masklay;
2318
2319         /* temp blending buffer */
2320         const int buffer_size = width * height;
2321         float *buffer_tmp;
2322
2323 #ifdef USE_MANGO_MASK_CACHE_HACK
2324         if (cache &&
2325             cache->width == width &&
2326             cache->height == height &&
2327             cache->do_aspect_correct == do_aspect_correct &&
2328             cache->do_mask_aa == do_mask_aa &&
2329             cache->do_feather == do_feather &&
2330             mask_layers_compare(&cache->layers, &mask->masklayers))
2331         {
2332                 memcpy(buffer, cache->buffer, sizeof(float) * buffer_size);
2333                 return;
2334         }
2335
2336         BKE_mask_raster_cache_free(mask);
2337 #endif
2338
2339         buffer_tmp = MEM_mallocN(sizeof(float) * buffer_size, __func__);
2340
2341         for (masklay = masklayers->first; masklay; masklay = masklay->next) {
2342                 MaskSpline *spline;
2343                 float alpha;
2344
2345                 if (masklay->restrictflag & MASK_RESTRICT_RENDER) {
2346                         continue;
2347                 }
2348
2349                 memset(buffer_tmp, 0, sizeof(float) * buffer_size);
2350
2351                 for (spline = masklay->splines.first; spline; spline = spline->next) {
2352                         float (*diff_points)[2];
2353                         int tot_diff_point;
2354
2355                         float (*diff_feather_points)[2];
2356                         int tot_diff_feather_points;
2357
2358                         diff_points = BKE_mask_spline_differentiate_with_resolution(spline, width, height,
2359                                                                                     &tot_diff_point);
2360
2361                         if (tot_diff_point) {
2362                                 if (do_feather) {
2363                                         diff_feather_points =
2364                                                 BKE_mask_spline_feather_differentiated_points_with_resolution(spline, width, height,
2365                                                                                                               &tot_diff_feather_points);
2366                                 }
2367                                 else {
2368                                         tot_diff_feather_points = 0;
2369                                         diff_feather_points = NULL;
2370                                 }
2371
2372                                 if (do_aspect_correct) {
2373                                         if (width != height) {
2374                                                 float *fp;
2375                                                 float *ffp;
2376                                                 int i;
2377                                                 float asp;
2378
2379                                                 if (width < height) {
2380                                                         fp = &diff_points[0][0];
2381                                                         ffp = tot_diff_feather_points ? &diff_feather_points[0][0] : NULL;
2382                                                         asp = (float)width / (float)height;
2383                                                 }
2384                                                 else {
2385                                                         fp = &diff_points[0][1];
2386                                                         ffp = tot_diff_feather_points ? &diff_feather_points[0][1] : NULL;
2387                                                         asp = (float)height / (float)width;
2388                                                 }
2389
2390                                                 for (i = 0; i < tot_diff_point; i++, fp += 2) {
2391                                                         (*fp) = (((*fp) - 0.5f) / asp) + 0.5f;
2392                                                 }
2393
2394                                                 if (tot_diff_feather_points) {
2395                                                         for (i = 0; i < tot_diff_feather_points; i++, ffp += 2) {
2396                                                                 (*ffp) = (((*ffp) - 0.5f) / asp) + 0.5f;
2397                                                         }
2398                                                 }
2399                                         }
2400                                 }
2401
2402                                 if (tot_diff_point) {
2403                                         PLX_raskterize(diff_points, tot_diff_point,
2404                                                        buffer_tmp, width, height, do_mask_aa);
2405
2406                                         if (tot_diff_feather_points) {
2407                                                 PLX_raskterize_feather(diff_points, tot_diff_point,
2408                                                                        diff_feather_points, tot_diff_feather_points,
2409                                                                        buffer_tmp, width, height);
2410                                                 MEM_freeN(diff_feather_points);
2411                                         }
2412
2413                                         MEM_freeN(diff_points);
2414                                 }
2415                         }
2416                 }
2417
2418                 /* blend with original */
2419                 if (masklay->blend_flag & MASK_BLENDFLAG_INVERT) {
2420                         /* apply alpha multiply before inverting */
2421                         if (masklay->alpha != 1.0f) {
2422                                 m_invert_vn_vn(buffer_tmp, masklay->alpha, buffer_size);
2423                         }
2424                         else {
2425                                 invert_vn_vn(buffer_tmp, buffer_size);
2426                         }
2427
2428                         alpha = 1.0f;
2429                 }
2430                 else {
2431                         alpha = masklay->alpha;
2432                 }
2433
2434                 switch (masklay->blend) {
2435                         case MASK_BLEND_SUBTRACT:
2436                         {
2437                                 if (alpha == 1.0f) {
2438                                         sub_vn_vn(buffer, buffer_tmp, buffer_size);
2439                                 }
2440                                 else {
2441                                         msub_vn_vn(buffer, buffer_tmp, alpha, buffer_size);
2442                                 }
2443                                 break;
2444                         }
2445                         case MASK_BLEND_ADD:
2446                         default:
2447                         {
2448                                 if (alpha == 1.0f) {
2449                                         add_vn_vn(buffer, buffer_tmp, buffer_size);
2450                                 }
2451                                 else {
2452                                         madd_vn_vn(buffer, buffer_tmp, alpha, buffer_size);
2453                                 }
2454                                 break;
2455                         }
2456                 }
2457
2458                 /* clamp at the end */
2459                 clamp_vn_vn(buffer, buffer_size);
2460         }
2461
2462         MEM_freeN(buffer_tmp);
2463
2464 #ifdef USE_MANGO_MASK_CACHE_HACK
2465         cache = MEM_callocN(sizeof(MaskRasterCache), "mask raster cache");
2466
2467         cache->buffer = MEM_mallocN(sizeof(float) * buffer_size, "mask raster cache buffer");
2468
2469         BKE_mask_layer_copy_list(&cache->layers, masklayers);
2470
2471         memcpy(cache->buffer, buffer, sizeof(float) * buffer_size);
2472
2473         cache->width = width;
2474         cache->height = height;
2475         cache->do_aspect_correct = do_aspect_correct;
2476         cache->do_mask_aa = do_mask_aa;
2477         cache->do_feather = do_feather;
2478
2479         mask->raster_cache = cache;
2480 #endif
2481 }
2482
2483 void BKE_mask_rasterize(Mask *mask, int width, int height, float *buffer,
2484                         const short do_aspect_correct, const short do_mask_aa,
2485                         const short do_feather)
2486 {
2487         BKE_mask_rasterize_layers(mask, &mask->masklayers, width, height, buffer, do_aspect_correct, do_mask_aa, do_feather);
2488 }