Implement asymmetric and free handles type for masks
[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  *                 Campbell Barton
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/mask.c
29  *  \ingroup bke
30  */
31
32 #include <stddef.h>
33 #include <string.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "BLI_utildefines.h"
38 #include "BLI_ghash.h"
39 #include "BLI_path_util.h"
40 #include "BLI_string.h"
41 #include "BLI_listbase.h"
42 #include "BLI_math.h"
43
44 #include "BLF_translation.h"
45
46 #include "DNA_mask_types.h"
47 #include "DNA_node_types.h"
48 #include "DNA_screen_types.h"
49 #include "DNA_space_types.h"
50 #include "DNA_sequence_types.h"
51
52 #include "BKE_curve.h"
53 #include "BKE_global.h"
54 #include "BKE_library.h"
55 #include "BKE_main.h"
56 #include "BKE_mask.h"
57 #include "BKE_node.h"
58 #include "BKE_sequencer.h"
59 #include "BKE_tracking.h"
60 #include "BKE_movieclip.h"
61 #include "BKE_image.h"
62
63 #include "NOD_composite.h"
64
65 static struct {
66         ListBase splines;
67         struct GHash *id_hash;
68 } mask_clipboard = {{NULL}};
69
70 static MaskSplinePoint *mask_spline_point_next(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
71 {
72         if (point == &points_array[spline->tot_point - 1]) {
73                 if (spline->flag & MASK_SPLINE_CYCLIC) {
74                         return &points_array[0];
75                 }
76                 else {
77                         return NULL;
78                 }
79         }
80         else {
81                 return point + 1;
82         }
83 }
84
85 static MaskSplinePoint *mask_spline_point_prev(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
86 {
87         if (point == points_array) {
88                 if (spline->flag & MASK_SPLINE_CYCLIC) {
89                         return &points_array[spline->tot_point - 1];
90                 }
91                 else {
92                         return NULL;
93                 }
94         }
95         else {
96                 return point - 1;
97         }
98 }
99
100 BezTriple *BKE_mask_spline_point_next_bezt(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
101 {
102         if (point == &points_array[spline->tot_point - 1]) {
103                 if (spline->flag & MASK_SPLINE_CYCLIC) {
104                         return &(points_array[0].bezt);
105                 }
106                 else {
107                         return NULL;
108                 }
109         }
110         else {
111                 return &((point + 1))->bezt;
112         }
113 }
114
115 MaskSplinePoint *BKE_mask_spline_point_array(MaskSpline *spline)
116 {
117         return spline->points_deform ? spline->points_deform : spline->points;
118 }
119
120 MaskSplinePoint *BKE_mask_spline_point_array_from_point(MaskSpline *spline, MaskSplinePoint *point_ref)
121 {
122         if ((point_ref >= spline->points) && (point_ref < &spline->points[spline->tot_point])) {
123                 return spline->points;
124         }
125
126         if ((point_ref >= spline->points_deform) && (point_ref < &spline->points_deform[spline->tot_point])) {
127                 return spline->points_deform;
128         }
129
130         BLI_assert(!"wrong array");
131         return NULL;
132 }
133
134 /* mask layers */
135
136 MaskLayer *BKE_mask_layer_new(Mask *mask, const char *name)
137 {
138         MaskLayer *masklay = MEM_callocN(sizeof(MaskLayer), __func__);
139
140         if (name && name[0])
141                 BLI_strncpy(masklay->name, name, sizeof(masklay->name));
142         else
143                 strcpy(masklay->name, "MaskLayer");
144
145         BLI_addtail(&mask->masklayers, masklay);
146
147         BKE_mask_layer_unique_name(mask, masklay);
148
149         mask->masklay_tot++;
150
151         masklay->blend = MASK_BLEND_MERGE_ADD;
152         masklay->alpha = 1.0f;
153         masklay->flag = MASK_LAYERFLAG_FILL_DISCRETE | MASK_LAYERFLAG_FILL_OVERLAP;
154
155         return masklay;
156 }
157
158 /* note: may still be hidden, caller needs to check */
159 MaskLayer *BKE_mask_layer_active(Mask *mask)
160 {
161         return BLI_findlink(&mask->masklayers, mask->masklay_act);
162 }
163
164 void BKE_mask_layer_active_set(Mask *mask, MaskLayer *masklay)
165 {
166         mask->masklay_act = BLI_findindex(&mask->masklayers, masklay);
167 }
168
169 void BKE_mask_layer_remove(Mask *mask, MaskLayer *masklay)
170 {
171         BLI_remlink(&mask->masklayers, masklay);
172         BKE_mask_layer_free(masklay);
173
174         mask->masklay_tot--;
175
176         if (mask->masklay_act >= mask->masklay_tot)
177                 mask->masklay_act = mask->masklay_tot - 1;
178 }
179
180 void BKE_mask_layer_unique_name(Mask *mask, MaskLayer *masklay)
181 {
182         BLI_uniquename(&mask->masklayers, masklay, DATA_("MaskLayer"), '.', offsetof(MaskLayer, name),
183                        sizeof(masklay->name));
184 }
185
186 MaskLayer *BKE_mask_layer_copy(MaskLayer *masklay)
187 {
188         MaskLayer *masklay_new;
189         MaskSpline *spline;
190
191         masklay_new = MEM_callocN(sizeof(MaskLayer), "new mask layer");
192
193         BLI_strncpy(masklay_new->name, masklay->name, sizeof(masklay_new->name));
194
195         masklay_new->alpha = masklay->alpha;
196         masklay_new->blend = masklay->blend;
197         masklay_new->blend_flag = masklay->blend_flag;
198         masklay_new->flag = masklay->flag;
199         masklay_new->restrictflag = masklay->restrictflag;
200
201         for (spline = masklay->splines.first; spline; spline = spline->next) {
202                 MaskSpline *spline_new = BKE_mask_spline_copy(spline);
203
204                 BLI_addtail(&masklay_new->splines, spline_new);
205         }
206
207         /* correct animation */
208         if (masklay->splines_shapes.first) {
209                 MaskLayerShape *masklay_shape;
210                 MaskLayerShape *masklay_shape_new;
211
212                 for (masklay_shape = masklay->splines_shapes.first;
213                      masklay_shape;
214                      masklay_shape = masklay_shape->next)
215                 {
216                         masklay_shape_new = MEM_callocN(sizeof(MaskLayerShape), "new mask layer shape");
217
218                         masklay_shape_new->data = MEM_dupallocN(masklay_shape->data);
219                         masklay_shape_new->tot_vert = masklay_shape->tot_vert;
220                         masklay_shape_new->flag = masklay_shape->flag;
221                         masklay_shape_new->frame = masklay_shape->frame;
222
223                         BLI_addtail(&masklay_new->splines_shapes, masklay_shape_new);
224                 }
225         }
226
227         return masklay_new;
228 }
229
230 void BKE_mask_layer_copy_list(ListBase *masklayers_new, ListBase *masklayers)
231 {
232         MaskLayer *layer;
233
234         for (layer = masklayers->first; layer; layer = layer->next) {
235                 MaskLayer *layer_new = BKE_mask_layer_copy(layer);
236
237                 BLI_addtail(masklayers_new, layer_new);
238         }
239 }
240
241 /* splines */
242
243 MaskSpline *BKE_mask_spline_add(MaskLayer *masklay)
244 {
245         MaskSpline *spline;
246
247         spline = MEM_callocN(sizeof(MaskSpline), "new mask spline");
248         BLI_addtail(&masklay->splines, spline);
249
250         /* spline shall have one point at least */
251         spline->points = MEM_callocN(sizeof(MaskSplinePoint), "new mask spline point");
252         spline->tot_point = 1;
253
254         /* cyclic shapes are more usually used */
255         // spline->flag |= MASK_SPLINE_CYCLIC; // disable because its not so nice for drawing. could be done differently
256
257         spline->weight_interp = MASK_SPLINE_INTERP_EASE;
258
259         BKE_mask_parent_init(&spline->parent);
260
261         return spline;
262 }
263
264 bool BKE_mask_spline_remove(MaskLayer *mask_layer, MaskSpline *spline)
265 {
266         if (BLI_remlink_safe(&mask_layer->splines, spline) == FALSE) {
267                 return false;
268         }
269
270         BKE_mask_spline_free(spline);
271
272         return true;
273 }
274
275 void BKE_mask_point_direction_switch(MaskSplinePoint *point)
276 {
277         const int tot_uw = point->tot_uw;
278         const int tot_uw_half = tot_uw / 2;
279         int i;
280
281         float co_tmp[2];
282
283         /* swap handles */
284         copy_v2_v2(co_tmp, point->bezt.vec[0]);
285         copy_v2_v2(point->bezt.vec[0], point->bezt.vec[2]);
286         copy_v2_v2(point->bezt.vec[2], co_tmp);
287         /* in this case the flags are unlikely to be different but swap anyway */
288         SWAP(char, point->bezt.f1, point->bezt.f3);
289         SWAP(char, point->bezt.h1, point->bezt.h2);
290
291
292         /* swap UW's */
293         if (tot_uw > 1) {
294                 /* count */
295                 for (i = 0; i < tot_uw_half; i++) {
296                         MaskSplinePointUW *uw_a = &point->uw[i];
297                         MaskSplinePointUW *uw_b = &point->uw[tot_uw - (i + 1)];
298                         SWAP(MaskSplinePointUW, *uw_a, *uw_b);
299                 }
300         }
301
302         for (i = 0; i < tot_uw; i++) {
303                 MaskSplinePointUW *uw = &point->uw[i];
304                 uw->u = 1.0f - uw->u;
305         }
306 }
307
308 void BKE_mask_spline_direction_switch(MaskLayer *masklay, MaskSpline *spline)
309 {
310         const int tot_point = spline->tot_point;
311         const int tot_point_half = tot_point / 2;
312         int i, i_prev;
313
314         if (tot_point < 2) {
315                 return;
316         }
317
318         /* count */
319         for (i = 0; i < tot_point_half; i++) {
320                 MaskSplinePoint *point_a = &spline->points[i];
321                 MaskSplinePoint *point_b = &spline->points[tot_point - (i + 1)];
322                 SWAP(MaskSplinePoint, *point_a, *point_b);
323         }
324
325         /* correct UW's */
326         i_prev = tot_point - 1;
327         for (i = 0; i < tot_point; i++) {
328
329                 BKE_mask_point_direction_switch(&spline->points[i]);
330
331                 SWAP(MaskSplinePointUW *, spline->points[i].uw,     spline->points[i_prev].uw);
332                 SWAP(int,                 spline->points[i].tot_uw, spline->points[i_prev].tot_uw);
333
334                 i_prev = i;
335         }
336
337         /* correct animation */
338         if (masklay->splines_shapes.first) {
339                 MaskLayerShape *masklay_shape;
340
341                 const int spline_index = BKE_mask_layer_shape_spline_to_index(masklay, spline);
342
343                 for (masklay_shape = masklay->splines_shapes.first;
344                      masklay_shape;
345                      masklay_shape = masklay_shape->next)
346                 {
347                         MaskLayerShapeElem *fp_arr = (MaskLayerShapeElem *)masklay_shape->data;
348
349                         for (i = 0; i < tot_point_half; i++) {
350                                 MaskLayerShapeElem *fp_a = &fp_arr[spline_index +              (i)     ];
351                                 MaskLayerShapeElem *fp_b = &fp_arr[spline_index + (tot_point - (i + 1))];
352                                 SWAP(MaskLayerShapeElem, *fp_a, *fp_b);
353                         }
354                 }
355         }
356 }
357
358
359 float BKE_mask_spline_project_co(MaskSpline *spline, MaskSplinePoint *point,
360                                  float start_u, const float co[2], const eMaskSign sign)
361 {
362         const float proj_eps    = 1e-3;
363         const float proj_eps_sq = proj_eps * proj_eps;
364         const int N = 1000;
365         float u = -1.0f, du = 1.0f / N, u1 = start_u, u2 = start_u;
366         float ang = -1.0f;
367
368         BLI_assert(ABS(sign) <= 1); /* (-1, 0, 1) */
369
370         while (u1 > 0.0f || u2 < 1.0f) {
371                 float n1[2], n2[2], co1[2], co2[2];
372                 float v1[2], v2[2];
373                 float ang1, ang2;
374
375                 if (u1 >= 0.0f) {
376                         BKE_mask_point_segment_co(spline, point, u1, co1);
377                         BKE_mask_point_normal(spline, point, u1, n1);
378                         sub_v2_v2v2(v1, co, co1);
379
380                         if ((sign == MASK_PROJ_ANY) ||
381                             ((sign == MASK_PROJ_NEG) && (dot_v2v2(v1, n1) <= 0.0f)) ||
382                             ((sign == MASK_PROJ_POS) && (dot_v2v2(v1, n1) >= 0.0f)))
383                         {
384
385                                 if (len_squared_v2(v1) > proj_eps_sq) {
386                                         ang1 = angle_v2v2(v1, n1);
387                                         if (ang1 > (float)M_PI / 2.0f)
388                                                 ang1 = (float)M_PI - ang1;
389
390                                         if (ang < 0.0f || ang1 < ang) {
391                                                 ang = ang1;
392                                                 u = u1;
393                                         }
394                                 }
395                                 else {
396                                         u = u1;
397                                         break;
398                                 }
399                         }
400                 }
401
402                 if (u2 <= 1.0f) {
403                         BKE_mask_point_segment_co(spline, point, u2, co2);
404                         BKE_mask_point_normal(spline, point, u2, n2);
405                         sub_v2_v2v2(v2, co, co2);
406
407                         if ((sign == MASK_PROJ_ANY) ||
408                             ((sign == MASK_PROJ_NEG) && (dot_v2v2(v2, n2) <= 0.0f)) ||
409                             ((sign == MASK_PROJ_POS) && (dot_v2v2(v2, n2) >= 0.0f)))
410                         {
411
412                                 if (len_squared_v2(v2) > proj_eps_sq) {
413                                         ang2 = angle_v2v2(v2, n2);
414                                         if (ang2 > (float)M_PI / 2.0f)
415                                                 ang2 = (float)M_PI - ang2;
416
417                                         if (ang2 < ang) {
418                                                 ang = ang2;
419                                                 u = u2;
420                                         }
421                                 }
422                                 else {
423                                         u = u2;
424                                         break;
425                                 }
426                         }
427                 }
428
429                 u1 -= du;
430                 u2 += du;
431         }
432
433         return u;
434 }
435
436 /* point */
437
438 eMaskhandleMode BKE_mask_point_handles_mode_get(MaskSplinePoint *point)
439 {
440         BezTriple *bezt = &point->bezt;
441
442         if (bezt->h1 == bezt->h2 && bezt->h1 == HD_ALIGN) {
443                 return MASK_HANDLE_MODE_STICK;
444         }
445
446         return MASK_HANDLE_MODE_INDIVIDUAL_HANDLES;
447 }
448
449 void BKE_mask_point_handle(MaskSplinePoint *point, eMaskWhichHandle which_handle, float handle[2])
450 {
451         BezTriple *bezt = &point->bezt;
452
453         if (which_handle == MASK_WHICH_HANDLE_STICK) {
454                 float vec[2];
455
456                 sub_v2_v2v2(vec, bezt->vec[0], bezt->vec[1]);
457
458                 handle[0] = (bezt->vec[1][0] + vec[1]);
459                 handle[1] = (bezt->vec[1][1] - vec[0]);
460         }
461         else if (which_handle == MASK_WHICH_HANDLE_LEFT) {
462                 copy_v2_v2(handle, bezt->vec[0]);
463         }
464         else if (which_handle == MASK_WHICH_HANDLE_RIGHT) {
465                 copy_v2_v2(handle, bezt->vec[2]);
466         }
467         else {
468                 BLI_assert(!"Unknown handle passed to BKE_mask_point_handle");
469         }
470 }
471
472 void BKE_mask_point_set_handle(MaskSplinePoint *point, eMaskWhichHandle which_handle,
473                                float loc[2], bool keep_direction,
474                                float orig_handle[2], float orig_vec[3][3])
475 {
476         BezTriple *bezt = &point->bezt;
477
478         if (which_handle == MASK_WHICH_HANDLE_STICK) {
479                 float v1[2], v2[2], vec[2];
480                 if (keep_direction) {
481                         sub_v2_v2v2(v1, loc, orig_vec[1]);
482                         sub_v2_v2v2(v2, orig_handle, orig_vec[1]);
483
484                         project_v2_v2v2(vec, v1, v2);
485
486                         if (dot_v2v2(v2, vec) > 0) {
487                                 float len = len_v2(vec);
488
489                                 sub_v2_v2v2(v1, orig_vec[0], orig_vec[1]);
490
491                                 mul_v2_fl(v1, len / len_v2(v1));
492
493                                 add_v2_v2v2(bezt->vec[0], bezt->vec[1], v1);
494                                 sub_v2_v2v2(bezt->vec[2], bezt->vec[1], v1);
495                         }
496                         else {
497                                 copy_v3_v3(bezt->vec[0], bezt->vec[1]);
498                                 copy_v3_v3(bezt->vec[2], bezt->vec[1]);
499                         }
500                 }
501                 else {
502                         sub_v2_v2v2(v1, loc, bezt->vec[1]);
503
504                         v2[0] = -v1[1];
505                         v2[1] =  v1[0];
506
507                         add_v2_v2v2(bezt->vec[0], bezt->vec[1], v2);
508                         sub_v2_v2v2(bezt->vec[2], bezt->vec[1], v2);
509                 }
510         }
511         else if (which_handle == MASK_WHICH_HANDLE_LEFT) {
512                 copy_v2_v2(bezt->vec[0], loc);
513         }
514         else if (which_handle == MASK_WHICH_HANDLE_RIGHT) {
515                 copy_v2_v2(bezt->vec[2], loc);
516         }
517         else {
518                 BLI_assert(!"unknown handle passed to BKE_mask_point_set_handle");
519         }
520 }
521
522 void BKE_mask_point_segment_co(MaskSpline *spline, MaskSplinePoint *point, float u, float co[2])
523 {
524         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
525
526         BezTriple *bezt = &point->bezt, *bezt_next;
527         float q0[2], q1[2], q2[2], r0[2], r1[2];
528
529         bezt_next = BKE_mask_spline_point_next_bezt(spline, points_array, point);
530
531         if (!bezt_next) {
532                 copy_v2_v2(co, bezt->vec[1]);
533                 return;
534         }
535
536         interp_v2_v2v2(q0, bezt->vec[1], bezt->vec[2], u);
537         interp_v2_v2v2(q1, bezt->vec[2], bezt_next->vec[0], u);
538         interp_v2_v2v2(q2, bezt_next->vec[0], bezt_next->vec[1], u);
539
540         interp_v2_v2v2(r0, q0, q1, u);
541         interp_v2_v2v2(r1, q1, q2, u);
542
543         interp_v2_v2v2(co, r0, r1, u);
544 }
545
546 BLI_INLINE void orthogonal_direction_get(float vec[2], float result[2])
547 {
548         result[0] = -vec[1];
549         result[1] = vec[0];
550         normalize_v2(result);
551 }
552
553 /* TODO(sergey): This function will re-calculate loads of stuff again and again
554  *               when differentiating feather points. This might be easily cached
555  *               in the callee function for this case.
556  */
557 void BKE_mask_point_normal(MaskSpline *spline, MaskSplinePoint *point, float u, float n[2])
558 {
559
560         MaskSplinePoint *point_prev, *point_next;
561
562         /* TODO(sergey): This actually depends on a resolution. */
563         const float du = 0.05f;
564
565         BKE_mask_get_handle_point_adjacent(spline, point, &point_prev, &point_next);
566
567         if (u - du < 0.0f && point_prev == NULL) {
568                 float co[2], dir[2];
569                 BKE_mask_point_segment_co(spline, point, u + du, co);
570                 sub_v2_v2v2(dir, co, point->bezt.vec[1]);
571                 orthogonal_direction_get(dir, n);
572         }
573         else if (u + du > 1.0f && point_next == NULL) {
574                 float co[2], dir[2];
575                 BKE_mask_point_segment_co(spline, point, u - du, co);
576                 sub_v2_v2v2(dir, point->bezt.vec[1], co);
577                 orthogonal_direction_get(dir, n);
578         }
579         else {
580                 float prev_co[2], next_co[2], co[2];
581                 float dir1[2], dir2[2], dir[2];
582
583                 if (u - du < 0.0f) {
584                         BKE_mask_point_segment_co(spline, point_prev, 1.0f + (u - du), prev_co);
585                 }
586                 else {
587                         BKE_mask_point_segment_co(spline, point, u - du, prev_co);
588                 }
589
590                 BKE_mask_point_segment_co(spline, point, u, co);
591
592                 if (u + du > 1.0f) {
593                         BKE_mask_point_segment_co(spline, point_next, u + du - 1.0f, next_co);
594                 }
595                 else {
596                         BKE_mask_point_segment_co(spline, point, u + du, next_co);
597                 }
598
599                 sub_v2_v2v2(dir1, co, prev_co);
600                 sub_v2_v2v2(dir2, next_co, co);
601
602                 normalize_v2(dir1);
603                 normalize_v2(dir2);
604                 add_v2_v2v2(dir, dir1, dir2);
605
606                 orthogonal_direction_get(dir, n);
607         }
608 }
609
610 static float mask_point_interp_weight(BezTriple *bezt, BezTriple *bezt_next, const float u)
611 {
612         return (bezt->weight * (1.0f - u)) + (bezt_next->weight * u);
613 }
614
615 float BKE_mask_point_weight_scalar(MaskSpline *spline, MaskSplinePoint *point, const float u)
616 {
617         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
618         BezTriple *bezt = &point->bezt, *bezt_next;
619
620         bezt_next = BKE_mask_spline_point_next_bezt(spline, points_array, point);
621
622         if (!bezt_next) {
623                 return bezt->weight;
624         }
625         else if (u <= 0.0f) {
626                 return bezt->weight;
627         }
628         else if (u >= 1.0f) {
629                 return bezt_next->weight;
630         }
631         else {
632                 return mask_point_interp_weight(bezt, bezt_next, u);
633         }
634 }
635
636 float BKE_mask_point_weight(MaskSpline *spline, MaskSplinePoint *point, const float u)
637 {
638         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
639         BezTriple *bezt = &point->bezt, *bezt_next;
640
641         bezt_next = BKE_mask_spline_point_next_bezt(spline, points_array, point);
642
643         if (!bezt_next) {
644                 return bezt->weight;
645         }
646         else if (u <= 0.0f) {
647                 return bezt->weight;
648         }
649         else if (u >= 1.0f) {
650                 return bezt_next->weight;
651         }
652         else {
653                 float cur_u = 0.0f, cur_w = 0.0f, next_u = 0.0f, next_w = 0.0f, fac; /* Quite warnings */
654                 int i;
655
656                 for (i = 0; i <= point->tot_uw; i++) {
657
658                         if (i == 0) {
659                                 cur_u = 0.0f;
660                                 cur_w = 1.0f; /* mask_point_interp_weight will scale it */
661                         }
662                         else {
663                                 cur_u = point->uw[i - 1].u;
664                                 cur_w = point->uw[i - 1].w;
665                         }
666
667                         if (i == point->tot_uw) {
668                                 next_u = 1.0f;
669                                 next_w = 1.0f; /* mask_point_interp_weight will scale it */
670                         }
671                         else {
672                                 next_u = point->uw[i].u;
673                                 next_w = point->uw[i].w;
674                         }
675
676                         if (u >= cur_u && u <= next_u) {
677                                 break;
678                         }
679                 }
680
681                 fac = (u - cur_u) / (next_u - cur_u);
682
683                 cur_w  *= mask_point_interp_weight(bezt, bezt_next, cur_u);
684                 next_w *= mask_point_interp_weight(bezt, bezt_next, next_u);
685
686                 if (spline->weight_interp == MASK_SPLINE_INTERP_EASE) {
687                         return cur_w + (next_w - cur_w) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
688                 }
689                 else {
690                         return (1.0f - fac) * cur_w + fac * next_w;
691                 }
692         }
693 }
694
695 MaskSplinePointUW *BKE_mask_point_sort_uw(MaskSplinePoint *point, MaskSplinePointUW *uw)
696 {
697         if (point->tot_uw > 1) {
698                 int idx = uw - point->uw;
699
700                 if (idx > 0 && point->uw[idx - 1].u > uw->u) {
701                         while (idx > 0 && point->uw[idx - 1].u > point->uw[idx].u) {
702                                 SWAP(MaskSplinePointUW, point->uw[idx - 1], point->uw[idx]);
703                                 idx--;
704                         }
705                 }
706
707                 if (idx < point->tot_uw - 1 && point->uw[idx + 1].u < uw->u) {
708                         while (idx < point->tot_uw - 1 && point->uw[idx + 1].u < point->uw[idx].u) {
709                                 SWAP(MaskSplinePointUW, point->uw[idx + 1], point->uw[idx]);
710                                 idx++;
711                         }
712                 }
713
714                 return &point->uw[idx];
715         }
716
717         return uw;
718 }
719
720 void BKE_mask_point_add_uw(MaskSplinePoint *point, float u, float w)
721 {
722         if (!point->uw)
723                 point->uw = MEM_mallocN(sizeof(*point->uw), "mask point uw");
724         else
725                 point->uw = MEM_reallocN(point->uw, (point->tot_uw + 1) * sizeof(*point->uw));
726
727         point->uw[point->tot_uw].u = u;
728         point->uw[point->tot_uw].w = w;
729         point->uw[point->tot_uw].flag = 0;
730
731         point->tot_uw++;
732
733         BKE_mask_point_sort_uw(point, &point->uw[point->tot_uw - 1]);
734 }
735
736 void BKE_mask_point_select_set(MaskSplinePoint *point, const bool do_select)
737 {
738         int i;
739
740         if (do_select) {
741                 MASKPOINT_SEL_ALL(point);
742         }
743         else {
744                 MASKPOINT_DESEL_ALL(point);
745         }
746
747         for (i = 0; i < point->tot_uw; i++) {
748                 if (do_select) {
749                         point->uw[i].flag |= SELECT;
750                 }
751                 else {
752                         point->uw[i].flag &= ~SELECT;
753                 }
754         }
755 }
756
757 void BKE_mask_point_select_set_handle(MaskSplinePoint *point, const eMaskWhichHandle which_handle, const bool do_select)
758 {
759         if (do_select) {
760                 if (ELEM(which_handle, MASK_WHICH_HANDLE_STICK, MASK_WHICH_HANDLE_BOTH)) {
761                         point->bezt.f1 |= SELECT;
762                         point->bezt.f3 |= SELECT;
763                 }
764                 else if (which_handle == MASK_WHICH_HANDLE_LEFT) {
765                         point->bezt.f1 |= SELECT;
766                 }
767                 else if (which_handle == MASK_WHICH_HANDLE_RIGHT) {
768                         point->bezt.f3 |= SELECT;
769                 }
770                 else {
771                         BLI_assert(!"Wrong which_handle passed to BKE_mask_point_select_set_handle");
772                 }
773         }
774         else {
775                 if (ELEM(which_handle, MASK_WHICH_HANDLE_STICK, MASK_WHICH_HANDLE_BOTH)) {
776                         point->bezt.f1 &= ~SELECT;
777                         point->bezt.f3 &= ~SELECT;
778                 }
779                 else if (which_handle == MASK_WHICH_HANDLE_LEFT) {
780                         point->bezt.f1 &= ~SELECT;
781                 }
782                 else if (which_handle == MASK_WHICH_HANDLE_RIGHT) {
783                         point->bezt.f3 &= ~SELECT;
784                 }
785                 else {
786                         BLI_assert(!"Wrong which_handle passed to BKE_mask_point_select_set_handle");
787                 }
788         }
789 }
790
791 /* only mask block itself */
792 static Mask *mask_alloc(Main *bmain, const char *name)
793 {
794         Mask *mask;
795
796         mask = BKE_libblock_alloc(bmain, ID_MSK, name);
797
798         mask->id.flag |= LIB_FAKEUSER;
799
800         return mask;
801 }
802
803 Mask *BKE_mask_new(Main *bmain, const char *name)
804 {
805         Mask *mask;
806         char mask_name[MAX_ID_NAME - 2];
807
808         if (name && name[0])
809                 BLI_strncpy(mask_name, name, sizeof(mask_name));
810         else
811                 strcpy(mask_name, "Mask");
812
813         mask = mask_alloc(bmain, mask_name);
814
815         /* arbitrary defaults */
816         mask->sfra = 1;
817         mask->efra = 100;
818
819         return mask;
820 }
821
822 /* TODO(sergey): Use generic BKE_libblock_copy_nolib() instead. */
823 Mask *BKE_mask_copy_nolib(Mask *mask)
824 {
825         Mask *mask_new;
826
827         mask_new = MEM_dupallocN(mask);
828
829         /*take care here! - we may want to copy anim data  */
830         mask_new->adt = NULL;
831
832         BLI_listbase_clear(&mask_new->masklayers);
833
834         BKE_mask_layer_copy_list(&mask_new->masklayers, &mask->masklayers);
835
836         /* enable fake user by default */
837         if (!(mask_new->id.flag & LIB_FAKEUSER)) {
838                 mask_new->id.flag |= LIB_FAKEUSER;
839                 mask_new->id.us++;
840         }
841
842         return mask_new;
843 }
844
845 Mask *BKE_mask_copy(Mask *mask)
846 {
847         Mask *mask_new;
848
849         mask_new = BKE_libblock_copy(&mask->id);
850
851         BLI_listbase_clear(&mask_new->masklayers);
852
853         BKE_mask_layer_copy_list(&mask_new->masklayers, &mask->masklayers);
854
855         /* enable fake user by default */
856         if (!(mask_new->id.flag & LIB_FAKEUSER)) {
857                 mask_new->id.flag |= LIB_FAKEUSER;
858                 mask_new->id.us++;
859         }
860
861         return mask_new;
862 }
863
864 void BKE_mask_point_free(MaskSplinePoint *point)
865 {
866         if (point->uw)
867                 MEM_freeN(point->uw);
868 }
869
870 void BKE_mask_spline_free(MaskSpline *spline)
871 {
872         int i = 0;
873
874         for (i = 0; i < spline->tot_point; i++) {
875                 MaskSplinePoint *point;
876                 point = &spline->points[i];
877                 BKE_mask_point_free(point);
878
879                 if (spline->points_deform) {
880                         point = &spline->points_deform[i];
881                         BKE_mask_point_free(point);
882                 }
883         }
884
885         MEM_freeN(spline->points);
886
887         if (spline->points_deform) {
888                 MEM_freeN(spline->points_deform);
889         }
890
891         MEM_freeN(spline);
892 }
893
894 void BKE_mask_spline_free_list(ListBase *splines)
895 {
896         MaskSpline *spline = splines->first;
897         while (spline) {
898                 MaskSpline *next_spline = spline->next;
899
900                 BLI_remlink(splines, spline);
901                 BKE_mask_spline_free(spline);
902
903                 spline = next_spline;
904         }
905 }
906
907 static MaskSplinePoint *mask_spline_points_copy(MaskSplinePoint *points, int tot_point)
908 {
909         MaskSplinePoint *npoints;
910         int i;
911
912         npoints = MEM_dupallocN(points);
913
914         for (i = 0; i < tot_point; i++) {
915                 MaskSplinePoint *point = &npoints[i];
916
917                 if (point->uw)
918                         point->uw = MEM_dupallocN(point->uw);
919         }
920
921         return npoints;
922 }
923
924 MaskSpline *BKE_mask_spline_copy(MaskSpline *spline)
925 {
926         MaskSpline *nspline = MEM_callocN(sizeof(MaskSpline), "new spline");
927
928         *nspline = *spline;
929
930         nspline->points_deform = NULL;
931         nspline->points = mask_spline_points_copy(spline->points, spline->tot_point);
932
933         if (spline->points_deform) {
934                 nspline->points_deform = mask_spline_points_copy(spline->points_deform, spline->tot_point);
935         }
936
937         return nspline;
938 }
939
940 /* note: does NOT add to the list */
941 MaskLayerShape *BKE_mask_layer_shape_alloc(MaskLayer *masklay, const int frame)
942 {
943         MaskLayerShape *masklay_shape;
944         int tot_vert = BKE_mask_layer_shape_totvert(masklay);
945
946         masklay_shape = MEM_mallocN(sizeof(MaskLayerShape), __func__);
947         masklay_shape->frame = frame;
948         masklay_shape->tot_vert = tot_vert;
949         masklay_shape->data = MEM_mallocN(tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, __func__);
950
951         return masklay_shape;
952 }
953
954 void BKE_mask_layer_shape_free(MaskLayerShape *masklay_shape)
955 {
956         if (masklay_shape->data) {
957                 MEM_freeN(masklay_shape->data);
958         }
959
960         MEM_freeN(masklay_shape);
961 }
962
963 /** \brief Free all animation keys for a mask layer
964  */
965 void BKE_mask_layer_free_shapes(MaskLayer *masklay)
966 {
967         MaskLayerShape *masklay_shape;
968
969         /* free animation data */
970         masklay_shape = masklay->splines_shapes.first;
971         while (masklay_shape) {
972                 MaskLayerShape *next_masklay_shape = masklay_shape->next;
973
974                 BLI_remlink(&masklay->splines_shapes, masklay_shape);
975                 BKE_mask_layer_shape_free(masklay_shape);
976
977                 masklay_shape = next_masklay_shape;
978         }
979 }
980
981 void BKE_mask_layer_free(MaskLayer *masklay)
982 {
983         /* free splines */
984         BKE_mask_spline_free_list(&masklay->splines);
985
986         /* free animation data */
987         BKE_mask_layer_free_shapes(masklay);
988
989         MEM_freeN(masklay);
990 }
991
992 void BKE_mask_layer_free_list(ListBase *masklayers)
993 {
994         MaskLayer *masklay = masklayers->first;
995
996         while (masklay) {
997                 MaskLayer *masklay_next = masklay->next;
998
999                 BLI_remlink(masklayers, masklay);
1000                 BKE_mask_layer_free(masklay);
1001
1002                 masklay = masklay_next;
1003         }
1004 }
1005
1006 /** free for temp copy, but don't manage unlinking from other pointers */
1007 void BKE_mask_free_nolib(Mask *mask)
1008 {
1009         BKE_mask_layer_free_list(&mask->masklayers);
1010 }
1011
1012 void BKE_mask_free(Main *bmain, Mask *mask)
1013 {
1014         bScreen *scr;
1015         ScrArea *area;
1016         SpaceLink *sl;
1017         Scene *scene;
1018
1019         for (scr = bmain->screen.first; scr; scr = scr->id.next) {
1020                 for (area = scr->areabase.first; area; area = area->next) {
1021                         for (sl = area->spacedata.first; sl; sl = sl->next) {
1022                                 switch (sl->spacetype) {
1023                                         case SPACE_CLIP:
1024                                         {
1025                                                 SpaceClip *sc = (SpaceClip *)sl;
1026
1027                                                 if (sc->mask_info.mask == mask) {
1028                                                         sc->mask_info.mask = NULL;
1029                                                 }
1030                                                 break;
1031                                         }
1032                                         case SPACE_IMAGE:
1033                                         {
1034                                                 SpaceImage *sima = (SpaceImage *)sl;
1035
1036                                                 if (sima->mask_info.mask == mask) {
1037                                                         sima->mask_info.mask = NULL;
1038                                                 }
1039                                                 break;
1040                                         }
1041                                 }
1042                         }
1043                 }
1044         }
1045
1046         for (scene = bmain->scene.first; scene; scene = scene->id.next) {
1047                 if (scene->ed) {
1048                         Sequence *seq;
1049
1050                         SEQ_BEGIN (scene->ed, seq)
1051                         {
1052                                 if (seq->mask == mask) {
1053                                         seq->mask = NULL;
1054                                 }
1055                         }
1056                         SEQ_END
1057                 }
1058         }
1059
1060         FOREACH_NODETREE(bmain, ntree, id) {
1061                 BKE_node_tree_unlink_id((ID *)mask, ntree);
1062         } FOREACH_NODETREE_END
1063
1064         /* free mask data */
1065         BKE_mask_layer_free_list(&mask->masklayers);
1066 }
1067
1068 void BKE_mask_coord_from_frame(float r_co[2], const float co[2], const float frame_size[2])
1069 {
1070         if (frame_size[0] == frame_size[1]) {
1071                 r_co[0] = co[0];
1072                 r_co[1] = co[1];
1073         }
1074         else if (frame_size[0] < frame_size[1]) {
1075                 r_co[0] = ((co[0] - 0.5f) * (frame_size[0] / frame_size[1])) + 0.5f;
1076                 r_co[1] = co[1];
1077         }
1078         else { /* (frame_size[0] > frame_size[1]) */
1079                 r_co[0] = co[0];
1080                 r_co[1] = ((co[1] - 0.5f) * (frame_size[1] / frame_size[0])) + 0.5f;
1081         }
1082 }
1083
1084 void BKE_mask_coord_from_movieclip(MovieClip *clip, MovieClipUser *user, float r_co[2], const float co[2])
1085 {
1086         float aspx, aspy;
1087         float frame_size[2];
1088
1089         /* scaling for the clip */
1090         BKE_movieclip_get_size_fl(clip, user, frame_size);
1091         BKE_movieclip_get_aspect(clip, &aspx, &aspy);
1092
1093         frame_size[1] *= (aspy / aspx);
1094
1095         BKE_mask_coord_from_frame(r_co, co, frame_size);
1096 }
1097
1098 void BKE_mask_coord_from_image(Image *image, ImageUser *iuser, float r_co[2], const float co[2])
1099 {
1100         float aspx, aspy;
1101         float frame_size[2];
1102
1103         BKE_image_get_size_fl(image, iuser, frame_size);
1104         BKE_image_get_aspect(image, &aspx, &aspy);
1105
1106         frame_size[1] *= (aspy / aspx);
1107
1108         BKE_mask_coord_from_frame(r_co, co, frame_size);
1109 }
1110
1111 /* as above but divide */
1112 void BKE_mask_coord_to_frame(float r_co[2], const float co[2], const float frame_size[2])
1113 {
1114         if (frame_size[0] == frame_size[1]) {
1115                 r_co[0] = co[0];
1116                 r_co[1] = co[1];
1117         }
1118         else if (frame_size[0] < frame_size[1]) {
1119                 r_co[0] = ((co[0] - 0.5f) / (frame_size[0] / frame_size[1])) + 0.5f;
1120                 r_co[1] = co[1];
1121         }
1122         else { /* (frame_size[0] > frame_size[1]) */
1123                 r_co[0] = co[0];
1124                 r_co[1] = ((co[1] - 0.5f) / (frame_size[1] / frame_size[0])) + 0.5f;
1125         }
1126 }
1127
1128 void BKE_mask_coord_to_movieclip(MovieClip *clip, MovieClipUser *user, float r_co[2], const float co[2])
1129 {
1130         float aspx, aspy;
1131         float frame_size[2];
1132
1133         /* scaling for the clip */
1134         BKE_movieclip_get_size_fl(clip, user, frame_size);
1135         BKE_movieclip_get_aspect(clip, &aspx, &aspy);
1136
1137         frame_size[1] /= (aspy / aspx);
1138
1139         BKE_mask_coord_to_frame(r_co, co, frame_size);
1140 }
1141
1142 void BKE_mask_coord_to_image(Image *image, ImageUser *iuser, float r_co[2], const float co[2])
1143 {
1144         float aspx, aspy;
1145         float frame_size[2];
1146
1147         /* scaling for the clip */
1148         BKE_image_get_size_fl(image, iuser, frame_size);
1149         BKE_image_get_aspect(image, &aspx, &aspy);
1150
1151         frame_size[1] /= (aspy / aspx);
1152
1153         BKE_mask_coord_to_frame(r_co, co, frame_size);
1154 }
1155
1156 void BKE_mask_point_parent_matrix_get(MaskSplinePoint *point, float ctime, float parent_matrix[3][3])
1157 {
1158         MaskParent *parent = &point->parent;
1159
1160         unit_m3(parent_matrix);
1161
1162         if (!parent) {
1163                 return;
1164         }
1165
1166         if (parent->id_type == ID_MC) {
1167                 if (parent->id) {
1168                         MovieClip *clip = (MovieClip *) parent->id;
1169                         MovieTracking *tracking = (MovieTracking *) &clip->tracking;
1170                         MovieTrackingObject *ob = BKE_tracking_object_get_named(tracking, parent->parent);
1171
1172                         if (ob) {
1173                                 MovieClipUser user = {0};
1174                                 float clip_framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, ctime);
1175                                 BKE_movieclip_user_set_frame(&user, ctime);
1176
1177                                 if (parent->type == MASK_PARENT_POINT_TRACK) {
1178                                         MovieTrackingTrack *track = BKE_tracking_track_get_named(tracking, ob, parent->sub_parent);
1179
1180                                         if (track) {
1181                                                 float marker_position[2], parent_co[2];
1182                                                 BKE_tracking_marker_get_subframe_position(track, clip_framenr, marker_position);
1183                                                 BKE_mask_coord_from_movieclip(clip, &user, parent_co, marker_position);
1184                                                 sub_v2_v2v2(parent_matrix[2], parent_co, parent->parent_orig);
1185                                         }
1186                                 }
1187                                 else /* if (parent->type == MASK_PARENT_PLANE_TRACK) */ {
1188                                         MovieTrackingPlaneTrack *plane_track = BKE_tracking_plane_track_get_named(tracking, ob, parent->sub_parent);
1189
1190                                         if (plane_track) {
1191                                                 MovieTrackingPlaneMarker *plane_marker = BKE_tracking_plane_marker_get(plane_track, clip_framenr);
1192                                                 float aspx, aspy;
1193                                                 float frame_size[2], H[3][3], mask_from_clip_matrix[3][3], mask_to_clip_matrix[3][3];
1194
1195                                                 BKE_tracking_homography_between_two_quads(parent->parent_corners_orig, plane_marker->corners, H);
1196
1197                                                 unit_m3(mask_from_clip_matrix);
1198
1199                                                 BKE_movieclip_get_size_fl(clip, &user, frame_size);
1200                                                 BKE_movieclip_get_aspect(clip, &aspx, &aspy);
1201
1202                                                 frame_size[1] *= (aspy / aspx);
1203                                                 if (frame_size[0] == frame_size[1]) {
1204                                                         /* pass */
1205                                                 }
1206                                                 else if (frame_size[0] < frame_size[1]) {
1207                                                         mask_from_clip_matrix[0][0] = frame_size[1] / frame_size[0];
1208                                                         mask_from_clip_matrix[2][0] = -0.5f * (frame_size[1] / frame_size[0]) + 0.5f;
1209                                                 }
1210                                                 else { /* (frame_size[0] > frame_size[1]) */
1211                                                         mask_from_clip_matrix[1][1] = frame_size[1] / frame_size[0];
1212                                                         mask_from_clip_matrix[2][1] = -0.5f * (frame_size[1] / frame_size[0]) + 0.5f;
1213                                                 }
1214
1215                                                 invert_m3_m3(mask_to_clip_matrix, mask_from_clip_matrix);
1216                                                 mul_serie_m3(parent_matrix, mask_to_clip_matrix, H, mask_from_clip_matrix, NULL, NULL, NULL, NULL, NULL);
1217                                         }
1218                                 }
1219                         }
1220                 }
1221         }
1222 }
1223
1224 static void mask_evaluate_apply_point_parent(MaskSplinePoint *point, float ctime)
1225 {
1226         float parent_matrix[3][3];
1227
1228         BKE_mask_point_parent_matrix_get(point, ctime, parent_matrix);
1229
1230         mul_m3_v2(parent_matrix, point->bezt.vec[0]);
1231         mul_m3_v2(parent_matrix, point->bezt.vec[1]);
1232         mul_m3_v2(parent_matrix, point->bezt.vec[2]);
1233 }
1234
1235 static void mask_calc_point_handle(MaskSplinePoint *point, MaskSplinePoint *point_prev, MaskSplinePoint *point_next)
1236 {
1237         BezTriple *bezt = &point->bezt;
1238         BezTriple *bezt_prev = NULL, *bezt_next = NULL;
1239         //int handle_type = bezt->h1;
1240
1241         if (point_prev)
1242                 bezt_prev = &point_prev->bezt;
1243
1244         if (point_next)
1245                 bezt_next = &point_next->bezt;
1246
1247 #if 1
1248         if (bezt_prev || bezt_next) {
1249                 BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
1250         }
1251 #else
1252         if (handle_type == HD_VECT) {
1253                 BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
1254         }
1255         else if (handle_type == HD_AUTO) {
1256                 BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
1257         }
1258         else if (handle_type == HD_ALIGN || handle_type == HD_ALIGN_DOUBLESIDE) {
1259                 float v1[3], v2[3];
1260                 float vec[3], h[3];
1261
1262                 sub_v3_v3v3(v1, bezt->vec[0], bezt->vec[1]);
1263                 sub_v3_v3v3(v2, bezt->vec[2], bezt->vec[1]);
1264                 add_v3_v3v3(vec, v1, v2);
1265
1266                 if (len_squared_v3(vec) > (1e-3f * 1e-3f)) {
1267                         h[0] = vec[1];
1268                         h[1] = -vec[0];
1269                         h[2] = 0.0f;
1270                 }
1271                 else {
1272                         copy_v3_v3(h, v1);
1273                 }
1274
1275                 add_v3_v3v3(bezt->vec[0], bezt->vec[1], h);
1276                 sub_v3_v3v3(bezt->vec[2], bezt->vec[1], h);
1277         }
1278 #endif
1279 }
1280
1281 void BKE_mask_get_handle_point_adjacent(MaskSpline *spline, MaskSplinePoint *point,
1282                                         MaskSplinePoint **r_point_prev, MaskSplinePoint **r_point_next)
1283 {
1284         /* TODO, could avoid calling this at such low level */
1285         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
1286
1287         *r_point_prev = mask_spline_point_prev(spline, points_array, point);
1288         *r_point_next = mask_spline_point_next(spline, points_array, point);
1289 }
1290
1291 /* calculates the tangent of a point by its previous and next
1292  * (ignoring handles - as if its a poly line) */
1293 void BKE_mask_calc_tangent_polyline(MaskSpline *spline, MaskSplinePoint *point, float t[2])
1294 {
1295         float tvec_a[2], tvec_b[2];
1296
1297         MaskSplinePoint *point_prev, *point_next;
1298
1299         BKE_mask_get_handle_point_adjacent(spline, point,
1300                                            &point_prev, &point_next);
1301
1302         if (point_prev) {
1303                 sub_v2_v2v2(tvec_a, point->bezt.vec[1], point_prev->bezt.vec[1]);
1304                 normalize_v2(tvec_a);
1305         }
1306         else {
1307                 zero_v2(tvec_a);
1308         }
1309
1310         if (point_next) {
1311                 sub_v2_v2v2(tvec_b, point_next->bezt.vec[1], point->bezt.vec[1]);
1312                 normalize_v2(tvec_b);
1313         }
1314         else {
1315                 zero_v2(tvec_b);
1316         }
1317
1318         add_v2_v2v2(t, tvec_a, tvec_b);
1319         normalize_v2(t);
1320 }
1321
1322 void BKE_mask_calc_handle_point(MaskSpline *spline, MaskSplinePoint *point)
1323 {
1324         MaskSplinePoint *point_prev, *point_next;
1325
1326         BKE_mask_get_handle_point_adjacent(spline, point,
1327                                            &point_prev, &point_next);
1328
1329         mask_calc_point_handle(point, point_prev, point_next);
1330 }
1331
1332 void BKE_mask_calc_handle_adjacent_interp(MaskSpline *spline, MaskSplinePoint *point, const float u)
1333 {
1334         /* TODO! - make this interpolate between siblings - not always midpoint! */
1335         int length_tot = 0;
1336         float length_average = 0.0f;
1337         float weight_average = 0.0f;
1338
1339
1340         MaskSplinePoint *point_prev, *point_next;
1341
1342         BLI_assert(u >= 0.0f && u <= 1.0f);
1343
1344         BKE_mask_get_handle_point_adjacent(spline, point,
1345                                            &point_prev, &point_next);
1346
1347         if (point_prev && point_next) {
1348                 length_average = ((len_v2v2(point_prev->bezt.vec[0], point_prev->bezt.vec[1]) * (1.0f - u)) +
1349                                   (len_v2v2(point_next->bezt.vec[2], point_next->bezt.vec[1]) * u));
1350
1351                 weight_average = (point_prev->bezt.weight * (1.0f - u) +
1352                                   point_next->bezt.weight * u);
1353                 length_tot = 1;
1354         }
1355         else {
1356                 if (point_prev) {
1357                         length_average += len_v2v2(point_prev->bezt.vec[0], point_prev->bezt.vec[1]);
1358                         weight_average += point_prev->bezt.weight;
1359                         length_tot++;
1360                 }
1361
1362                 if (point_next) {
1363                         length_average += len_v2v2(point_next->bezt.vec[2], point_next->bezt.vec[1]);
1364                         weight_average += point_next->bezt.weight;
1365                         length_tot++;
1366                 }
1367         }
1368
1369         if (length_tot) {
1370                 length_average /= (float)length_tot;
1371                 weight_average /= (float)length_tot;
1372
1373                 dist_ensure_v2_v2fl(point->bezt.vec[0], point->bezt.vec[1], length_average);
1374                 dist_ensure_v2_v2fl(point->bezt.vec[2], point->bezt.vec[1], length_average);
1375                 point->bezt.weight = weight_average;
1376         }
1377 }
1378
1379
1380 /**
1381  * \brief Resets auto handles even for non-auto bezier points
1382  *
1383  * Useful for giving sane defaults.
1384  */
1385 void BKE_mask_calc_handle_point_auto(MaskSpline *spline, MaskSplinePoint *point,
1386                                      const bool do_recalc_length)
1387 {
1388         MaskSplinePoint *point_prev, *point_next;
1389         const char h_back[2] = {point->bezt.h1, point->bezt.h2};
1390         const float length_average = (do_recalc_length) ? 0.0f /* dummy value */ :
1391                                      (len_v3v3(point->bezt.vec[0], point->bezt.vec[1]) +
1392                                       len_v3v3(point->bezt.vec[1], point->bezt.vec[2])) / 2.0f;
1393
1394         BKE_mask_get_handle_point_adjacent(spline, point,
1395                                            &point_prev, &point_next);
1396
1397         point->bezt.h1 = HD_AUTO;
1398         point->bezt.h2 = HD_AUTO;
1399         mask_calc_point_handle(point, point_prev, point_next);
1400
1401         point->bezt.h1 = h_back[0];
1402         point->bezt.h2 = h_back[1];
1403
1404         /* preserve length by applying it back */
1405         if (do_recalc_length == FALSE) {
1406                 dist_ensure_v2_v2fl(point->bezt.vec[0], point->bezt.vec[1], length_average);
1407                 dist_ensure_v2_v2fl(point->bezt.vec[2], point->bezt.vec[1], length_average);
1408         }
1409 }
1410
1411 void BKE_mask_layer_calc_handles(MaskLayer *masklay)
1412 {
1413         MaskSpline *spline;
1414         for (spline = masklay->splines.first; spline; spline = spline->next) {
1415                 int i;
1416                 for (i = 0; i < spline->tot_point; i++) {
1417                         BKE_mask_calc_handle_point(spline, &spline->points[i]);
1418                 }
1419         }
1420 }
1421
1422 void BKE_mask_spline_ensure_deform(MaskSpline *spline)
1423 {
1424         int allocated_points = (MEM_allocN_len(spline->points_deform) / sizeof(*spline->points_deform));
1425         // printf("SPLINE ALLOC %p %d\n", spline->points_deform, allocated_points);
1426
1427         if (spline->points_deform == NULL || allocated_points != spline->tot_point) {
1428                 // printf("alloc new deform spline\n");
1429
1430                 if (spline->points_deform) {
1431                         int i;
1432
1433                         for (i = 0; i < allocated_points; i++) {
1434                                 MaskSplinePoint *point = &spline->points_deform[i];
1435                                 BKE_mask_point_free(point);
1436                         }
1437
1438                         MEM_freeN(spline->points_deform);
1439                 }
1440
1441                 spline->points_deform = MEM_callocN(sizeof(*spline->points_deform) * spline->tot_point, __func__);
1442         }
1443         else {
1444                 // printf("alloc spline done\n");
1445         }
1446 }
1447
1448 void BKE_mask_layer_evaluate(MaskLayer *masklay, const float ctime, const bool do_newframe)
1449 {
1450         /* animation if available */
1451         if (do_newframe) {
1452                 MaskLayerShape *masklay_shape_a;
1453                 MaskLayerShape *masklay_shape_b;
1454                 int found;
1455
1456                 if ((found = BKE_mask_layer_shape_find_frame_range(masklay, ctime,
1457                                                                    &masklay_shape_a, &masklay_shape_b)))
1458                 {
1459                         if (found == 1) {
1460 #if 0
1461                                 printf("%s: exact %d %d (%d)\n", __func__, (int)ctime, BLI_countlist(&masklay->splines_shapes),
1462                                        masklay_shape_a->frame);
1463 #endif
1464
1465                                 BKE_mask_layer_shape_to_mask(masklay, masklay_shape_a);
1466                         }
1467                         else if (found == 2) {
1468                                 float w = masklay_shape_b->frame - masklay_shape_a->frame;
1469 #if 0
1470                                 printf("%s: tween %d %d (%d %d)\n", __func__, (int)ctime, BLI_countlist(&masklay->splines_shapes),
1471                                        masklay_shape_a->frame, masklay_shape_b->frame);
1472 #endif
1473                                 BKE_mask_layer_shape_to_mask_interp(masklay, masklay_shape_a, masklay_shape_b,
1474                                                                     (ctime - masklay_shape_a->frame) / w);
1475                         }
1476                         else {
1477                                 /* always fail, should never happen */
1478                                 BLI_assert(found == 2);
1479                         }
1480                 }
1481         }
1482         /* animation done... */
1483
1484         BKE_mask_layer_calc_handles(masklay);
1485
1486         /* update deform */
1487         {
1488                 MaskSpline *spline;
1489
1490                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1491                         int i;
1492                         int need_handle_recalc = FALSE;
1493
1494                         BKE_mask_spline_ensure_deform(spline);
1495
1496                         for (i = 0; i < spline->tot_point; i++) {
1497                                 MaskSplinePoint *point = &spline->points[i];
1498                                 MaskSplinePoint *point_deform = &spline->points_deform[i];
1499
1500                                 BKE_mask_point_free(point_deform);
1501
1502                                 *point_deform = *point;
1503                                 point_deform->uw = point->uw ? MEM_dupallocN(point->uw) : NULL;
1504
1505                                 mask_evaluate_apply_point_parent(point_deform, ctime);
1506
1507                                 if (ELEM(point->bezt.h1, HD_AUTO, HD_VECT)) {
1508                                         need_handle_recalc = TRUE;
1509                                 }
1510                         }
1511
1512                         /* if the spline has auto or vector handles, these need to be recalculated after deformation */
1513                         if (need_handle_recalc) {
1514                                 for (i = 0; i < spline->tot_point; i++) {
1515                                         MaskSplinePoint *point_deform = &spline->points_deform[i];
1516                                         if (ELEM(point_deform->bezt.h1, HD_AUTO, HD_VECT)) {
1517                                                 BKE_mask_calc_handle_point(spline, point_deform);
1518                                         }
1519                                 }
1520                         }
1521                         /* end extra calc handles loop */
1522                 }
1523         }
1524 }
1525
1526 void BKE_mask_evaluate(Mask *mask, const float ctime, const bool do_newframe)
1527 {
1528         MaskLayer *masklay;
1529
1530         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1531                 BKE_mask_layer_evaluate(masklay, ctime, do_newframe);
1532         }
1533 }
1534
1535 /* the purpose of this function is to ensure spline->points_deform is never out of date.
1536  * for now re-evaluate all. eventually this might work differently */
1537 void BKE_mask_update_display(Mask *mask, float ctime)
1538 {
1539 #if 0
1540         MaskLayer *masklay;
1541
1542         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1543                 MaskSpline *spline;
1544
1545                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1546                         if (spline->points_deform) {
1547                                 int i = 0;
1548
1549                                 for (i = 0; i < spline->tot_point; i++) {
1550                                         MaskSplinePoint *point;
1551
1552                                         if (spline->points_deform) {
1553                                                 point = &spline->points_deform[i];
1554                                                 BKE_mask_point_free(point);
1555                                         }
1556                                 }
1557                                 if (spline->points_deform) {
1558                                         MEM_freeN(spline->points_deform);
1559                                 }
1560
1561                                 spline->points_deform = NULL;
1562                         }
1563                 }
1564         }
1565 #endif
1566
1567         BKE_mask_evaluate(mask, ctime, false);
1568 }
1569
1570 void BKE_mask_evaluate_all_masks(Main *bmain, float ctime, const bool do_newframe)
1571 {
1572         Mask *mask;
1573
1574         for (mask = bmain->mask.first; mask; mask = mask->id.next) {
1575                 BKE_mask_evaluate(mask, ctime, do_newframe);
1576         }
1577 }
1578
1579 void BKE_mask_update_scene(Main *bmain, Scene *scene)
1580 {
1581         Mask *mask;
1582
1583         for (mask = bmain->mask.first; mask; mask = mask->id.next) {
1584                 if (mask->id.flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA)) {
1585                         bool do_new_frame = (mask->id.flag & LIB_ID_RECALC_DATA) != 0;
1586                         BKE_mask_evaluate_all_masks(bmain, CFRA, do_new_frame);
1587                 }
1588         }
1589 }
1590
1591 void BKE_mask_parent_init(MaskParent *parent)
1592 {
1593         parent->id_type = ID_MC;
1594 }
1595
1596
1597 /* *** own animation/shapekey implementation ***
1598  * BKE_mask_layer_shape_XXX */
1599
1600 int BKE_mask_layer_shape_totvert(MaskLayer *masklay)
1601 {
1602         int tot = 0;
1603         MaskSpline *spline;
1604
1605         for (spline = masklay->splines.first; spline; spline = spline->next) {
1606                 tot += spline->tot_point;
1607         }
1608
1609         return tot;
1610 }
1611
1612 static void mask_layer_shape_from_mask_point(BezTriple *bezt, float fp[MASK_OBJECT_SHAPE_ELEM_SIZE])
1613 {
1614         copy_v2_v2(&fp[0], bezt->vec[0]);
1615         copy_v2_v2(&fp[2], bezt->vec[1]);
1616         copy_v2_v2(&fp[4], bezt->vec[2]);
1617         fp[6] = bezt->weight;
1618         fp[7] = bezt->radius;
1619 }
1620
1621 static void mask_layer_shape_to_mask_point(BezTriple *bezt, float fp[MASK_OBJECT_SHAPE_ELEM_SIZE])
1622 {
1623         copy_v2_v2(bezt->vec[0], &fp[0]);
1624         copy_v2_v2(bezt->vec[1], &fp[2]);
1625         copy_v2_v2(bezt->vec[2], &fp[4]);
1626         bezt->weight = fp[6];
1627         bezt->radius = fp[7];
1628 }
1629
1630 /* these functions match. copy is swapped */
1631 void BKE_mask_layer_shape_from_mask(MaskLayer *masklay, MaskLayerShape *masklay_shape)
1632 {
1633         int tot = BKE_mask_layer_shape_totvert(masklay);
1634
1635         if (masklay_shape->tot_vert == tot) {
1636                 float *fp = masklay_shape->data;
1637
1638                 MaskSpline *spline;
1639                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1640                         int i;
1641                         for (i = 0; i < spline->tot_point; i++) {
1642                                 mask_layer_shape_from_mask_point(&spline->points[i].bezt, fp);
1643                                 fp += MASK_OBJECT_SHAPE_ELEM_SIZE;
1644                         }
1645                 }
1646         }
1647         else {
1648                 printf("%s: vert mismatch %d != %d (frame %d)\n",
1649                        __func__, masklay_shape->tot_vert, tot, masklay_shape->frame);
1650         }
1651 }
1652
1653 void BKE_mask_layer_shape_to_mask(MaskLayer *masklay, MaskLayerShape *masklay_shape)
1654 {
1655         int tot = BKE_mask_layer_shape_totvert(masklay);
1656
1657         if (masklay_shape->tot_vert == tot) {
1658                 float *fp = masklay_shape->data;
1659
1660                 MaskSpline *spline;
1661                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1662                         int i;
1663                         for (i = 0; i < spline->tot_point; i++) {
1664                                 mask_layer_shape_to_mask_point(&spline->points[i].bezt, fp);
1665                                 fp += MASK_OBJECT_SHAPE_ELEM_SIZE;
1666                         }
1667                 }
1668         }
1669         else {
1670                 printf("%s: vert mismatch %d != %d (frame %d)\n",
1671                        __func__, masklay_shape->tot_vert, tot, masklay_shape->frame);
1672         }
1673 }
1674
1675 BLI_INLINE void interp_v2_v2v2_flfl(float target[2], const float a[2], const float b[2],
1676                                     const float t, const float s)
1677 {
1678         target[0] = s * a[0] + t * b[0];
1679         target[1] = s * a[1] + t * b[1];
1680 }
1681
1682 /* linear interpolation only */
1683 void BKE_mask_layer_shape_to_mask_interp(MaskLayer *masklay,
1684                                          MaskLayerShape *masklay_shape_a,
1685                                          MaskLayerShape *masklay_shape_b,
1686                                          const float fac)
1687 {
1688         int tot = BKE_mask_layer_shape_totvert(masklay);
1689         if (masklay_shape_a->tot_vert == tot && masklay_shape_b->tot_vert == tot) {
1690                 float *fp_a = masklay_shape_a->data;
1691                 float *fp_b = masklay_shape_b->data;
1692                 const float ifac = 1.0f - fac;
1693
1694                 MaskSpline *spline;
1695                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1696                         int i;
1697                         for (i = 0; i < spline->tot_point; i++) {
1698                                 BezTriple *bezt = &spline->points[i].bezt;
1699                                 /* *** BKE_mask_layer_shape_from_mask - swapped *** */
1700                                 interp_v2_v2v2_flfl(bezt->vec[0], fp_a, fp_b, fac, ifac); fp_a += 2; fp_b += 2;
1701                                 interp_v2_v2v2_flfl(bezt->vec[1], fp_a, fp_b, fac, ifac); fp_a += 2; fp_b += 2;
1702                                 interp_v2_v2v2_flfl(bezt->vec[2], fp_a, fp_b, fac, ifac); fp_a += 2; fp_b += 2;
1703                                 bezt->weight = (fp_a[0] * ifac) + (fp_b[0] * fac);
1704                                 bezt->radius = (fp_a[1] * ifac) + (fp_b[1] * fac); fp_a += 2; fp_b += 2;
1705                         }
1706                 }
1707         }
1708         else {
1709                 printf("%s: vert mismatch %d != %d != %d (frame %d - %d)\n",
1710                        __func__, masklay_shape_a->tot_vert, masklay_shape_b->tot_vert, tot,
1711                        masklay_shape_a->frame, masklay_shape_b->frame);
1712         }
1713 }
1714
1715 MaskLayerShape *BKE_mask_layer_shape_find_frame(MaskLayer *masklay, const int frame)
1716 {
1717         MaskLayerShape *masklay_shape;
1718
1719         for (masklay_shape = masklay->splines_shapes.first;
1720              masklay_shape;
1721              masklay_shape = masklay_shape->next)
1722         {
1723                 if (frame == masklay_shape->frame) {
1724                         return masklay_shape;
1725                 }
1726                 else if (frame < masklay_shape->frame) {
1727                         break;
1728                 }
1729         }
1730
1731         return NULL;
1732 }
1733
1734 /* when returning 2 - the frame isnt found but before/after frames are */
1735 int BKE_mask_layer_shape_find_frame_range(MaskLayer *masklay, const float frame,
1736                                           MaskLayerShape **r_masklay_shape_a,
1737                                           MaskLayerShape **r_masklay_shape_b)
1738 {
1739         MaskLayerShape *masklay_shape;
1740
1741         for (masklay_shape = masklay->splines_shapes.first;
1742              masklay_shape;
1743              masklay_shape = masklay_shape->next)
1744         {
1745                 if (frame == masklay_shape->frame) {
1746                         *r_masklay_shape_a = masklay_shape;
1747                         *r_masklay_shape_b = NULL;
1748                         return 1;
1749                 }
1750                 else if (frame < masklay_shape->frame) {
1751                         if (masklay_shape->prev) {
1752                                 *r_masklay_shape_a = masklay_shape->prev;
1753                                 *r_masklay_shape_b = masklay_shape;
1754                                 return 2;
1755                         }
1756                         else {
1757                                 *r_masklay_shape_a = masklay_shape;
1758                                 *r_masklay_shape_b = NULL;
1759                                 return 1;
1760                         }
1761                 }
1762         }
1763
1764         if ((masklay_shape = masklay->splines_shapes.last)) {
1765                 *r_masklay_shape_a = masklay_shape;
1766                 *r_masklay_shape_b = NULL;
1767                 return 1;
1768         }
1769         else {
1770                 *r_masklay_shape_a = NULL;
1771                 *r_masklay_shape_b = NULL;
1772
1773                 return 0;
1774         }
1775 }
1776
1777 MaskLayerShape *BKE_mask_layer_shape_verify_frame(MaskLayer *masklay, const int frame)
1778 {
1779         MaskLayerShape *masklay_shape;
1780
1781         masklay_shape = BKE_mask_layer_shape_find_frame(masklay, frame);
1782
1783         if (masklay_shape == NULL) {
1784                 masklay_shape = BKE_mask_layer_shape_alloc(masklay, frame);
1785                 BLI_addtail(&masklay->splines_shapes, masklay_shape);
1786                 BKE_mask_layer_shape_sort(masklay);
1787         }
1788
1789 #if 0
1790         {
1791                 MaskLayerShape *masklay_shape;
1792                 int i = 0;
1793                 for (masklay_shape = masklay->splines_shapes.first;
1794                      masklay_shape;
1795                      masklay_shape = masklay_shape->next)
1796                 {
1797                         printf("mask %d, %d\n", i++, masklay_shape->frame);
1798                 }
1799         }
1800 #endif
1801
1802         return masklay_shape;
1803 }
1804
1805 MaskLayerShape *BKE_mask_layer_shape_duplicate(MaskLayerShape *masklay_shape)
1806 {
1807         MaskLayerShape *masklay_shape_copy;
1808
1809         masklay_shape_copy = MEM_dupallocN(masklay_shape);
1810
1811         if (LIKELY(masklay_shape_copy->data)) {
1812                 masklay_shape_copy->data = MEM_dupallocN(masklay_shape_copy->data);
1813         }
1814
1815         return masklay_shape_copy;
1816 }
1817
1818 void BKE_mask_layer_shape_unlink(MaskLayer *masklay, MaskLayerShape *masklay_shape)
1819 {
1820         BLI_remlink(&masklay->splines_shapes, masklay_shape);
1821
1822         BKE_mask_layer_shape_free(masklay_shape);
1823 }
1824
1825 static int mask_layer_shape_sort_cb(void *masklay_shape_a_ptr, void *masklay_shape_b_ptr)
1826 {
1827         MaskLayerShape *masklay_shape_a = (MaskLayerShape *)masklay_shape_a_ptr;
1828         MaskLayerShape *masklay_shape_b = (MaskLayerShape *)masklay_shape_b_ptr;
1829
1830         if      (masklay_shape_a->frame < masklay_shape_b->frame)  return -1;
1831         else if (masklay_shape_a->frame > masklay_shape_b->frame)  return  1;
1832         else                                                       return  0;
1833 }
1834
1835 void BKE_mask_layer_shape_sort(MaskLayer *masklay)
1836 {
1837         BLI_sortlist(&masklay->splines_shapes, mask_layer_shape_sort_cb);
1838 }
1839
1840 bool BKE_mask_layer_shape_spline_from_index(MaskLayer *masklay, int index,
1841                                             MaskSpline **r_masklay_shape, int *r_index)
1842 {
1843         MaskSpline *spline;
1844
1845         for (spline = masklay->splines.first; spline; spline = spline->next) {
1846                 if (index < spline->tot_point) {
1847                         *r_masklay_shape = spline;
1848                         *r_index = index;
1849                         return true;
1850                 }
1851                 index -= spline->tot_point;
1852         }
1853
1854         return false;
1855 }
1856
1857 int BKE_mask_layer_shape_spline_to_index(MaskLayer *masklay, MaskSpline *spline)
1858 {
1859         MaskSpline *spline_iter;
1860         int i_abs = 0;
1861         for (spline_iter = masklay->splines.first;
1862              spline_iter && spline_iter != spline;
1863              i_abs += spline_iter->tot_point, spline_iter = spline_iter->next)
1864         {
1865                 /* pass */
1866         }
1867
1868         return i_abs;
1869 }
1870
1871 /* basic 2D interpolation functions, could make more comprehensive later */
1872 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])
1873 {
1874         float pt_on_line[2];
1875         r_uv[0] = closest_to_line_v2(pt_on_line, pt, pt_a, pt_b);
1876         r_uv[1] = (len_v2v2(pt_on_line, pt) / len_v2v2(pt_a, pt_b)) *
1877                   ((line_point_side_v2(pt_a, pt_b, pt) < 0.0f) ? -1.0f : 1.0f);  /* this line only sets the sign */
1878 }
1879
1880
1881 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])
1882 {
1883         const float dvec[2] = {pt_b[0] - pt_a[0],
1884                                pt_b[1] - pt_a[1]};
1885
1886         /* u */
1887         madd_v2_v2v2fl(r_pt, pt_a, dvec, uv[0]);
1888
1889         /* v */
1890         r_pt[0] += -dvec[1] * uv[1];
1891         r_pt[1] +=  dvec[0] * uv[1];
1892 }
1893
1894 /* when a new points added - resize all shapekey array  */
1895 void BKE_mask_layer_shape_changed_add(MaskLayer *masklay, int index,
1896                                       bool do_init, bool do_init_interpolate)
1897 {
1898         MaskLayerShape *masklay_shape;
1899
1900         /* spline index from masklay */
1901         MaskSpline *spline;
1902         int spline_point_index;
1903
1904         if (BKE_mask_layer_shape_spline_from_index(masklay, index,
1905                                                    &spline, &spline_point_index))
1906         {
1907                 /* sanity check */
1908                 /* the point has already been removed in this array so subtract one when comparing with the shapes */
1909                 int tot = BKE_mask_layer_shape_totvert(masklay) - 1;
1910
1911                 /* for interpolation */
1912                 /* TODO - assumes closed curve for now */
1913                 float uv[3][2]; /* 3x 2D handles */
1914                 const int pi_curr =   spline_point_index;
1915                 const int pi_prev = ((spline_point_index - 1) + spline->tot_point) % spline->tot_point;
1916                 const int pi_next =  (spline_point_index + 1)                      % spline->tot_point;
1917
1918                 const int index_offset = index - spline_point_index;
1919                 /* const int pi_curr_abs = index; */
1920                 const int pi_prev_abs = pi_prev + index_offset;
1921                 const int pi_next_abs = pi_next + index_offset;
1922
1923                 int i;
1924                 if (do_init_interpolate) {
1925                         for (i = 0; i < 3; i++) {
1926                                 interp_weights_uv_v2_calc(uv[i],
1927                                                           spline->points[pi_curr].bezt.vec[i],
1928                                                           spline->points[pi_prev].bezt.vec[i],
1929                                                           spline->points[pi_next].bezt.vec[i]);
1930                         }
1931                 }
1932
1933                 for (masklay_shape = masklay->splines_shapes.first;
1934                      masklay_shape;
1935                      masklay_shape = masklay_shape->next)
1936                 {
1937                         if (tot == masklay_shape->tot_vert) {
1938                                 float *data_resized;
1939
1940                                 masklay_shape->tot_vert++;
1941                                 data_resized = MEM_mallocN(masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, __func__);
1942                                 if (index > 0) {
1943                                         memcpy(data_resized,
1944                                                masklay_shape->data,
1945                                                index * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
1946                                 }
1947
1948                                 if (index != masklay_shape->tot_vert - 1) {
1949                                         memcpy(&data_resized[(index + 1) * MASK_OBJECT_SHAPE_ELEM_SIZE],
1950                                                masklay_shape->data + (index * MASK_OBJECT_SHAPE_ELEM_SIZE),
1951                                                (masklay_shape->tot_vert - (index + 1)) * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
1952                                 }
1953
1954                                 if (do_init) {
1955                                         float *fp = &data_resized[index * MASK_OBJECT_SHAPE_ELEM_SIZE];
1956
1957                                         mask_layer_shape_from_mask_point(&spline->points[spline_point_index].bezt, fp);
1958
1959                                         if (do_init_interpolate && spline->tot_point > 2) {
1960                                                 for (i = 0; i < 3; i++) {
1961                                                         interp_weights_uv_v2_apply(uv[i],
1962                                                                                    &fp[i * 2],
1963                                                                                    &data_resized[(pi_prev_abs * MASK_OBJECT_SHAPE_ELEM_SIZE) + (i * 2)],
1964                                                                                    &data_resized[(pi_next_abs * MASK_OBJECT_SHAPE_ELEM_SIZE) + (i * 2)]);
1965                                                 }
1966                                         }
1967                                 }
1968                                 else {
1969                                         memset(&data_resized[index * MASK_OBJECT_SHAPE_ELEM_SIZE],
1970                                                0,
1971                                                sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
1972                                 }
1973
1974                                 MEM_freeN(masklay_shape->data);
1975                                 masklay_shape->data = data_resized;
1976                         }
1977                         else {
1978                                 printf("%s: vert mismatch %d != %d (frame %d)\n",
1979                                        __func__, masklay_shape->tot_vert, tot, masklay_shape->frame);
1980                         }
1981                 }
1982         }
1983 }
1984
1985
1986 /* move array to account for removed point */
1987 void BKE_mask_layer_shape_changed_remove(MaskLayer *masklay, int index, int count)
1988 {
1989         MaskLayerShape *masklay_shape;
1990
1991         /* the point has already been removed in this array so add one when comparing with the shapes */
1992         int tot = BKE_mask_layer_shape_totvert(masklay);
1993
1994         for (masklay_shape = masklay->splines_shapes.first;
1995              masklay_shape;
1996              masklay_shape = masklay_shape->next)
1997         {
1998                 if (tot == masklay_shape->tot_vert - count) {
1999                         float *data_resized;
2000
2001                         masklay_shape->tot_vert -= count;
2002                         data_resized = MEM_mallocN(masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, __func__);
2003                         if (index > 0) {
2004                                 memcpy(data_resized,
2005                                        masklay_shape->data,
2006                                        index * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2007                         }
2008
2009                         if (index != masklay_shape->tot_vert) {
2010                                 memcpy(&data_resized[index * MASK_OBJECT_SHAPE_ELEM_SIZE],
2011                                        masklay_shape->data + ((index + count) * MASK_OBJECT_SHAPE_ELEM_SIZE),
2012                                        (masklay_shape->tot_vert - index) * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2013                         }
2014
2015                         MEM_freeN(masklay_shape->data);
2016                         masklay_shape->data = data_resized;
2017                 }
2018                 else {
2019                         printf("%s: vert mismatch %d != %d (frame %d)\n",
2020                                __func__, masklay_shape->tot_vert - count, tot, masklay_shape->frame);
2021                 }
2022         }
2023 }
2024
2025 int BKE_mask_get_duration(Mask *mask)
2026 {
2027         return max_ii(1, mask->efra - mask->sfra);
2028 }
2029
2030 /*********************** clipboard *************************/
2031
2032 static void mask_clipboard_free_ex(bool final_free)
2033 {
2034         BKE_mask_spline_free_list(&mask_clipboard.splines);
2035         BLI_listbase_clear(&mask_clipboard.splines);
2036         if (mask_clipboard.id_hash) {
2037                 if (final_free) {
2038                         BLI_ghash_free(mask_clipboard.id_hash, NULL, MEM_freeN);
2039                 }
2040                 else {
2041                         BLI_ghash_clear(mask_clipboard.id_hash, NULL, MEM_freeN);
2042                 }
2043         }
2044 }
2045
2046 /* Free the clipboard. */
2047 void BKE_mask_clipboard_free(void)
2048 {
2049         mask_clipboard_free_ex(true);
2050 }
2051
2052 /* Copy selected visible splines from the given layer to clipboard. */
2053 void BKE_mask_clipboard_copy_from_layer(MaskLayer *mask_layer)
2054 {
2055         MaskSpline *spline;
2056
2057         /* Nothing to do if selection if disabled for the given layer. */
2058         if (mask_layer->restrictflag & MASK_RESTRICT_SELECT) {
2059                 return;
2060         }
2061
2062         mask_clipboard_free_ex(false);
2063         if (mask_clipboard.id_hash == NULL) {
2064                 mask_clipboard.id_hash = BLI_ghash_ptr_new("mask clipboard ID hash");
2065         }
2066
2067         for (spline = mask_layer->splines.first; spline; spline = spline->next) {
2068                 if (spline->flag & SELECT) {
2069                         MaskSpline *spline_new = BKE_mask_spline_copy(spline);
2070                         int i;
2071                         for (i = 0; i < spline_new->tot_point; i++) {
2072                                 MaskSplinePoint *point = &spline_new->points[i];
2073                                 if (point->parent.id) {
2074                                         if (!BLI_ghash_lookup(mask_clipboard.id_hash, point->parent.id)) {
2075                                                 int len = strlen(point->parent.id->name);
2076                                                 char *name_copy = MEM_mallocN(len + 1, "mask clipboard ID name");
2077                                                 strcpy(name_copy, point->parent.id->name);
2078                                                 BLI_ghash_insert(mask_clipboard.id_hash,
2079                                                                  point->parent.id,
2080                                                                  name_copy);
2081                                         }
2082                                 }
2083                         }
2084
2085                         BLI_addtail(&mask_clipboard.splines, spline_new);
2086                 }
2087         }
2088 }
2089
2090 /* Check clipboard is empty. */
2091 bool BKE_mask_clipboard_is_empty(void)
2092 {
2093         return BLI_listbase_is_empty(&mask_clipboard.splines);
2094 }
2095
2096 /* Paste the contents of clipboard to given mask layer */
2097 void BKE_mask_clipboard_paste_to_layer(Main *bmain, MaskLayer *mask_layer)
2098 {
2099         MaskSpline *spline;
2100
2101         for (spline = mask_clipboard.splines.first; spline; spline = spline->next) {
2102                 MaskSpline *spline_new = BKE_mask_spline_copy(spline);
2103                 int i;
2104
2105                 for (i = 0; i < spline_new->tot_point; i++) {
2106                         MaskSplinePoint *point = &spline_new->points[i];
2107                         if (point->parent.id) {
2108                                 char *id_name = BLI_ghash_lookup(mask_clipboard.id_hash, point->parent.id);
2109                                 ListBase *listbase;
2110
2111                                 BLI_assert(id_name != NULL);
2112
2113                                 listbase = which_libbase(bmain, GS(id_name));
2114                                 point->parent.id = BLI_findstring(listbase, id_name + 2, offsetof(ID, name) + 2);
2115                         }
2116                 }
2117
2118                 BLI_addtail(&mask_layer->splines, spline_new);
2119         }
2120 }