8106befcab83c6b887f0cd7675c488127d71952a
[blender.git] / source / blender / editors / space_clip / tracking_ops.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) 2011 Blender Foundation.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation,
23  *                 Sergey Sharybin
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/space_clip/tracking_ops.c
29  *  \ingroup spclip
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_camera_types.h"
35 #include "DNA_constraint_types.h"
36 #include "DNA_gpencil_types.h"
37 #include "DNA_mask_types.h"
38 #include "DNA_movieclip_types.h"
39 #include "DNA_object_types.h"   /* SELECT */
40 #include "DNA_scene_types.h"
41
42 #include "BLI_utildefines.h"
43 #include "BLI_math.h"
44 #include "BLI_listbase.h"
45 #include "BLI_rect.h"
46 #include "BLI_blenlib.h"
47
48 #include "BKE_main.h"
49 #include "BKE_context.h"
50 #include "BKE_constraint.h"
51 #include "BKE_movieclip.h"
52 #include "BKE_tracking.h"
53 #include "BKE_global.h"
54 #include "BKE_depsgraph.h"
55 #include "BKE_object.h"
56 #include "BKE_report.h"
57 #include "BKE_scene.h"
58 #include "BKE_library.h"
59 #include "BKE_mask.h"
60 #include "BKE_node.h"
61 #include "BKE_sound.h"
62
63 #include "WM_api.h"
64 #include "WM_types.h"
65
66 #include "ED_screen.h"
67 #include "ED_clip.h"
68 #include "ED_keyframing.h"
69
70 #include "IMB_imbuf_types.h"
71 #include "IMB_imbuf.h"
72
73 #include "UI_interface.h"
74
75 #include "RNA_access.h"
76 #include "RNA_define.h"
77
78 #include "BLF_translation.h"
79
80 #include "PIL_time.h"
81
82 #include "UI_view2d.h"
83
84 #include "clip_intern.h"    // own include
85
86 /********************** add marker operator *********************/
87
88 static bool add_marker(const bContext *C, float x, float y)
89 {
90         SpaceClip *sc = CTX_wm_space_clip(C);
91         MovieClip *clip = ED_space_clip_get_clip(sc);
92         MovieTracking *tracking = &clip->tracking;
93         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
94         ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
95         MovieTrackingTrack *track;
96         int width, height;
97         int framenr = ED_space_clip_get_clip_frame_number(sc);
98
99         ED_space_clip_get_size(sc, &width, &height);
100
101         if (width == 0 || height == 0) {
102                 return false;
103         }
104
105         track = BKE_tracking_track_add(tracking, tracksbase, x, y, framenr, width, height);
106
107         BKE_tracking_track_select(tracksbase, track, TRACK_AREA_ALL, 0);
108         BKE_tracking_plane_tracks_deselect_all(plane_tracks_base);
109
110         clip->tracking.act_track = track;
111         clip->tracking.act_plane_track = NULL;
112
113         return true;
114 }
115
116 static int add_marker_exec(bContext *C, wmOperator *op)
117 {
118         SpaceClip *sc = CTX_wm_space_clip(C);
119         MovieClip *clip = ED_space_clip_get_clip(sc);
120         float pos[2];
121
122         RNA_float_get_array(op->ptr, "location", pos);
123
124         if (!add_marker(C, pos[0], pos[1])) {
125                 return OPERATOR_CANCELLED;
126         }
127
128         /* reset offset from locked position, so frame jumping wouldn't be so confusing */
129         sc->xlockof = 0;
130         sc->ylockof = 0;
131
132         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
133
134         return OPERATOR_FINISHED;
135 }
136
137 static int add_marker_invoke(bContext *C, wmOperator *op, const wmEvent *event)
138 {
139         SpaceClip *sc = CTX_wm_space_clip(C);
140         ARegion *ar = CTX_wm_region(C);
141
142         if (!RNA_struct_property_is_set(op->ptr, "location")) {
143                 /* If location is not set, use mouse positio nas default. */
144                 float co[2];
145                 ED_clip_mouse_pos(sc, ar, event->mval, co);
146                 RNA_float_set_array(op->ptr, "location", co);
147         }
148
149         return add_marker_exec(C, op);
150 }
151
152 void CLIP_OT_add_marker(wmOperatorType *ot)
153 {
154         /* identifiers */
155         ot->name = "Add Marker";
156         ot->idname = "CLIP_OT_add_marker";
157         ot->description = "Place new marker at specified location";
158
159         /* api callbacks */
160         ot->invoke = add_marker_invoke;
161         ot->exec = add_marker_exec;
162         ot->poll = ED_space_clip_tracking_poll;
163
164         /* flags */
165         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
166
167         /* properties */
168         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
169                              "Location", "Location of marker on frame", -1.0f, 1.0f);
170 }
171
172 /********************** add marker operator *********************/
173
174 static int add_marker_at_click_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
175 {
176         ED_area_headerprint(CTX_wm_area(C), IFACE_("Use LMB click to define location where place the marker"));
177
178         /* add modal handler for ESC */
179         WM_event_add_modal_handler(C, op);
180
181         return OPERATOR_RUNNING_MODAL;
182 }
183
184 static int add_marker_at_click_modal(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
185 {
186         SpaceClip *sc = CTX_wm_space_clip(C);
187         MovieClip *clip = ED_space_clip_get_clip(sc);
188         ARegion *ar = CTX_wm_region(C);
189         float pos[2];
190
191         switch (event->type) {
192                 case MOUSEMOVE:
193                         return OPERATOR_RUNNING_MODAL;
194                         break;
195
196                 case LEFTMOUSE:
197                         ED_area_headerprint(CTX_wm_area(C), NULL);
198
199                         ED_clip_point_stable_pos(sc, ar,
200                                                  event->x - ar->winrct.xmin,
201                                                  event->y - ar->winrct.ymin,
202                                                  &pos[0], &pos[1]);
203
204                         if (!add_marker(C, pos[0], pos[1]))
205                                 return OPERATOR_CANCELLED;
206
207                         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
208                         return OPERATOR_FINISHED;
209                         break;
210
211                 case ESCKEY:
212                         ED_area_headerprint(CTX_wm_area(C), NULL);
213                         return OPERATOR_CANCELLED;
214         }
215
216         return OPERATOR_PASS_THROUGH;
217 }
218
219 void CLIP_OT_add_marker_at_click(wmOperatorType *ot)
220 {
221         /* identifiers */
222         ot->name = "Add Marker at Click";
223         ot->idname = "CLIP_OT_add_marker_at_click";
224         ot->description = "Place new marker at the desired (clicked) position";
225
226         /* api callbacks */
227         ot->invoke = add_marker_at_click_invoke;
228         ot->poll = ED_space_clip_tracking_poll;
229         ot->modal = add_marker_at_click_modal;
230
231         /* flags */
232         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
233 }
234
235 /********************** delete track operator *********************/
236
237 static int delete_track_exec(bContext *C, wmOperator *UNUSED(op))
238 {
239         SpaceClip *sc = CTX_wm_space_clip(C);
240         MovieClip *clip = ED_space_clip_get_clip(sc);
241         MovieTracking *tracking = &clip->tracking;
242         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
243         ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
244         MovieTrackingTrack *track = tracksbase->first, *next;
245         MovieTrackingPlaneTrack *plane_track, *next_plane_track;
246         bool modified = false;
247
248         /* Delete selected plane tracks. */
249         for (plane_track = plane_tracks_base->first;
250              plane_track;
251              plane_track = next_plane_track)
252         {
253                 next_plane_track = plane_track->next;
254
255                 if (plane_track->flag & SELECT) {
256                         BKE_tracking_plane_track_free(plane_track);
257                         BLI_freelinkN(plane_tracks_base, plane_track);
258                         modified = true;
259                 }
260         }
261
262         /* Remove selected point tracks (they'll also be removed from planes which uses them). */
263         while (track) {
264                 next = track->next;
265
266                 if (TRACK_VIEW_SELECTED(sc, track))
267                         clip_delete_track(C, clip, track);
268
269                 track = next;
270         }
271
272         /* nothing selected now, unlock view so it can be scrolled nice again */
273         sc->flag &= ~SC_LOCK_SELECTION;
274
275         if (modified) {
276                 WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
277         }
278
279         return OPERATOR_FINISHED;
280 }
281
282 void CLIP_OT_delete_track(wmOperatorType *ot)
283 {
284         /* identifiers */
285         ot->name = "Delete Track";
286         ot->idname = "CLIP_OT_delete_track";
287         ot->description = "Delete selected tracks";
288
289         /* api callbacks */
290         ot->invoke = WM_operator_confirm;
291         ot->exec = delete_track_exec;
292         ot->poll = ED_space_clip_tracking_poll;
293
294         /* flags */
295         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
296 }
297
298 /********************** delete marker operator *********************/
299
300 static int delete_marker_exec(bContext *C, wmOperator *UNUSED(op))
301 {
302         SpaceClip *sc = CTX_wm_space_clip(C);
303         MovieClip *clip = ED_space_clip_get_clip(sc);
304         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
305         ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(&clip->tracking);
306         MovieTrackingTrack *track = tracksbase->first, *next;
307         MovieTrackingPlaneTrack *plane_track, *plane_track_next;
308         int framenr = ED_space_clip_get_clip_frame_number(sc);
309         int has_selection = 0;
310
311         while (track) {
312                 next = track->next;
313
314                 if (TRACK_VIEW_SELECTED(sc, track)) {
315                         MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, framenr);
316
317                         if (marker) {
318                                 has_selection |= track->markersnr > 1;
319
320                                 clip_delete_marker(C, clip, track, marker);
321                         }
322                 }
323
324                 track = next;
325         }
326
327         for (plane_track = plane_tracks_base->first;
328              plane_track;
329              plane_track = plane_track_next)
330         {
331                 plane_track_next = plane_track->next;
332
333                 if (plane_track->flag & SELECT) {
334                         MovieTrackingPlaneMarker *plane_marker = BKE_tracking_plane_marker_get_exact(plane_track, framenr);
335
336                         if (plane_marker) {
337                                 if (plane_track->markersnr == 1) {
338                                         BKE_tracking_plane_track_free(plane_track);
339                                         BLI_freelinkN(plane_tracks_base, plane_track);
340                                 }
341                                 else {
342                                         BKE_tracking_plane_marker_delete(plane_track, framenr);
343                                 }
344                         }
345                 }
346         }
347
348         if (!has_selection) {
349                 /* nothing selected now, unlock view so it can be scrolled nice again */
350                 sc->flag &= ~SC_LOCK_SELECTION;
351         }
352
353         return OPERATOR_FINISHED;
354 }
355
356 void CLIP_OT_delete_marker(wmOperatorType *ot)
357 {
358         /* identifiers */
359         ot->name = "Delete Marker";
360         ot->idname = "CLIP_OT_delete_marker";
361         ot->description = "Delete marker for current frame from selected tracks";
362
363         /* api callbacks */
364         ot->invoke = WM_operator_confirm;
365         ot->exec = delete_marker_exec;
366         ot->poll = ED_space_clip_tracking_poll;
367
368         /* flags */
369         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
370 }
371
372 /********************** slide marker operator *********************/
373
374 #define SLIDE_ACTION_POS       0
375 #define SLIDE_ACTION_SIZE      1
376 #define SLIDE_ACTION_OFFSET    2
377 #define SLIDE_ACTION_TILT_SIZE 3
378
379 typedef struct {
380         short area, action;
381         MovieTrackingTrack *track;
382         MovieTrackingMarker *marker;
383
384         int mval[2];
385         int width, height;
386         float *min, *max, *pos, *offset, (*corners)[2];
387         float spos[2];
388
389         short lock, accurate;
390
391         /* data to restore on cancel */
392         float old_search_min[2], old_search_max[2], old_pos[2], old_offset[2];
393         float old_corners[4][2];
394         float (*old_markers)[2];
395 } SlideMarkerData;
396
397 static void slide_marker_tilt_slider(MovieTrackingMarker *marker, float slider[2])
398 {
399         add_v2_v2v2(slider, marker->pattern_corners[1], marker->pattern_corners[2]);
400         add_v2_v2(slider, marker->pos);
401 }
402
403 static SlideMarkerData *create_slide_marker_data(SpaceClip *sc, MovieTrackingTrack *track,
404                                                  MovieTrackingMarker *marker, const wmEvent *event,
405                                                  int area, int corner, int action, int width, int height)
406 {
407         SlideMarkerData *data = MEM_callocN(sizeof(SlideMarkerData), "slide marker data");
408         int framenr = ED_space_clip_get_clip_frame_number(sc);
409
410         marker = BKE_tracking_marker_ensure(track, framenr);
411
412         data->area = area;
413         data->action = action;
414         data->track = track;
415         data->marker = marker;
416
417         if (area == TRACK_AREA_POINT) {
418                 data->pos = marker->pos;
419                 data->offset = track->offset;
420         }
421         else if (area == TRACK_AREA_PAT) {
422                 if (action == SLIDE_ACTION_SIZE) {
423                         data->corners = marker->pattern_corners;
424                 }
425                 else if (action == SLIDE_ACTION_OFFSET) {
426                         int a;
427
428                         data->pos = marker->pos;
429                         data->offset = track->offset;
430
431                         data->old_markers = MEM_callocN(sizeof(*data->old_markers) * track->markersnr, "slide marekrs");
432                         for (a = 0; a < track->markersnr; a++)
433                                 copy_v2_v2(data->old_markers[a], track->markers[a].pos);
434                 }
435                 else if (action == SLIDE_ACTION_POS) {
436                         data->corners = marker->pattern_corners;
437                         data->pos = marker->pattern_corners[corner];
438                         copy_v2_v2(data->spos, data->pos);
439                 }
440                 else if (action == SLIDE_ACTION_TILT_SIZE) {
441                         data->corners = marker->pattern_corners;
442                         slide_marker_tilt_slider(marker, data->spos);
443                 }
444         }
445         else if (area == TRACK_AREA_SEARCH) {
446                 data->min = marker->search_min;
447                 data->max = marker->search_max;
448         }
449
450         data->mval[0] = event->mval[0];
451         data->mval[1] = event->mval[1];
452
453         data->width = width;
454         data->height = height;
455
456         if (action == SLIDE_ACTION_SIZE)
457                 data->lock = 1;
458
459         /* backup marker's settings */
460         memcpy(data->old_corners, marker->pattern_corners, sizeof(data->old_corners));
461         copy_v2_v2(data->old_search_min, marker->search_min);
462         copy_v2_v2(data->old_search_max, marker->search_max);
463         copy_v2_v2(data->old_pos, marker->pos);
464         copy_v2_v2(data->old_offset, track->offset);
465
466         return data;
467 }
468
469 static int mouse_on_slide_zone(SpaceClip *sc, MovieTrackingMarker *marker,
470                                int area, float co[2], float slide_zone[2],
471                                float padding, int width, int height)
472 {
473         const float size = 12.0f;
474         float min[2], max[2];
475         float dx, dy;
476
477         if (area == TRACK_AREA_SEARCH) {
478                 copy_v2_v2(min, marker->search_min);
479                 copy_v2_v2(max, marker->search_max);
480         }
481         else {
482                 BKE_tracking_marker_pattern_minmax(marker, min, max);
483         }
484
485         min[0] -= padding / width;
486         min[1] -= padding / height;
487         max[0] += padding / width;
488         max[1] += padding / height;
489
490         dx = size / width / sc->zoom;
491         dy = size / height / sc->zoom;
492
493         dx = min_ff(dx, (max[0] - min[0]) / 6.0f);
494         dy = min_ff(dy, (max[1] - min[1]) / 6.0f);
495
496         return IN_RANGE_INCL(co[0], slide_zone[0] - dx, slide_zone[0] + dx) &&
497                IN_RANGE_INCL(co[1], slide_zone[1] - dy, slide_zone[1] + dy);
498 }
499
500 static int mouse_on_corner(SpaceClip *sc, MovieTrackingMarker *marker,
501                            int area, float co[2], int corner, float padding,
502                            int width, int height)
503 {
504         float min[2], max[2], crn[2];
505
506         if (area == TRACK_AREA_SEARCH) {
507                 copy_v2_v2(min, marker->search_min);
508                 copy_v2_v2(max, marker->search_max);
509         }
510         else {
511                 BKE_tracking_marker_pattern_minmax(marker, min, max);
512         }
513
514         min[0] -= padding / width;
515         min[1] -= padding / height;
516         max[0] += padding / width;
517         max[1] += padding / height;
518
519         if (corner == 0) {
520                 crn[0] = marker->pos[0] + max[0];
521                 crn[1] = marker->pos[1] + min[1];
522         }
523         else {
524                 crn[0] = marker->pos[0] + min[0];
525                 crn[1] = marker->pos[1] + max[1];
526         }
527
528         return mouse_on_slide_zone(sc, marker, area, co, crn, padding, width, height);
529 }
530
531 static int get_mouse_pattern_corner(SpaceClip *sc, MovieTrackingMarker *marker, float co[2], int width, int height)
532 {
533         int i, next;
534         float len = FLT_MAX, dx, dy;
535
536         for (i = 0; i < 4; i++) {
537                 float cur_len;
538
539                 next = (i + 1) % 4;
540
541                 cur_len = len_v2v2(marker->pattern_corners[i], marker->pattern_corners[next]);
542
543                 len = min_ff(cur_len, len);
544         }
545
546         dx = 12.0f / width / sc->zoom;
547         dy = 12.0f / height / sc->zoom;
548
549         dx = min_ff(dx, len * 2.0f / 3.0f);
550         dy = min_ff(dy, len * width / height * 2.0f / 3.0f);
551
552         for (i = 0; i < 4; i++) {
553                 float crn[2];
554                 int inside;
555
556                 add_v2_v2v2(crn, marker->pattern_corners[i], marker->pos);
557
558                 inside = IN_RANGE_INCL(co[0], crn[0] - dx, crn[0] + dx) &&
559                          IN_RANGE_INCL(co[1], crn[1] - dy, crn[1] + dy);
560
561                 if (inside)
562                         return i;
563         }
564
565         return -1;
566 }
567
568 static int mouse_on_offset(SpaceClip *sc, MovieTrackingTrack *track, MovieTrackingMarker *marker,
569                            float co[2], int width, int height)
570 {
571         float pos[2], dx, dy;
572         float pat_min[2], pat_max[2];
573
574         BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max);
575
576         add_v2_v2v2(pos, marker->pos, track->offset);
577
578         dx = 12.0f / width / sc->zoom;
579         dy = 12.0f / height / sc->zoom;
580
581         dx = min_ff(dx, (pat_max[0] - pat_min[0]) / 2.0f);
582         dy = min_ff(dy, (pat_max[1] - pat_min[1]) / 2.0f);
583
584         return co[0] >= pos[0] - dx && co[0] <= pos[0] + dx && co[1] >= pos[1] - dy && co[1] <= pos[1] + dy;
585 }
586
587 static int mouse_on_tilt(SpaceClip *sc, MovieTrackingMarker *marker, float co[2], int width, int height)
588 {
589         float slider[2];
590
591         slide_marker_tilt_slider(marker, slider);
592
593         return mouse_on_slide_zone(sc, marker, TRACK_AREA_PAT, co, slider, 0.0f, width, height);
594 }
595
596 static bool slide_check_corners(float (*corners)[2])
597 {
598         int i, next, prev;
599         float cross = 0.0f;
600         float p[2] = {0.0f, 0.0f};
601
602         if (!isect_point_quad_v2(p, corners[0], corners[1], corners[2], corners[3]))
603                 return false;
604
605         for (i = 0; i < 4; i++) {
606                 float v1[2], v2[2], cur_cross;
607
608                 next = (i + 1) % 4;
609                 prev = (4 + i - 1) % 4;
610
611                 sub_v2_v2v2(v1, corners[i], corners[prev]);
612                 sub_v2_v2v2(v2, corners[next], corners[i]);
613
614                 cur_cross = cross_v2v2(v1, v2);
615
616                 if (fabsf(cur_cross) > FLT_EPSILON) {
617                         if (cross == 0.0f) {
618                                 cross = cur_cross;
619                         }
620                         else if (cross * cur_cross < 0.0f) {
621                                 return false;
622                         }
623                 }
624         }
625
626         return true;
627 }
628
629 static void hide_cursor(bContext *C)
630 {
631         wmWindow *win = CTX_wm_window(C);
632
633         WM_cursor_set(win, CURSOR_NONE);
634 }
635
636 static void show_cursor(bContext *C)
637 {
638         wmWindow *win = CTX_wm_window(C);
639
640         WM_cursor_set(win, CURSOR_STD);
641 }
642
643 MovieTrackingTrack *tracking_marker_check_slide(bContext *C, const wmEvent *event, int *area_r, int *action_r, int *corner_r)
644 {
645         SpaceClip *sc = CTX_wm_space_clip(C);
646         ARegion *ar = CTX_wm_region(C);
647
648         MovieClip *clip = ED_space_clip_get_clip(sc);
649         MovieTrackingTrack *track;
650         int width, height;
651         float co[2];
652         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
653         int framenr = ED_space_clip_get_clip_frame_number(sc);
654         int action = -1, area = 0, corner = -1;
655
656         ED_space_clip_get_size(sc, &width, &height);
657
658         if (width == 0 || height == 0)
659                 return NULL;
660
661         ED_clip_mouse_pos(sc, ar, event->mval, co);
662
663         track = tracksbase->first;
664         while (track) {
665                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
666                         MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
667                         bool ok = false;
668
669                         if ((marker->flag & MARKER_DISABLED) == 0) {
670                                 if (mouse_on_offset(sc, track, marker, co, width, height)) {
671                                         area = TRACK_AREA_POINT;
672                                         action = SLIDE_ACTION_POS;
673                                         ok = true;
674                                 }
675
676                                 if (!ok && (sc->flag & SC_SHOW_MARKER_SEARCH)) {
677                                         if (mouse_on_corner(sc, marker, TRACK_AREA_SEARCH, co, 1, 0.0f, width, height)) {
678                                                 area = TRACK_AREA_SEARCH;
679                                                 action = SLIDE_ACTION_OFFSET;
680                                                 ok = true;
681                                         }
682                                         else if (mouse_on_corner(sc, marker, TRACK_AREA_SEARCH, co, 0, 0.0f, width, height)) {
683                                                 area = TRACK_AREA_SEARCH;
684                                                 action = SLIDE_ACTION_SIZE;
685                                                 ok = true;
686                                         }
687                                 }
688
689                                 if (!ok && (sc->flag & SC_SHOW_MARKER_PATTERN)) {
690                                         int current_corner = get_mouse_pattern_corner(sc, marker, co, width, height);
691
692                                         if (current_corner != -1) {
693                                                 area = TRACK_AREA_PAT;
694                                                 action = SLIDE_ACTION_POS;
695                                                 corner = current_corner;
696                                                 ok = true;
697                                         }
698                                         else {
699 #if 0
700                                                 /* TODO: disable for now, needs better approaches for visualization */
701
702                                                 if (mouse_on_corner(sc, marker, TRACK_AREA_PAT, co, 1, 12.0f, width, height)) {
703                                                         area = TRACK_AREA_PAT;
704                                                         action = SLIDE_ACTION_OFFSET;
705                                                         ok = true;
706                                                 }
707                                                 if (!ok && mouse_on_corner(sc, marker, TRACK_AREA_PAT, co, 0, 12.0f, width, height)) {
708                                                         area = TRACK_AREA_PAT;
709                                                         action = SLIDE_ACTION_SIZE;
710                                                         ok = true;
711                                                 }
712 #endif
713                                                 if (!ok && mouse_on_tilt(sc, marker, co, width, height)) {
714                                                         area = TRACK_AREA_PAT;
715                                                         action = SLIDE_ACTION_TILT_SIZE;
716                                                         ok = true;
717                                                 }
718                                         }
719                                 }
720
721                                 if (ok) {
722                                         if (area_r)
723                                                 *area_r = area;
724
725                                         if (action_r)
726                                                 *action_r = action;
727
728                                         if (corner_r)
729                                                 *corner_r = corner;
730
731                                         return track;
732                                 }
733                         }
734                 }
735
736                 track = track->next;
737         }
738
739         return NULL;
740 }
741
742 static void *slide_marker_customdata(bContext *C, const wmEvent *event)
743 {
744         SpaceClip *sc = CTX_wm_space_clip(C);
745         ARegion *ar = CTX_wm_region(C);
746
747         MovieTrackingTrack *track;
748         int width, height;
749         float co[2];
750         void *customdata = NULL;
751         int framenr = ED_space_clip_get_clip_frame_number(sc);
752         int area, action, corner;
753
754         ED_space_clip_get_size(sc, &width, &height);
755
756         if (width == 0 || height == 0)
757                 return NULL;
758
759         ED_clip_mouse_pos(sc, ar, event->mval, co);
760
761         track = tracking_marker_check_slide(C, event, &area, &action, &corner);
762         if (track) {
763                 MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
764
765                 customdata = create_slide_marker_data(sc, track, marker, event, area, corner, action, width, height);
766         }
767
768         return customdata;
769 }
770
771 static int slide_marker_invoke(bContext *C, wmOperator *op, const wmEvent *event)
772 {
773         SlideMarkerData *slidedata = slide_marker_customdata(C, event);
774
775         if (slidedata) {
776                 SpaceClip *sc = CTX_wm_space_clip(C);
777                 MovieClip *clip = ED_space_clip_get_clip(sc);
778                 MovieTracking *tracking = &clip->tracking;
779
780                 tracking->act_track = slidedata->track;
781                 tracking->act_plane_track = NULL;
782
783                 op->customdata = slidedata;
784
785                 hide_cursor(C);
786                 WM_event_add_modal_handler(C, op);
787
788                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
789
790                 return OPERATOR_RUNNING_MODAL;
791         }
792
793         return OPERATOR_PASS_THROUGH;
794 }
795
796 static void cancel_mouse_slide(SlideMarkerData *data)
797 {
798         MovieTrackingTrack *track = data->track;
799         MovieTrackingMarker *marker = data->marker;
800
801         memcpy(marker->pattern_corners, data->old_corners, sizeof(marker->pattern_corners));
802         copy_v2_v2(marker->search_min, data->old_search_min);
803         copy_v2_v2(marker->search_max, data->old_search_max);
804         copy_v2_v2(marker->pos, data->old_pos);
805         copy_v2_v2(track->offset, data->old_offset);
806
807         if (data->old_markers) {
808                 int a;
809
810                 for (a = 0; a < data->track->markersnr; a++)
811                         copy_v2_v2(data->track->markers[a].pos, data->old_markers[a]);
812         }
813 }
814
815 static void free_slide_data(SlideMarkerData *data)
816 {
817         if (data->old_markers)
818                 MEM_freeN(data->old_markers);
819
820         MEM_freeN(data);
821 }
822
823 static int slide_marker_modal(bContext *C, wmOperator *op, const wmEvent *event)
824 {
825         SpaceClip *sc = CTX_wm_space_clip(C);
826         ARegion *ar = CTX_wm_region(C);
827
828         SlideMarkerData *data = (SlideMarkerData *)op->customdata;
829         float dx, dy, mdelta[2];
830
831         switch (event->type) {
832                 case LEFTCTRLKEY:
833                 case RIGHTCTRLKEY:
834                 case LEFTSHIFTKEY:
835                 case RIGHTSHIFTKEY:
836                         if (data->action == SLIDE_ACTION_SIZE)
837                                 if (ELEM(event->type, LEFTCTRLKEY, RIGHTCTRLKEY))
838                                         data->lock = event->val == KM_RELEASE;
839
840                         if (ELEM(event->type, LEFTSHIFTKEY, RIGHTSHIFTKEY))
841                                 data->accurate = event->val == KM_PRESS;
842
843                         /* fall-through */
844                 case MOUSEMOVE:
845                         mdelta[0] = event->mval[0] - data->mval[0];
846                         mdelta[1] = event->mval[1] - data->mval[1];
847
848                         dx = mdelta[0] / data->width / sc->zoom;
849
850                         if (data->lock)
851                                 dy = -dx / data->height * data->width;
852                         else
853                                 dy = mdelta[1] / data->height / sc->zoom;
854
855                         if (data->accurate) {
856                                 dx /= 5;
857                                 dy /= 5;
858                         }
859
860                         if (data->area == TRACK_AREA_POINT) {
861                                 if (data->action == SLIDE_ACTION_OFFSET) {
862                                         data->offset[0] = data->old_offset[0] + dx;
863                                         data->offset[1] = data->old_offset[1] + dy;
864                                 }
865                                 else {
866                                         data->pos[0] = data->old_pos[0] + dx;
867                                         data->pos[1] = data->old_pos[1] + dy;
868                                 }
869
870                                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
871                                 DAG_id_tag_update(&sc->clip->id, 0);
872                         }
873                         else if (data->area == TRACK_AREA_PAT) {
874                                 if (data->action == SLIDE_ACTION_SIZE) {
875                                         float start[2], end[2];
876                                         float scale;
877
878                                         ED_clip_point_stable_pos(sc, ar, data->mval[0], data->mval[1], &start[0], &start[1]);
879
880                                         sub_v2_v2(start, data->old_pos);
881
882                                         if (len_v2(start) > 0.0f) {
883                                                 float mval[2];
884
885                                                 if (data->accurate) {
886                                                         mval[0] = data->mval[0] + (event->mval[0] - data->mval[0]) / 5.0f;
887                                                         mval[1] = data->mval[1] + (event->mval[1] - data->mval[1]) / 5.0f;
888                                                 }
889                                                 else {
890                                                         mval[0] = event->mval[0];
891                                                         mval[1] = event->mval[1];
892                                                 }
893
894                                                 ED_clip_point_stable_pos(sc, ar, mval[0], mval[1], &end[0], &end[1]);
895
896                                                 sub_v2_v2(end, data->old_pos);
897
898                                                 scale = len_v2(end) / len_v2(start);
899
900                                                 if (scale > 0.0f) {
901                                                         int a;
902
903                                                         for (a = 0; a < 4; a++) {
904                                                                 mul_v2_v2fl(data->corners[a], data->old_corners[a], scale);
905                                                         }
906                                                 }
907                                         }
908
909                                         BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
910                                 }
911                                 else if (data->action == SLIDE_ACTION_OFFSET) {
912                                         float d[2] = {dx, dy};
913                                         int a;
914
915                                         for (a = 0; a < data->track->markersnr; a++)
916                                                 add_v2_v2v2(data->track->markers[a].pos, data->old_markers[a], d);
917
918                                         sub_v2_v2v2(data->offset, data->old_offset, d);
919                                 }
920                                 else if (data->action == SLIDE_ACTION_POS) {
921                                         float spos[2];
922
923                                         copy_v2_v2(spos, data->pos);
924
925                                         data->pos[0] = data->spos[0] + dx;
926                                         data->pos[1] = data->spos[1] + dy;
927
928                                         if (!slide_check_corners(data->corners)) {
929                                                 copy_v2_v2(data->pos, spos);
930                                         }
931
932                                         /* currently only patterns are allowed to have such combination of event and data */
933                                         BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
934                                 }
935                                 else if (data->action == SLIDE_ACTION_TILT_SIZE) {
936                                         float start[2], end[2];
937                                         float scale = 1.0f, angle = 0.0f;
938                                         int a;
939                                         float mval[2];
940
941                                         if (data->accurate) {
942                                                 mval[0] = data->mval[0] + (event->mval[0] - data->mval[0]) / 5.0f;
943                                                 mval[1] = data->mval[1] + (event->mval[1] - data->mval[1]) / 5.0f;
944                                         }
945                                         else {
946                                                 mval[0] = event->mval[0];
947                                                 mval[1] = event->mval[1];
948                                         }
949
950                                         sub_v2_v2v2(start, data->spos, data->old_pos);
951
952                                         ED_clip_point_stable_pos(sc, ar, mval[0], mval[1], &end[0], &end[1]);
953                                         sub_v2_v2(end, data->old_pos);
954
955                                         if (len_v2(start) > 0.0f) {
956                                                 scale = len_v2(end) / len_v2(start);
957
958                                                 if (scale < 0.0f) {
959                                                         scale = 0.0;
960                                                 }
961                                         }
962
963                                         angle = -angle_signed_v2v2(start, end);
964
965                                         for (a = 0; a < 4; a++) {
966                                                 float vec[2];
967
968                                                 mul_v2_v2fl(data->corners[a], data->old_corners[a], scale);
969
970                                                 copy_v2_v2(vec, data->corners[a]);
971                                                 vec[0] *= data->width;
972                                                 vec[1] *= data->height;
973
974                                                 data->corners[a][0] = (vec[0] * cosf(angle) - vec[1] * sinf(angle)) / data->width;
975                                                 data->corners[a][1] = (vec[1] * cosf(angle) + vec[0] * sinf(angle)) / data->height;
976                                         }
977
978                                         BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
979
980                                 }
981                         }
982                         else if (data->area == TRACK_AREA_SEARCH) {
983                                 if (data->action == SLIDE_ACTION_SIZE) {
984                                         data->min[0] = data->old_search_min[0] - dx;
985                                         data->max[0] = data->old_search_max[0] + dx;
986
987                                         data->min[1] = data->old_search_min[1] + dy;
988                                         data->max[1] = data->old_search_max[1] - dy;
989
990                                         BKE_tracking_marker_clamp(data->marker, CLAMP_SEARCH_DIM);
991                                 }
992                                 else if (data->area == TRACK_AREA_SEARCH) {
993                                         float d[2] = {dx, dy};
994
995                                         add_v2_v2v2(data->min, data->old_search_min, d);
996                                         add_v2_v2v2(data->max, data->old_search_max, d);
997                                 }
998
999                                 BKE_tracking_marker_clamp(data->marker, CLAMP_SEARCH_POS);
1000                         }
1001
1002                         data->marker->flag &= ~MARKER_TRACKED;
1003
1004                         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
1005
1006                         break;
1007
1008                 case LEFTMOUSE:
1009                         if (event->val == KM_RELEASE) {
1010                                 free_slide_data(op->customdata);
1011
1012                                 show_cursor(C);
1013
1014                                 return OPERATOR_FINISHED;
1015                         }
1016
1017                         break;
1018
1019                 case ESCKEY:
1020                         cancel_mouse_slide(op->customdata);
1021
1022                         free_slide_data(op->customdata);
1023
1024                         show_cursor(C);
1025
1026                         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
1027
1028                         return OPERATOR_CANCELLED;
1029         }
1030
1031         return OPERATOR_RUNNING_MODAL;
1032 }
1033
1034 void CLIP_OT_slide_marker(wmOperatorType *ot)
1035 {
1036         /* identifiers */
1037         ot->name = "Slide Marker";
1038         ot->description = "Slide marker areas";
1039         ot->idname = "CLIP_OT_slide_marker";
1040
1041         /* api callbacks */
1042         ot->poll = ED_space_clip_tracking_poll;
1043         ot->invoke = slide_marker_invoke;
1044         ot->modal = slide_marker_modal;
1045
1046         /* flags */
1047         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_GRAB_POINTER | OPTYPE_BLOCKING;
1048
1049         /* properties */
1050         RNA_def_float_vector(ot->srna, "offset", 2, NULL, -FLT_MAX, FLT_MAX,
1051                              "Offset", "Offset in floating point units, 1.0 is the width and height of the image", -FLT_MAX, FLT_MAX);
1052 }
1053
1054 /********************** track operator *********************/
1055
1056 typedef struct TrackMarkersJob {
1057         struct MovieTrackingContext *context;   /* tracking context */
1058         int sfra, efra, lastfra;    /* Start, end and recently tracked frames */
1059         int backwards;              /* Backwards tracking flag */
1060         MovieClip *clip;            /* Clip which is tracking */
1061         float delay;                /* Delay in milliseconds to allow tracking at fixed FPS */
1062
1063         struct Main *main;
1064         struct Scene *scene;
1065         struct bScreen *screen;
1066 } TrackMarkersJob;
1067
1068 static int track_markers_testbreak(void)
1069 {
1070         return G.is_break;
1071 }
1072
1073 static int track_count_markers(SpaceClip *sc, MovieClip *clip)
1074 {
1075         int tot = 0;
1076         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
1077         MovieTrackingTrack *track;
1078         int framenr = ED_space_clip_get_clip_frame_number(sc);
1079
1080         track = tracksbase->first;
1081         while (track) {
1082                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
1083                         MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
1084
1085                         if (!marker || (marker->flag & MARKER_DISABLED) == 0)
1086                                 tot++;
1087                 }
1088
1089                 track = track->next;
1090         }
1091
1092         return tot;
1093 }
1094
1095 static void clear_invisible_track_selection(SpaceClip *sc, MovieClip *clip)
1096 {
1097         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
1098         int hidden = 0;
1099
1100         if ((sc->flag & SC_SHOW_MARKER_PATTERN) == 0)
1101                 hidden |= TRACK_AREA_PAT;
1102
1103         if ((sc->flag & SC_SHOW_MARKER_SEARCH) == 0)
1104                 hidden |= TRACK_AREA_SEARCH;
1105
1106         if (hidden) {
1107                 MovieTrackingTrack *track = tracksbase->first;
1108
1109                 while (track) {
1110                         if ((track->flag & TRACK_HIDDEN) == 0)
1111                                 BKE_tracking_track_flag_clear(track, hidden, SELECT);
1112
1113                         track = track->next;
1114                 }
1115         }
1116 }
1117
1118 static void track_init_markers(SpaceClip *sc, MovieClip *clip, int *frames_limit_r)
1119 {
1120         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
1121         MovieTrackingTrack *track;
1122         int framenr = ED_space_clip_get_clip_frame_number(sc);
1123         int frames_limit = 0;
1124
1125         clear_invisible_track_selection(sc, clip);
1126
1127         track = tracksbase->first;
1128         while (track) {
1129                 if (TRACK_VIEW_SELECTED(sc, track)) {
1130                         if ((track->flag & TRACK_HIDDEN) == 0 && (track->flag & TRACK_LOCKED) == 0) {
1131                                 BKE_tracking_marker_ensure(track, framenr);
1132
1133                                 if (track->frames_limit) {
1134                                         if (frames_limit == 0)
1135                                                 frames_limit = track->frames_limit;
1136                                         else
1137                                                 frames_limit = min_ii(frames_limit, (int)track->frames_limit);
1138                                 }
1139                         }
1140                 }
1141
1142                 track = track->next;
1143         }
1144
1145         *frames_limit_r = frames_limit;
1146 }
1147
1148 static bool track_markers_check_direction(int backwards, int curfra, int efra)
1149 {
1150         if (backwards) {
1151                 if (curfra < efra)
1152                         return false;
1153         }
1154         else {
1155                 if (curfra > efra)
1156                         return false;
1157         }
1158
1159         return true;
1160 }
1161
1162 static int track_markers_initjob(bContext *C, TrackMarkersJob *tmj, int backwards)
1163 {
1164         SpaceClip *sc = CTX_wm_space_clip(C);
1165         MovieClip *clip = ED_space_clip_get_clip(sc);
1166         Scene *scene = CTX_data_scene(C);
1167         MovieTrackingSettings *settings = &clip->tracking.settings;
1168         int frames_limit;
1169
1170         track_init_markers(sc, clip, &frames_limit);
1171
1172         tmj->sfra = ED_space_clip_get_clip_frame_number(sc);
1173         tmj->clip = clip;
1174         tmj->backwards = backwards;
1175
1176         if (backwards)
1177                 tmj->efra = SFRA;
1178         else
1179                 tmj->efra = EFRA;
1180
1181         /* limit frames to be tracked by user setting */
1182         if (frames_limit) {
1183                 if (backwards)
1184                         tmj->efra = MAX2(tmj->efra, tmj->sfra - frames_limit);
1185                 else
1186                         tmj->efra = MIN2(tmj->efra, tmj->sfra + frames_limit);
1187         }
1188
1189         tmj->efra = BKE_movieclip_remap_scene_to_clip_frame(clip, tmj->efra);
1190
1191         if (settings->speed != TRACKING_SPEED_FASTEST) {
1192                 tmj->delay = 1.0f / scene->r.frs_sec * 1000.0f;
1193
1194                 if (settings->speed == TRACKING_SPEED_HALF)
1195                         tmj->delay *= 2;
1196                 else if (settings->speed == TRACKING_SPEED_QUARTER)
1197                         tmj->delay *= 4;
1198                 else if (settings->speed == TRACKING_SPEED_DOUBLE)
1199                         tmj->delay /= 2;
1200         }
1201
1202         tmj->context = BKE_tracking_context_new(clip, &sc->user, backwards, 1);
1203
1204         clip->tracking_context = tmj->context;
1205
1206         tmj->lastfra = tmj->sfra;
1207
1208         /* XXX: silly to store this, but this data is needed to update scene and movie-clip
1209          *      frame numbers when tracking is finished. This introduces better feedback for artists.
1210          *      Maybe there's another way to solve this problem, but can't think better way atm.
1211          *      Anyway, this way isn't more unstable as animation rendering animation
1212          *      which uses the same approach (except storing screen). */
1213         tmj->scene = scene;
1214         tmj->main = CTX_data_main(C);
1215         tmj->screen = CTX_wm_screen(C);
1216
1217         return track_markers_check_direction(backwards, tmj->sfra, tmj->efra);
1218 }
1219
1220 static void track_markers_startjob(void *tmv, short *stop, short *do_update, float *progress)
1221 {
1222         TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
1223         int framenr = tmj->sfra;
1224         // double t = PIL_check_seconds_timer();
1225
1226         while (framenr != tmj->efra) {
1227                 if (tmj->delay > 0) {
1228                         /* tracking should happen with fixed fps. Calculate time
1229                          * using current timer value before tracking frame and after.
1230                          *
1231                          * Small (and maybe unneeded optimization): do not calculate exec_time
1232                          * for "Fastest" tracking */
1233
1234                         double start_time = PIL_check_seconds_timer(), exec_time;
1235
1236                         if (!BKE_tracking_context_step(tmj->context))
1237                                 break;
1238
1239                         exec_time = PIL_check_seconds_timer() - start_time;
1240                         if (tmj->delay > (float)exec_time)
1241                                 PIL_sleep_ms(tmj->delay - (float)exec_time);
1242                 }
1243                 else if (!BKE_tracking_context_step(tmj->context))
1244                         break;
1245
1246                 *do_update = TRUE;
1247                 *progress = (float)(framenr - tmj->sfra) / (tmj->efra - tmj->sfra);
1248
1249                 if (tmj->backwards)
1250                         framenr--;
1251                 else
1252                         framenr++;
1253
1254                 tmj->lastfra = framenr;
1255
1256                 if (*stop || track_markers_testbreak())
1257                         break;
1258         }
1259
1260         // printf("Tracking time: %lf\n", PIL_check_seconds_timer()-t);
1261 }
1262
1263 static void track_markers_updatejob(void *tmv)
1264 {
1265         TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
1266
1267         BKE_tracking_context_sync(tmj->context);
1268 }
1269
1270 static void track_markers_freejob(void *tmv)
1271 {
1272         TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
1273
1274         tmj->clip->tracking_context = NULL;
1275         tmj->scene->r.cfra = BKE_movieclip_remap_clip_to_scene_frame(tmj->clip, tmj->lastfra);
1276         ED_update_for_newframe(tmj->main, tmj->scene, 0);
1277
1278         BKE_tracking_context_sync(tmj->context);
1279         BKE_tracking_context_free(tmj->context);
1280
1281         WM_main_add_notifier(NC_SCENE | ND_FRAME, tmj->scene);
1282
1283         MEM_freeN(tmj);
1284 }
1285
1286 static int track_markers_exec(bContext *C, wmOperator *op)
1287 {
1288         SpaceClip *sc = CTX_wm_space_clip(C);
1289         MovieClip *clip = ED_space_clip_get_clip(sc);
1290         Scene *scene = CTX_data_scene(C);
1291         struct MovieTrackingContext *context;
1292         int framenr = ED_space_clip_get_clip_frame_number(sc);
1293         int sfra = framenr, efra;
1294         int backwards = RNA_boolean_get(op->ptr, "backwards");
1295         int sequence = RNA_boolean_get(op->ptr, "sequence");
1296         int frames_limit;
1297
1298         if (track_count_markers(sc, clip) == 0)
1299                 return OPERATOR_CANCELLED;
1300
1301         track_init_markers(sc, clip, &frames_limit);
1302
1303         if (backwards)
1304                 efra = SFRA;
1305         else
1306                 efra = EFRA;
1307
1308         /* limit frames to be tracked by user setting */
1309         if (frames_limit) {
1310                 if (backwards)
1311                         efra = MAX2(efra, sfra - frames_limit);
1312                 else
1313                         efra = MIN2(efra, sfra + frames_limit);
1314         }
1315
1316         efra = BKE_movieclip_remap_scene_to_clip_frame(clip, efra);
1317
1318         if (!track_markers_check_direction(backwards, framenr, efra))
1319                 return OPERATOR_CANCELLED;
1320
1321         /* do not disable tracks due to threshold when tracking frame-by-frame */
1322         context = BKE_tracking_context_new(clip, &sc->user, backwards, sequence);
1323
1324         while (framenr != efra) {
1325                 if (!BKE_tracking_context_step(context))
1326                         break;
1327
1328                 if (backwards) framenr--;
1329                 else framenr++;
1330
1331                 if (!sequence)
1332                         break;
1333         }
1334
1335         BKE_tracking_context_sync(context);
1336         BKE_tracking_context_free(context);
1337
1338         /* update scene current frame to the lastes tracked frame */
1339         scene->r.cfra = BKE_movieclip_remap_clip_to_scene_frame(clip, framenr);
1340
1341         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1342         WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
1343
1344         return OPERATOR_FINISHED;
1345 }
1346
1347 static int track_markers_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1348 {
1349         TrackMarkersJob *tmj;
1350         ScrArea *sa = CTX_wm_area(C);
1351         SpaceClip *sc = CTX_wm_space_clip(C);
1352         MovieClip *clip = ED_space_clip_get_clip(sc);
1353         wmJob *wm_job;
1354         int backwards = RNA_boolean_get(op->ptr, "backwards");
1355         int sequence = RNA_boolean_get(op->ptr, "sequence");
1356
1357         if (WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C), WM_JOB_TYPE_ANY)) {
1358                 /* only one tracking is allowed at a time */
1359                 return OPERATOR_CANCELLED;
1360         }
1361
1362         if (clip->tracking_context)
1363                 return OPERATOR_CANCELLED;
1364
1365         if (track_count_markers(sc, clip) == 0)
1366                 return OPERATOR_CANCELLED;
1367
1368         if (!sequence)
1369                 return track_markers_exec(C, op);
1370
1371         tmj = MEM_callocN(sizeof(TrackMarkersJob), "TrackMarkersJob data");
1372         if (!track_markers_initjob(C, tmj, backwards)) {
1373                 track_markers_freejob(tmj);
1374
1375                 return OPERATOR_CANCELLED;
1376         }
1377
1378         /* setup job */
1379         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, "Track Markers",
1380                              WM_JOB_PROGRESS, WM_JOB_TYPE_CLIP_TRACK_MARKERS);
1381         WM_jobs_customdata_set(wm_job, tmj, track_markers_freejob);
1382
1383         /* if there's delay set in tracking job, tracking should happen
1384          * with fixed FPS. To deal with editor refresh we have to synchronize
1385          * tracks from job and tracks in clip. Do this in timer callback
1386          * to prevent threading conflicts. */
1387         if (tmj->delay > 0)
1388                 WM_jobs_timer(wm_job, tmj->delay / 1000.0f, NC_MOVIECLIP | NA_EVALUATED, 0);
1389         else
1390                 WM_jobs_timer(wm_job, 0.2, NC_MOVIECLIP | NA_EVALUATED, 0);
1391
1392         WM_jobs_callbacks(wm_job, track_markers_startjob, NULL, track_markers_updatejob, NULL);
1393
1394         G.is_break = FALSE;
1395
1396         WM_jobs_start(CTX_wm_manager(C), wm_job);
1397         WM_cursor_wait(0);
1398
1399         /* add modal handler for ESC */
1400         WM_event_add_modal_handler(C, op);
1401
1402         return OPERATOR_RUNNING_MODAL;
1403 }
1404
1405 static int track_markers_modal(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
1406 {
1407         /* no running tracking, remove handler and pass through */
1408         if (0 == WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C), WM_JOB_TYPE_ANY))
1409                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
1410
1411         /* running tracking */
1412         switch (event->type) {
1413                 case ESCKEY:
1414                         return OPERATOR_RUNNING_MODAL;
1415                         break;
1416         }
1417
1418         return OPERATOR_PASS_THROUGH;
1419 }
1420
1421 void CLIP_OT_track_markers(wmOperatorType *ot)
1422 {
1423         /* identifiers */
1424         ot->name = "Track Markers";
1425         ot->description = "Track selected markers";
1426         ot->idname = "CLIP_OT_track_markers";
1427
1428         /* api callbacks */
1429         ot->exec = track_markers_exec;
1430         ot->invoke = track_markers_invoke;
1431         ot->poll = ED_space_clip_tracking_poll;
1432         ot->modal = track_markers_modal;
1433
1434         /* flags */
1435         ot->flag = OPTYPE_UNDO;
1436
1437         /* properties */
1438         RNA_def_boolean(ot->srna, "backwards", 0, "Backwards", "Do backwards tracking");
1439         RNA_def_boolean(ot->srna, "sequence", 0, "Track Sequence", "Track marker during image sequence rather than single image");
1440 }
1441
1442 /********************** refine track position operator *********************/
1443
1444 static int refine_marker_exec(bContext *C, wmOperator *op)
1445 {
1446         SpaceClip *sc = CTX_wm_space_clip(C);
1447         MovieClip *clip = ED_space_clip_get_clip(sc);
1448         MovieTracking *tracking = &clip->tracking;
1449         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
1450         MovieTrackingTrack *track;
1451         bool backwards = RNA_boolean_get(op->ptr, "backwards");
1452         int framenr = ED_space_clip_get_clip_frame_number(sc);
1453
1454         for (track = tracksbase->first; track; track = track->next) {
1455                 if (TRACK_VIEW_SELECTED(sc, track)) {
1456                         MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
1457
1458                         BKE_tracking_refine_marker(clip, track, marker, backwards);
1459                 }
1460         }
1461
1462         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1463
1464         return OPERATOR_FINISHED;
1465 }
1466
1467 void CLIP_OT_refine_markers(wmOperatorType *ot)
1468 {
1469         /* identifiers */
1470         ot->name = "Refine Markers";
1471         ot->description = "Refine selected markers positions "
1472                           "by running the tracker from track's reference to current frame";
1473         ot->idname = "CLIP_OT_refine_markers";
1474
1475         /* api callbacks */
1476         ot->exec = refine_marker_exec;
1477         ot->poll = ED_space_clip_tracking_poll;
1478
1479         /* flags */
1480         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1481
1482         /* properties */
1483         RNA_def_boolean(ot->srna, "backwards", 0, "Backwards", "Do backwards tracking");
1484 }
1485
1486 /********************** solve camera operator *********************/
1487
1488 typedef struct {
1489         Scene *scene;
1490         MovieClip *clip;
1491         MovieClipUser user;
1492
1493         ReportList *reports;
1494
1495         char stats_message[256];
1496
1497         struct MovieReconstructContext *context;
1498 } SolveCameraJob;
1499
1500 static int solve_camera_initjob(bContext *C, SolveCameraJob *scj, wmOperator *op, char *error_msg, int max_error)
1501 {
1502         SpaceClip *sc = CTX_wm_space_clip(C);
1503         MovieClip *clip = ED_space_clip_get_clip(sc);
1504         Scene *scene = CTX_data_scene(C);
1505         MovieTracking *tracking = &clip->tracking;
1506         MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
1507         int width, height;
1508
1509         if (!BKE_tracking_reconstruction_check(tracking, object, error_msg, max_error))
1510                 return 0;
1511
1512         /* could fail if footage uses images with different sizes */
1513         BKE_movieclip_get_size(clip, &sc->user, &width, &height);
1514
1515         scj->clip = clip;
1516         scj->scene = scene;
1517         scj->reports = op->reports;
1518         scj->user = sc->user;
1519
1520         scj->context = BKE_tracking_reconstruction_context_new(tracking, object,
1521                                                                object->keyframe1, object->keyframe2, width, height);
1522
1523         tracking->stats = MEM_callocN(sizeof(MovieTrackingStats), "solve camera stats");
1524
1525         return 1;
1526 }
1527
1528 static void solve_camera_updatejob(void *scv)
1529 {
1530         SolveCameraJob *scj = (SolveCameraJob *)scv;
1531         MovieTracking *tracking = &scj->clip->tracking;
1532
1533         BLI_strncpy(tracking->stats->message, scj->stats_message, sizeof(tracking->stats->message));
1534 }
1535
1536 static void solve_camera_startjob(void *scv, short *stop, short *do_update, float *progress)
1537 {
1538         SolveCameraJob *scj = (SolveCameraJob *)scv;
1539
1540         BKE_tracking_reconstruction_solve(scj->context, stop, do_update, progress,
1541                                           scj->stats_message, sizeof(scj->stats_message));
1542 }
1543
1544 static void solve_camera_freejob(void *scv)
1545 {
1546         SolveCameraJob *scj = (SolveCameraJob *)scv;
1547         MovieTracking *tracking = &scj->clip->tracking;
1548         Scene *scene = scj->scene;
1549         MovieClip *clip = scj->clip;
1550         int solved;
1551
1552         if (!scj->context) {
1553                 /* job weren't fully initialized due to some error */
1554                 MEM_freeN(scj);
1555                 return;
1556         }
1557
1558         solved = BKE_tracking_reconstruction_finish(scj->context, tracking);
1559         if (!solved)
1560                 BKE_report(scj->reports, RPT_WARNING, "Some data failed to reconstruct (see console for details)");
1561         else
1562                 BKE_reportf(scj->reports, RPT_INFO, "Average re-projection error: %.3f", tracking->reconstruction.error);
1563
1564         /* set currently solved clip as active for scene */
1565         if (scene->clip)
1566                 id_us_min(&clip->id);
1567
1568         scene->clip = clip;
1569         id_us_plus(&clip->id);
1570
1571         /* set blender camera focal length so result would look fine there */
1572         if (scene->camera && scene->camera->data && GS(((ID *) scene->camera->data)->name) == ID_CA) {
1573                 Camera *camera = (Camera *)scene->camera->data;
1574                 int width, height;
1575
1576                 BKE_movieclip_get_size(clip, &scj->user, &width, &height);
1577
1578                 BKE_tracking_camera_to_blender(tracking, scene, camera, width, height);
1579
1580                 WM_main_add_notifier(NC_OBJECT, camera);
1581         }
1582
1583         MEM_freeN(tracking->stats);
1584         tracking->stats = NULL;
1585
1586         DAG_id_tag_update(&clip->id, 0);
1587
1588         WM_main_add_notifier(NC_MOVIECLIP | NA_EVALUATED, clip);
1589         WM_main_add_notifier(NC_OBJECT | ND_TRANSFORM, NULL);
1590
1591         /* update active clip displayed in scene buttons */
1592         WM_main_add_notifier(NC_SCENE, scene);
1593
1594         BKE_tracking_reconstruction_context_free(scj->context);
1595         MEM_freeN(scj);
1596 }
1597
1598 static int solve_camera_exec(bContext *C, wmOperator *op)
1599 {
1600         SolveCameraJob *scj;
1601         char error_msg[256] = "\0";
1602
1603         scj = MEM_callocN(sizeof(SolveCameraJob), "SolveCameraJob data");
1604         if (!solve_camera_initjob(C, scj, op, error_msg, sizeof(error_msg))) {
1605                 if (error_msg[0])
1606                         BKE_report(op->reports, RPT_ERROR, error_msg);
1607
1608                 solve_camera_freejob(scj);
1609
1610                 return OPERATOR_CANCELLED;
1611         }
1612
1613         solve_camera_startjob(scj, NULL, NULL, NULL);
1614
1615         solve_camera_freejob(scj);
1616
1617         return OPERATOR_FINISHED;
1618 }
1619
1620 static int solve_camera_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1621 {
1622         SolveCameraJob *scj;
1623         ScrArea *sa = CTX_wm_area(C);
1624         SpaceClip *sc = CTX_wm_space_clip(C);
1625         MovieClip *clip = ED_space_clip_get_clip(sc);
1626         MovieTracking *tracking = &clip->tracking;
1627         MovieTrackingReconstruction *reconstruction = BKE_tracking_get_active_reconstruction(tracking);
1628         wmJob *wm_job;
1629         char error_msg[256] = "\0";
1630
1631         if (WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C), WM_JOB_TYPE_ANY)) {
1632                 /* only one solve is allowed at a time */
1633                 return OPERATOR_CANCELLED;
1634         }
1635
1636         scj = MEM_callocN(sizeof(SolveCameraJob), "SolveCameraJob data");
1637         if (!solve_camera_initjob(C, scj, op, error_msg, sizeof(error_msg))) {
1638                 if (error_msg[0])
1639                         BKE_report(op->reports, RPT_ERROR, error_msg);
1640
1641                 solve_camera_freejob(scj);
1642
1643                 return OPERATOR_CANCELLED;
1644         }
1645
1646         BLI_strncpy(tracking->stats->message, "Solving camera | Preparing solve", sizeof(tracking->stats->message));
1647
1648         /* hide reconstruction statistics from previous solve */
1649         reconstruction->flag &= ~TRACKING_RECONSTRUCTED;
1650         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1651
1652         /* setup job */
1653         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, "Solve Camera",
1654                              WM_JOB_PROGRESS, WM_JOB_TYPE_CLIP_SOLVE_CAMERA);
1655         WM_jobs_customdata_set(wm_job, scj, solve_camera_freejob);
1656         WM_jobs_timer(wm_job, 0.1, NC_MOVIECLIP | NA_EVALUATED, 0);
1657         WM_jobs_callbacks(wm_job, solve_camera_startjob, NULL, solve_camera_updatejob, NULL);
1658
1659         G.is_break = FALSE;
1660
1661         WM_jobs_start(CTX_wm_manager(C), wm_job);
1662         WM_cursor_wait(0);
1663
1664         /* add modal handler for ESC */
1665         WM_event_add_modal_handler(C, op);
1666
1667         return OPERATOR_RUNNING_MODAL;
1668 }
1669
1670 static int solve_camera_modal(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
1671 {
1672         /* no running solver, remove handler and pass through */
1673         if (0 == WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C), WM_JOB_TYPE_ANY))
1674                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
1675
1676         /* running tracking */
1677         switch (event->type) {
1678                 case ESCKEY:
1679                         return OPERATOR_RUNNING_MODAL;
1680                         break;
1681         }
1682
1683         return OPERATOR_PASS_THROUGH;
1684 }
1685
1686 void CLIP_OT_solve_camera(wmOperatorType *ot)
1687 {
1688         /* identifiers */
1689         ot->name = "Solve Camera";
1690         ot->description = "Solve camera motion from tracks";
1691         ot->idname = "CLIP_OT_solve_camera";
1692
1693         /* api callbacks */
1694         ot->exec = solve_camera_exec;
1695         ot->invoke = solve_camera_invoke;
1696         ot->modal = solve_camera_modal;
1697         ot->poll = ED_space_clip_tracking_poll;
1698
1699         /* flags */
1700         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1701 }
1702
1703 /********************** clear solution operator *********************/
1704
1705 static int clear_solution_exec(bContext *C, wmOperator *UNUSED(op))
1706 {
1707         SpaceClip *sc = CTX_wm_space_clip(C);
1708         MovieClip *clip = ED_space_clip_get_clip(sc);
1709         MovieTracking *tracking = &clip->tracking;
1710         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
1711         MovieTrackingReconstruction *reconstruction = BKE_tracking_get_active_reconstruction(tracking);
1712         MovieTrackingTrack *track = tracksbase->first;
1713
1714         while (track) {
1715                 track->flag &= ~TRACK_HAS_BUNDLE;
1716
1717                 track = track->next;
1718         }
1719
1720         if (reconstruction->cameras)
1721                 MEM_freeN(reconstruction->cameras);
1722
1723         reconstruction->cameras = NULL;
1724         reconstruction->camnr = 0;
1725
1726         reconstruction->flag &= ~TRACKING_RECONSTRUCTED;
1727
1728         DAG_id_tag_update(&clip->id, 0);
1729
1730         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1731         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, NULL);
1732
1733         return OPERATOR_FINISHED;
1734 }
1735
1736 void CLIP_OT_clear_solution(wmOperatorType *ot)
1737 {
1738         /* identifiers */
1739         ot->name = "Clear Solution";
1740         ot->description = "Clear all calculated data";
1741         ot->idname = "CLIP_OT_clear_solution";
1742
1743         /* api callbacks */
1744         ot->exec = clear_solution_exec;
1745         ot->poll = ED_space_clip_tracking_poll;
1746
1747         /* flags */
1748         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1749 }
1750
1751 /********************** clear track operator *********************/
1752
1753 static int clear_track_path_exec(bContext *C, wmOperator *op)
1754 {
1755         SpaceClip *sc = CTX_wm_space_clip(C);
1756         MovieClip *clip = ED_space_clip_get_clip(sc);
1757         MovieTracking *tracking = &clip->tracking;
1758         MovieTrackingTrack *track;
1759         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
1760         int action = RNA_enum_get(op->ptr, "action");
1761         int clear_active = RNA_boolean_get(op->ptr, "clear_active");
1762         int framenr = ED_space_clip_get_clip_frame_number(sc);
1763
1764         if (clear_active) {
1765                 track = BKE_tracking_track_get_active(tracking);
1766                 if (track) {
1767                         BKE_tracking_track_path_clear(track, framenr, action);
1768                 }
1769         }
1770         else {
1771                 track = tracksbase->first;
1772                 while (track) {
1773                         if (TRACK_VIEW_SELECTED(sc, track))
1774                                 BKE_tracking_track_path_clear(track, framenr, action);
1775
1776                         track = track->next;
1777                 }
1778         }
1779
1780         BKE_tracking_dopesheet_tag_update(tracking);
1781         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1782
1783         return OPERATOR_FINISHED;
1784 }
1785
1786 void CLIP_OT_clear_track_path(wmOperatorType *ot)
1787 {
1788         static EnumPropertyItem clear_path_actions[] = {
1789                 {TRACK_CLEAR_UPTO, "UPTO", 0, "Clear up-to", "Clear path up to current frame"},
1790                 {TRACK_CLEAR_REMAINED, "REMAINED", 0, "Clear remained", "Clear path at remaining frames (after current)"},
1791                 {TRACK_CLEAR_ALL, "ALL", 0, "Clear all", "Clear the whole path"},
1792                 {0, NULL, 0, NULL, NULL}
1793         };
1794
1795         /* identifiers */
1796         ot->name = "Clear Track Path";
1797         ot->description = "Clear tracks after/before current position or clear the whole track";
1798         ot->idname = "CLIP_OT_clear_track_path";
1799
1800         /* api callbacks */
1801         ot->exec = clear_track_path_exec;
1802         ot->poll = ED_space_clip_tracking_poll;
1803
1804         /* flags */
1805         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1806
1807         /* proeprties */
1808         RNA_def_enum(ot->srna, "action", clear_path_actions, TRACK_CLEAR_REMAINED, "Action", "Clear action to execute");
1809         RNA_def_boolean(ot->srna, "clear_active", 0, "Clear Active", "Clear active track only instead of all selected tracks");
1810 }
1811
1812 /********************** disable markers operator *********************/
1813
1814 static int disable_markers_exec(bContext *C, wmOperator *op)
1815 {
1816         SpaceClip *sc = CTX_wm_space_clip(C);
1817         MovieClip *clip = ED_space_clip_get_clip(sc);
1818         MovieTracking *tracking = &clip->tracking;
1819         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
1820         MovieTrackingTrack *track = tracksbase->first;
1821         int action = RNA_enum_get(op->ptr, "action");
1822         int framenr = ED_space_clip_get_clip_frame_number(sc);
1823
1824         while (track) {
1825                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
1826                         MovieTrackingMarker *marker = BKE_tracking_marker_ensure(track, framenr);
1827
1828                         if (action == 0)
1829                                 marker->flag |= MARKER_DISABLED;
1830                         else if (action == 1)
1831                                 marker->flag &= ~MARKER_DISABLED;
1832                         else marker->flag ^= MARKER_DISABLED;
1833                 }
1834
1835                 track = track->next;
1836         }
1837
1838         DAG_id_tag_update(&clip->id, 0);
1839
1840         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1841
1842         return OPERATOR_FINISHED;
1843 }
1844
1845 void CLIP_OT_disable_markers(wmOperatorType *ot)
1846 {
1847         static EnumPropertyItem actions_items[] = {
1848                 {0, "DISABLE", 0, "Disable", "Disable selected markers"},
1849                 {1, "ENABLE", 0, "Enable", "Enable selected markers"},
1850                 {2, "TOGGLE", 0, "Toggle", "Toggle disabled flag for selected markers"},
1851                 {0, NULL, 0, NULL, NULL}
1852         };
1853
1854         /* identifiers */
1855         ot->name = "Disable Markers";
1856         ot->description = "Disable/enable selected markers";
1857         ot->idname = "CLIP_OT_disable_markers";
1858
1859         /* api callbacks */
1860         ot->exec = disable_markers_exec;
1861         ot->poll = ED_space_clip_tracking_poll;
1862
1863         /* flags */
1864         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1865
1866         /* properties */
1867         RNA_def_enum(ot->srna, "action", actions_items, 0, "Action", "Disable action to execute");
1868 }
1869
1870 /********************** set origin operator *********************/
1871
1872 static Object *get_camera_with_movieclip(Scene *scene, MovieClip *clip)
1873 {
1874         Object *camera = scene->camera;
1875         Base *base;
1876
1877         if (camera && BKE_object_movieclip_get(scene, camera, 0) == clip)
1878                 return camera;
1879
1880         base = scene->base.first;
1881         while (base) {
1882                 if (base->object->type == OB_CAMERA) {
1883                         if (BKE_object_movieclip_get(scene, base->object, 0) == clip) {
1884                                 camera = base->object;
1885                                 break;
1886                         }
1887                 }
1888
1889                 base = base->next;
1890         }
1891
1892         return camera;
1893 }
1894
1895 static Object *get_orientation_object(bContext *C)
1896 {
1897         Scene *scene = CTX_data_scene(C);
1898         SpaceClip *sc = CTX_wm_space_clip(C);
1899         MovieClip *clip = ED_space_clip_get_clip(sc);
1900         MovieTracking *tracking = &clip->tracking;
1901         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
1902         Object *object = NULL;
1903
1904         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
1905                 object = get_camera_with_movieclip(scene, clip);
1906         }
1907         else {
1908                 object = OBACT;
1909         }
1910
1911         if (object && object->parent)
1912                 object = object->parent;
1913
1914         return object;
1915 }
1916
1917 static int set_orientation_poll(bContext *C)
1918 {
1919         SpaceClip *sc = CTX_wm_space_clip(C);
1920
1921         if (sc) {
1922                 Scene *scene = CTX_data_scene(C);
1923                 MovieClip *clip = ED_space_clip_get_clip(sc);
1924
1925                 if (clip) {
1926                         MovieTracking *tracking = &clip->tracking;
1927                         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
1928
1929                         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
1930                                 return TRUE;
1931                         }
1932                         else {
1933                                 return OBACT != NULL;
1934                         }
1935                 }
1936         }
1937
1938         return FALSE;
1939 }
1940
1941 static int count_selected_bundles(bContext *C)
1942 {
1943         SpaceClip *sc = CTX_wm_space_clip(C);
1944         MovieClip *clip = ED_space_clip_get_clip(sc);
1945         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
1946         MovieTrackingTrack *track;
1947         int tot = 0;
1948
1949         track = tracksbase->first;
1950         while (track) {
1951                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_HAS_BUNDLE))
1952                         tot++;
1953
1954                 track = track->next;
1955         }
1956
1957         return tot;
1958 }
1959
1960 static void object_solver_inverted_matrix(Scene *scene, Object *ob, float invmat[4][4])
1961 {
1962         bConstraint *con;
1963         bool found = false;
1964
1965         for (con = ob->constraints.first; con; con = con->next) {
1966                 bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
1967
1968                 if (!cti)
1969                         continue;
1970
1971                 if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
1972                         bObjectSolverConstraint *data = (bObjectSolverConstraint *)con->data;
1973
1974                         if (!found) {
1975                                 Object *cam = data->camera ? data->camera : scene->camera;
1976
1977                                 BKE_object_where_is_calc_mat4(scene, cam, invmat);
1978                         }
1979
1980                         mul_m4_m4m4(invmat, invmat, data->invmat);
1981
1982                         found = true;
1983                 }
1984         }
1985
1986         if (found)
1987                 invert_m4(invmat);
1988         else
1989                 unit_m4(invmat);
1990 }
1991
1992 static Object *object_solver_camera(Scene *scene, Object *ob)
1993 {
1994         bConstraint *con;
1995
1996         for (con = ob->constraints.first; con; con = con->next) {
1997                 bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
1998
1999                 if (!cti)
2000                         continue;
2001
2002                 if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
2003                         bObjectSolverConstraint *data = (bObjectSolverConstraint *)con->data;
2004
2005                         return data->camera ? data->camera : scene->camera;
2006                 }
2007         }
2008
2009         return NULL;
2010 }
2011
2012 static int set_origin_exec(bContext *C, wmOperator *op)
2013 {
2014         SpaceClip *sc = CTX_wm_space_clip(C);
2015         MovieClip *clip = ED_space_clip_get_clip(sc);
2016         MovieTracking *tracking = &clip->tracking;
2017         MovieTrackingTrack *track;
2018         MovieTrackingObject *tracking_object;
2019         Scene *scene = CTX_data_scene(C);
2020         Object *object;
2021         Object *camera = get_camera_with_movieclip(scene, clip);
2022         ListBase *tracksbase;
2023         float mat[4][4], vec[3], median[3];
2024         int selected_count = count_selected_bundles(C);
2025
2026         if (selected_count == 0) {
2027                 BKE_report(op->reports, RPT_ERROR,
2028                            "At least one track with bundle should be selected to define origin position");
2029
2030                 return OPERATOR_CANCELLED;
2031         }
2032
2033         object = get_orientation_object(C);
2034         if (!object) {
2035                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2036
2037                 return OPERATOR_CANCELLED;
2038         }
2039
2040         tracking_object = BKE_tracking_object_get_active(tracking);
2041
2042         tracksbase = BKE_tracking_object_get_tracks(tracking, tracking_object);
2043
2044         track = tracksbase->first;
2045         zero_v3(median);
2046         while (track) {
2047                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_HAS_BUNDLE)) {
2048                         add_v3_v3(median, track->bundle_pos);
2049                 }
2050
2051                 track = track->next;
2052         }
2053         mul_v3_fl(median, 1.0f / selected_count);
2054
2055         BKE_tracking_get_camera_object_matrix(scene, camera, mat);
2056
2057         mul_v3_m4v3(vec, mat, median);
2058
2059         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2060                 sub_v3_v3(object->loc, vec);
2061         }
2062         else {
2063                 object_solver_inverted_matrix(scene, object, mat);
2064                 mul_v3_m4v3(vec, mat, vec);
2065                 copy_v3_v3(object->loc, vec);
2066         }
2067
2068         DAG_id_tag_update(&clip->id, 0);
2069         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2070
2071         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2072         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2073
2074         return OPERATOR_FINISHED;
2075 }
2076
2077 void CLIP_OT_set_origin(wmOperatorType *ot)
2078 {
2079         /* identifiers */
2080         ot->name = "Set Origin";
2081         ot->description = "Set active marker as origin by moving camera (or it's parent if present) in 3D space";
2082         ot->idname = "CLIP_OT_set_origin";
2083
2084         /* api callbacks */
2085         ot->exec = set_origin_exec;
2086         ot->poll = set_orientation_poll;
2087
2088         /* flags */
2089         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2090
2091         /* properties */
2092         RNA_def_boolean(ot->srna, "use_median", 0, "Use Median", "Set origin to median point of selected bundles");
2093 }
2094
2095 /********************** set floor operator *********************/
2096
2097 static void set_axis(Scene *scene,  Object *ob, MovieClip *clip, MovieTrackingObject *tracking_object,
2098                      MovieTrackingTrack *track, char axis)
2099 {
2100         Object *camera = get_camera_with_movieclip(scene, clip);
2101         int is_camera = tracking_object->flag & TRACKING_OBJECT_CAMERA;
2102         bool flip = false;
2103         float mat[4][4], vec[3], obmat[4][4], dvec[3];
2104
2105         BKE_object_to_mat4(ob, obmat);
2106
2107         BKE_tracking_get_camera_object_matrix(scene, camera, mat);
2108         mul_v3_m4v3(vec, mat, track->bundle_pos);
2109         copy_v3_v3(dvec, vec);
2110
2111         if (!is_camera) {
2112                 float imat[4][4];
2113
2114                 object_solver_inverted_matrix(scene, ob, imat);
2115                 mul_v3_m4v3(vec, imat, vec);
2116
2117                 invert_m4_m4(imat, obmat);
2118                 mul_v3_m4v3(dvec, imat, vec);
2119
2120                 sub_v3_v3(vec, obmat[3]);
2121         }
2122
2123         if (len_v2(vec) < 1e-3f)
2124                 return;
2125
2126         unit_m4(mat);
2127
2128         if (axis == 'X') {
2129                 if (fabsf(dvec[1]) < 1e-3f) {
2130                         flip = true;
2131
2132                         mat[0][0] = -1.0f; mat[0][1] = 0.0f; mat[0][2] = 0.0f;
2133                         mat[1][0] = 0.0f; mat[1][1] = -1.0f; mat[1][2] = 0.0f;
2134                         mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
2135                 }
2136                 else {
2137                         copy_v3_v3(mat[0], vec);
2138
2139                         if (is_camera || fabsf(vec[2]) < 1e-3f) {
2140                                 mat[0][2] = 0.0f;
2141                                 mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
2142                                 cross_v3_v3v3(mat[1], mat[2], mat[0]);
2143                         }
2144                         else {
2145                                 vec[2] = 0.0f;
2146
2147                                 cross_v3_v3v3(mat[1], mat[0], vec);
2148                                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
2149                         }
2150                 }
2151         }
2152         else {
2153                 if (fabsf(dvec[0]) < 1e-3f) {
2154                         flip = true;
2155
2156                         mat[0][0] = -1.0f; mat[0][1] = 0.0f; mat[0][2] = 0.0f;
2157                         mat[1][0] = 0.0f; mat[1][1] = -1.0f; mat[1][2] = 0.0f;
2158                         mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
2159                 }
2160                 else {
2161                         copy_v3_v3(mat[1], vec);
2162
2163                         if (is_camera || fabsf(vec[2]) < 1e-3f) {
2164                                 mat[1][2] = 0.0f;
2165                                 mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
2166                                 cross_v3_v3v3(mat[0], mat[1], mat[2]);
2167                         }
2168                         else {
2169                                 vec[2] = 0.0f;
2170
2171                                 cross_v3_v3v3(mat[0], vec, mat[1]);
2172                                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
2173                         }
2174                 }
2175         }
2176
2177         normalize_v3(mat[0]);
2178         normalize_v3(mat[1]);
2179         normalize_v3(mat[2]);
2180
2181         if (is_camera) {
2182                 invert_m4(mat);
2183
2184                 mul_m4_m4m4(mat, mat, obmat);
2185         }
2186         else {
2187                 if (!flip) {
2188                         float lmat[4][4], ilmat[4][4], rmat[3][3];
2189
2190                         BKE_object_rot_to_mat3(ob, rmat, TRUE);
2191                         invert_m3(rmat);
2192                         mul_m4_m4m3(mat, mat, rmat);
2193
2194                         unit_m4(lmat);
2195                         copy_v3_v3(lmat[3], obmat[3]);
2196                         invert_m4_m4(ilmat, lmat);
2197
2198                         mul_serie_m4(mat, lmat, mat, ilmat, obmat, NULL, NULL, NULL, NULL);
2199                 }
2200                 else {
2201                         mul_m4_m4m4(mat, obmat, mat);
2202                 }
2203         }
2204
2205         BKE_object_apply_mat4(ob, mat, 0, 0);
2206 }
2207
2208 static int set_plane_exec(bContext *C, wmOperator *op)
2209 {
2210         SpaceClip *sc = CTX_wm_space_clip(C);
2211         MovieClip *clip = ED_space_clip_get_clip(sc);
2212         Scene *scene = CTX_data_scene(C);
2213         MovieTracking *tracking = &clip->tracking;
2214         MovieTrackingObject *tracking_object;
2215         MovieTrackingTrack *track, *axis_track = NULL, *act_track;
2216         ListBase *tracksbase;
2217         Object *object;
2218         Object *camera = get_camera_with_movieclip(scene, clip);
2219         int tot = 0;
2220         float vec[3][3], mat[4][4], obmat[4][4], newmat[4][4], orig[3] = {0.0f, 0.0f, 0.0f};
2221         int plane = RNA_enum_get(op->ptr, "plane");
2222         float rot[4][4] = {{0.0f, 0.0f, -1.0f, 0.0f},
2223                            {0.0f, 1.0f, 0.0f, 0.0f},
2224                            {1.0f, 0.0f, 0.0f, 0.0f},
2225                            {0.0f, 0.0f, 0.0f, 1.0f}};  /* 90 degrees Y-axis rotation matrix */
2226
2227         if (count_selected_bundles(C) != 3) {
2228                 BKE_report(op->reports, RPT_ERROR, "Three tracks with bundles are needed to orient the floor");
2229
2230                 return OPERATOR_CANCELLED;
2231         }
2232
2233         tracking_object = BKE_tracking_object_get_active(tracking);
2234         tracksbase = BKE_tracking_object_get_tracks(tracking, tracking_object);
2235         act_track = BKE_tracking_track_get_active(tracking);
2236
2237         object = get_orientation_object(C);
2238         if (!object) {
2239                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2240
2241                 return OPERATOR_CANCELLED;
2242         }
2243
2244         BKE_tracking_get_camera_object_matrix(scene, camera, mat);
2245
2246         /* get 3 bundles to use as reference */
2247         track = tracksbase->first;
2248         while (track && tot < 3) {
2249                 if (track->flag & TRACK_HAS_BUNDLE && TRACK_VIEW_SELECTED(sc, track)) {
2250                         mul_v3_m4v3(vec[tot], mat, track->bundle_pos);
2251
2252                         if (tot == 0 || track == act_track)
2253                                 copy_v3_v3(orig, vec[tot]);
2254                         else
2255                                 axis_track = track;
2256
2257                         tot++;
2258                 }
2259
2260                 track = track->next;
2261         }
2262
2263         sub_v3_v3(vec[1], vec[0]);
2264         sub_v3_v3(vec[2], vec[0]);
2265
2266         /* construct ortho-normal basis */
2267         unit_m4(mat);
2268
2269         if (plane == 0) { /* floor */
2270                 cross_v3_v3v3(mat[0], vec[1], vec[2]);
2271                 copy_v3_v3(mat[1], vec[1]);
2272                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
2273         }
2274         else if (plane == 1) { /* wall */
2275                 cross_v3_v3v3(mat[2], vec[1], vec[2]);
2276                 copy_v3_v3(mat[1], vec[1]);
2277                 cross_v3_v3v3(mat[0], mat[1], mat[2]);
2278         }
2279
2280         normalize_v3(mat[0]);
2281         normalize_v3(mat[1]);
2282         normalize_v3(mat[2]);
2283
2284         /* move to origin point */
2285         mat[3][0] = orig[0];
2286         mat[3][1] = orig[1];
2287         mat[3][2] = orig[2];
2288
2289         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2290                 invert_m4(mat);
2291
2292                 BKE_object_to_mat4(object, obmat);
2293                 mul_m4_m4m4(mat, mat, obmat);
2294                 mul_m4_m4m4(newmat, rot, mat);
2295                 BKE_object_apply_mat4(object, newmat, 0, 0);
2296
2297                 /* make camera have positive z-coordinate */
2298                 if (object->loc[2] < 0) {
2299                         invert_m4(rot);
2300                         mul_m4_m4m4(newmat, rot, mat);
2301                         BKE_object_apply_mat4(object, newmat, 0, 0);
2302                 }
2303         }
2304         else {
2305                 BKE_object_apply_mat4(object, mat, 0, 0);
2306         }
2307
2308         BKE_object_where_is_calc(scene, object);
2309         set_axis(scene, object, clip, tracking_object, axis_track, 'X');
2310
2311         DAG_id_tag_update(&clip->id, 0);
2312         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2313
2314         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2315         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2316
2317         return OPERATOR_FINISHED;
2318 }
2319
2320 void CLIP_OT_set_plane(wmOperatorType *ot)
2321 {
2322         static EnumPropertyItem plane_items[] = {
2323                 {0, "FLOOR", 0, "Floor", "Set floor plane"},
2324                 {1, "WALL", 0, "Wall", "Set wall plane"},
2325                 {0, NULL, 0, NULL, NULL}
2326         };
2327
2328         /* identifiers */
2329         ot->name = "Set Plane";
2330         ot->description = "Set plane based on 3 selected bundles by moving camera (or it's parent if present) in 3D space";
2331         ot->idname = "CLIP_OT_set_plane";
2332
2333         /* api callbacks */
2334         ot->exec = set_plane_exec;
2335         ot->poll = set_orientation_poll;
2336
2337         /* flags */
2338         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2339
2340         /* properties */
2341         RNA_def_enum(ot->srna, "plane", plane_items, 0, "Plane", "Plane to be used for orientation");
2342 }
2343
2344 /********************** set axis operator *********************/
2345
2346 static int set_axis_exec(bContext *C, wmOperator *op)
2347 {
2348         SpaceClip *sc = CTX_wm_space_clip(C);
2349         MovieClip *clip = ED_space_clip_get_clip(sc);
2350         MovieTracking *tracking = &clip->tracking;
2351         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
2352         MovieTrackingTrack *track;
2353         Scene *scene = CTX_data_scene(C);
2354         Object *object;
2355         ListBase *tracksbase;
2356         int axis = RNA_enum_get(op->ptr, "axis");
2357
2358         if (count_selected_bundles(C) != 1) {
2359                 BKE_report(op->reports, RPT_ERROR, "Single track with bundle should be selected to define axis");
2360
2361                 return OPERATOR_CANCELLED;
2362         }
2363
2364         object = get_orientation_object(C);
2365         if (!object) {
2366                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2367
2368                 return OPERATOR_CANCELLED;
2369         }
2370
2371         tracksbase = BKE_tracking_object_get_tracks(tracking, tracking_object);
2372
2373         track = tracksbase->first;
2374         while (track) {
2375                 if (TRACK_VIEW_SELECTED(sc, track))
2376                         break;
2377
2378                 track = track->next;
2379         }
2380
2381         set_axis(scene, object, clip, tracking_object, track, axis == 0 ? 'X' : 'Y');
2382
2383         DAG_id_tag_update(&clip->id, 0);
2384         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2385
2386         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2387         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2388
2389         return OPERATOR_FINISHED;
2390 }
2391
2392 void CLIP_OT_set_axis(wmOperatorType *ot)
2393 {
2394         static EnumPropertyItem axis_actions[] = {
2395                 {0, "X", 0, "X", "Align bundle align X axis"},
2396                 {1, "Y", 0, "Y", "Align bundle align Y axis"},
2397                 {0, NULL, 0, NULL, NULL}
2398         };
2399
2400         /* identifiers */
2401         ot->name = "Set Axis";
2402         ot->description = "Set direction of scene axis rotating camera (or it's parent if present) and assuming selected track lies on real axis joining it with the origin";
2403         ot->idname = "CLIP_OT_set_axis";
2404
2405         /* api callbacks */
2406         ot->exec = set_axis_exec;
2407         ot->poll = set_orientation_poll;
2408
2409         /* flags */
2410         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2411
2412         /* properties */
2413         RNA_def_enum(ot->srna, "axis", axis_actions, 0, "Axis", "Axis to use to align bundle along");
2414 }
2415
2416 /********************** set scale operator *********************/
2417
2418 static int do_set_scale(bContext *C, wmOperator *op, bool scale_solution, bool apply_scale)
2419 {
2420         SpaceClip *sc = CTX_wm_space_clip(C);
2421         MovieClip *clip = ED_space_clip_get_clip(sc);
2422         MovieTracking *tracking = &clip->tracking;
2423         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
2424         MovieTrackingTrack *track;
2425         Scene *scene = CTX_data_scene(C);
2426         Object *object = NULL;
2427         Object *camera = get_camera_with_movieclip(scene, clip);
2428         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2429         int tot = 0;
2430         float vec[2][3], mat[4][4], scale;
2431         float dist = RNA_float_get(op->ptr, "distance");
2432
2433         if (count_selected_bundles(C) != 2) {
2434                 BKE_report(op->reports, RPT_ERROR, "Two tracks with bundles should be selected to set scale");
2435
2436                 return OPERATOR_CANCELLED;
2437         }
2438
2439         if (!scale_solution && !apply_scale) {
2440                 object = get_orientation_object(C);
2441                 if (!object) {
2442                         BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2443
2444                         return OPERATOR_CANCELLED;
2445                 }
2446         }
2447
2448         BKE_tracking_get_camera_object_matrix(scene, camera, mat);
2449
2450         track = tracksbase->first;
2451         while (track) {
2452                 if (TRACK_VIEW_SELECTED(sc, track)) {
2453                         mul_v3_m4v3(vec[tot], mat, track->bundle_pos);
2454                         tot++;
2455                 }
2456
2457                 track = track->next;
2458         }
2459
2460         sub_v3_v3(vec[0], vec[1]);
2461
2462         if (len_v3(vec[0]) > 1e-5f) {
2463                 scale = dist / len_v3(vec[0]);
2464
2465                 if (apply_scale) {
2466                         /* Apply scale on reconstructed scene itself */
2467                         MovieTrackingReconstruction *reconstruction = BKE_tracking_get_active_reconstruction(tracking);
2468                         MovieReconstructedCamera *reconstructed_cameras;
2469                         int i;
2470
2471                         for (track = tracksbase->first; track; track = track->next) {
2472                                 mul_v3_fl(track->bundle_pos, scale);
2473                         }
2474
2475                         reconstructed_cameras = reconstruction->cameras;
2476                         for (i = 0; i < reconstruction->camnr; i++) {
2477                                 mul_v3_fl(reconstructed_cameras[i].mat[3], scale);
2478                         }
2479
2480                         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2481                         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2482                 }
2483                 else {
2484                         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2485                                 mul_v3_fl(object->size, scale);
2486                                 mul_v3_fl(object->loc, scale);
2487                         }
2488                         else if (!scale_solution) {
2489                                 Object *solver_camera = object_solver_camera(scene, object);
2490
2491                                 object->size[0] = object->size[1] = object->size[2] = 1.0f / scale;
2492
2493                                 if (solver_camera) {
2494                                         object->size[0] /= solver_camera->size[0];
2495                                         object->size[1] /= solver_camera->size[1];
2496                                         object->size[2] /= solver_camera->size[2];
2497                                 }
2498                         }
2499                         else {
2500                                 tracking_object->scale = scale;
2501                         }
2502
2503                         DAG_id_tag_update(&clip->id, 0);
2504
2505                         if (object)
2506                                 DAG_id_tag_update(&object->id, OB_RECALC_OB);
2507
2508                         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2509                         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2510                 }
2511         }
2512
2513         return OPERATOR_FINISHED;
2514 }
2515
2516 static int set_scale_exec(bContext *C, wmOperator *op)
2517 {
2518         return do_set_scale(C, op, false, false);
2519 }
2520
2521 static int set_scale_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2522 {
2523         SpaceClip *sc = CTX_wm_space_clip(C);
2524         MovieClip *clip = ED_space_clip_get_clip(sc);
2525
2526         if (!RNA_struct_property_is_set(op->ptr, "distance"))
2527                 RNA_float_set(op->ptr, "distance", clip->tracking.settings.dist);
2528
2529         return set_scale_exec(C, op);
2530 }
2531
2532 void CLIP_OT_set_scale(wmOperatorType *ot)
2533 {
2534         /* identifiers */
2535         ot->name = "Set Scale";
2536         ot->description = "Set scale of scene by scaling camera (or it's parent if present)";
2537         ot->idname = "CLIP_OT_set_scale";
2538
2539         /* api callbacks */
2540         ot->exec = set_scale_exec;
2541         ot->invoke = set_scale_invoke;
2542         ot->poll = set_orientation_poll;
2543
2544         /* flags */
2545         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2546
2547         /* properties */
2548         RNA_def_float(ot->srna, "distance", 0.0f, -FLT_MAX, FLT_MAX,
2549                       "Distance", "Distance between selected tracks", -100.0f, 100.0f);
2550 }
2551
2552 /********************** set solution scale operator *********************/
2553
2554 static int set_solution_scale_poll(bContext *C)
2555 {
2556         SpaceClip *sc = CTX_wm_space_clip(C);
2557
2558         if (sc) {
2559                 MovieClip *clip = ED_space_clip_get_clip(sc);
2560
2561                 if (clip) {
2562                         MovieTracking *tracking = &clip->tracking;
2563                         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
2564
2565                         return (tracking_object->flag & TRACKING_OBJECT_CAMERA) == 0;
2566                 }
2567         }
2568
2569         return FALSE;
2570 }
2571
2572 static int set_solution_scale_exec(bContext *C, wmOperator *op)
2573 {
2574         return do_set_scale(C, op, true, false);
2575 }
2576
2577 static int set_solution_scale_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2578 {
2579         SpaceClip *sc = CTX_wm_space_clip(C);
2580         MovieClip *clip = ED_space_clip_get_clip(sc);
2581
2582         if (!RNA_struct_property_is_set(op->ptr, "distance"))
2583                 RNA_float_set(op->ptr, "distance", clip->tracking.settings.object_distance);
2584
2585         return set_solution_scale_exec(C, op);
2586 }
2587
2588 void CLIP_OT_set_solution_scale(wmOperatorType *ot)
2589 {
2590         /* identifiers */
2591         ot->name = "Set Solution Scale";
2592         ot->description = "Set object solution scale using distance between two selected tracks";
2593         ot->idname = "CLIP_OT_set_solution_scale";
2594
2595         /* api callbacks */
2596         ot->exec = set_solution_scale_exec;
2597         ot->invoke = set_solution_scale_invoke;
2598         ot->poll = set_solution_scale_poll;
2599
2600         /* flags */
2601         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2602
2603         /* properties */
2604         RNA_def_float(ot->srna, "distance", 0.0f, -FLT_MAX, FLT_MAX,
2605                       "Distance", "Distance between selected tracks", -100.0f, 100.0f);
2606 }
2607
2608 /********************** apply solution scale operator *********************/
2609
2610 static int apply_solution_scale_poll(bContext *C)
2611 {
2612         SpaceClip *sc = CTX_wm_space_clip(C);
2613
2614         if (sc) {
2615                 MovieClip *clip = ED_space_clip_get_clip(sc);
2616
2617                 if (clip) {
2618                         MovieTracking *tracking = &clip->tracking;
2619                         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
2620
2621                         return tracking_object->flag & TRACKING_OBJECT_CAMERA;
2622                 }
2623         }
2624
2625         return FALSE;
2626 }
2627
2628 static int apply_solution_scale_exec(bContext *C, wmOperator *op)
2629 {
2630         return do_set_scale(C, op, false, true);
2631 }
2632
2633 static int apply_solution_scale_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2634 {
2635         SpaceClip *sc = CTX_wm_space_clip(C);
2636         MovieClip *clip = ED_space_clip_get_clip(sc);
2637
2638         if (!RNA_struct_property_is_set(op->ptr, "distance"))
2639                 RNA_float_set(op->ptr, "distance", clip->tracking.settings.dist);
2640
2641         return apply_solution_scale_exec(C, op);
2642 }
2643
2644 void CLIP_OT_apply_solution_scale(wmOperatorType *ot)
2645 {
2646         /* identifiers */
2647         ot->name = "Apply Solution Scale";
2648         ot->description = "Apply scale on solution itself to make distance between selected tracks equals to desired";
2649         ot->idname = "CLIP_OT_apply_solution_scale";
2650
2651         /* api callbacks */
2652         ot->exec = apply_solution_scale_exec;
2653         ot->invoke = apply_solution_scale_invoke;
2654         ot->poll = apply_solution_scale_poll;
2655
2656         /* flags */
2657         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2658
2659         /* properties */
2660         RNA_def_float(ot->srna, "distance", 0.0f, -FLT_MAX, FLT_MAX,
2661                       "Distance", "Distance between selected tracks", -100.0f, 100.0f);
2662 }
2663
2664 /********************** set principal center operator *********************/
2665
2666 static int set_center_principal_exec(bContext *C, wmOperator *UNUSED(op))
2667 {
2668         SpaceClip *sc = CTX_wm_space_clip(C);
2669         MovieClip *clip = ED_space_clip_get_clip(sc);
2670         int width, height;
2671
2672         BKE_movieclip_get_size(clip, &sc->user, &width, &height);
2673
2674         if (width == 0 || height == 0)
2675                 return OPERATOR_CANCELLED;
2676
2677         clip->tracking.camera.principal[0] = ((float)width) / 2.0f;
2678         clip->tracking.camera.principal[1] = ((float)height) / 2.0f;
2679
2680         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
2681
2682         return OPERATOR_FINISHED;
2683 }
2684
2685 void CLIP_OT_set_center_principal(wmOperatorType *ot)
2686 {
2687         /* identifiers */
2688         ot->name = "Set Principal to Center";
2689         ot->description = "Set optical center to center of footage";
2690         ot->idname = "CLIP_OT_set_center_principal";
2691
2692         /* api callbacks */
2693         ot->exec = set_center_principal_exec;
2694         ot->poll = ED_space_clip_tracking_poll;
2695
2696         /* flags */
2697         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2698 }
2699
2700 /********************** hide tracks operator *********************/
2701
2702 static int hide_tracks_exec(bContext *C, wmOperator *op)
2703 {
2704         SpaceClip *sc = CTX_wm_space_clip(C);
2705         MovieClip *clip = ED_space_clip_get_clip(sc);
2706         MovieTrackingTrack *track;
2707         MovieTracking *tracking = &clip->tracking;
2708         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2709         MovieTrackingTrack *act_track = BKE_tracking_track_get_active(tracking);
2710         int unselected;
2711
2712         unselected = RNA_boolean_get(op->ptr, "unselected");
2713
2714         track = tracksbase->first;
2715         while (track) {
2716                 if (unselected == 0 && TRACK_VIEW_SELECTED(sc, track)) {
2717                         track->flag |= TRACK_HIDDEN;
2718                 }
2719                 else if (unselected == 1 && !TRACK_VIEW_SELECTED(sc, track)) {
2720                         track->flag |= TRACK_HIDDEN;
2721                 }
2722
2723                 track = track->next;
2724         }
2725
2726         if (act_track && act_track->flag & TRACK_HIDDEN)
2727                 clip->tracking.act_track = NULL;
2728
2729         if (unselected == 0) {
2730                 /* no selection on screen now, unlock view so it can be scrolled nice again */
2731                 sc->flag &= ~SC_LOCK_SELECTION;
2732         }
2733
2734         BKE_tracking_dopesheet_tag_update(tracking);
2735
2736         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
2737
2738         return OPERATOR_FINISHED;
2739 }
2740
2741 void CLIP_OT_hide_tracks(wmOperatorType *ot)
2742 {
2743         /* identifiers */
2744         ot->name = "Hide Tracks";
2745         ot->description = "Hide selected tracks";
2746         ot->idname = "CLIP_OT_hide_tracks";
2747
2748         /* api callbacks */
2749         ot->exec = hide_tracks_exec;
2750         ot->poll = ED_space_clip_tracking_poll;
2751
2752         /* flags */
2753         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2754
2755         /* properties */
2756         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected tracks");
2757 }
2758
2759 /********************** hide tracks clear operator *********************/
2760
2761 static int hide_tracks_clear_exec(bContext *C, wmOperator *UNUSED(op))
2762 {
2763         SpaceClip *sc = CTX_wm_space_clip(C);
2764         MovieClip *clip = ED_space_clip_get_clip(sc);
2765         MovieTracking *tracking = &clip->tracking;
2766         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2767         MovieTrackingTrack *track;
2768
2769         track = tracksbase->first;
2770         while (track) {
2771                 track->flag &= ~TRACK_HIDDEN;
2772
2773                 track = track->next;
2774         }
2775
2776         BKE_tracking_dopesheet_tag_update(tracking);
2777
2778         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
2779
2780         return OPERATOR_FINISHED;
2781 }
2782
2783 void CLIP_OT_hide_tracks_clear(wmOperatorType *ot)
2784 {
2785         /* identifiers */
2786         ot->name = "Hide Tracks Clear";
2787         ot->description = "Clear hide selected tracks";
2788         ot->idname = "CLIP_OT_hide_tracks_clear";
2789
2790         /* api callbacks */
2791         ot->exec = hide_tracks_clear_exec;
2792         ot->poll = ED_space_clip_tracking_poll;
2793
2794         /* flags */
2795         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2796 }
2797
2798 /********************** detect features operator *********************/
2799
2800 static bGPDlayer *detect_get_layer(MovieClip *clip)
2801 {
2802         bGPDlayer *layer;
2803
2804         if (!clip->gpd)
2805                 return NULL;
2806
2807         layer = clip->gpd->layers.first;
2808         while (layer) {
2809                 if (layer->flag & GP_LAYER_ACTIVE)
2810                         return layer;
2811
2812                 layer = layer->next;
2813         }
2814
2815         return NULL;
2816 }
2817
2818 static int detect_features_exec(bContext *C, wmOperator *op)
2819 {
2820         SpaceClip *sc = CTX_wm_space_clip(C);
2821         MovieClip *clip = ED_space_clip_get_clip(sc);
2822         int clip_flag = clip->flag & MCLIP_TIMECODE_FLAGS;
2823         ImBuf *ibuf = BKE_movieclip_get_ibuf_flag(clip, &sc->user, clip_flag, MOVIECLIP_CACHE_SKIP);
2824         MovieTracking *tracking = &clip->tracking;
2825         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2826         MovieTrackingTrack *track = tracksbase->first;
2827         int placement = RNA_enum_get(op->ptr, "placement");
2828         int margin = RNA_int_get(op->ptr, "margin");
2829         int min_trackability = RNA_int_get(op->ptr, "min_trackability");
2830         int min_distance = RNA_int_get(op->ptr, "min_distance");
2831         int place_outside_layer = 0;
2832         int framenr = ED_space_clip_get_clip_frame_number(sc);
2833         bGPDlayer *layer = NULL;
2834
2835         if (!ibuf) {
2836                 BKE_report(op->reports, RPT_ERROR, "Feature detection requires valid clip frame");
2837                 return OPERATOR_CANCELLED;
2838         }
2839
2840         if (placement != 0) {
2841                 layer = detect_get_layer(clip);
2842                 place_outside_layer = placement == 2;
2843         }
2844
2845         /* deselect existing tracks */
2846         while (track) {
2847                 track->flag &= ~SELECT;
2848                 track->pat_flag &= ~SELECT;
2849                 track->search_flag &= ~SELECT;
2850
2851                 track = track->next;
2852         }
2853
2854         BKE_tracking_detect_fast(tracking, tracksbase, ibuf, framenr, margin,
2855                                  min_trackability, min_distance, layer, place_outside_layer);
2856
2857         IMB_freeImBuf(ibuf);
2858
2859         BKE_tracking_dopesheet_tag_update(tracking);
2860         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
2861
2862         return OPERATOR_FINISHED;
2863 }
2864
2865 void CLIP_OT_detect_features(wmOperatorType *ot)
2866 {
2867         static EnumPropertyItem placement_items[] = {
2868                 {0, "FRAME",            0, "Whole Frame",           "Place markers across the whole frame"},
2869                 {1, "INSIDE_GPENCIL",   0, "Inside grease pencil",  "Place markers only inside areas outlined with grease pencil"},
2870                 {2, "OUTSIDE_GPENCIL",  0, "Outside grease pencil", "Place markers only outside areas outlined with grease pencil"},
2871                 {0, NULL, 0, NULL, NULL}
2872         };
2873
2874         /* identifiers */
2875         ot->name = "Detect Features";
2876         ot->description = "Automatically detect features and place markers to track";
2877         ot->idname = "CLIP_OT_detect_features";
2878
2879         /* api callbacks */
2880         ot->exec = detect_features_exec;
2881         ot->poll = ED_space_clip_tracking_poll;
2882
2883         /* flags */
2884         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2885
2886         /* properties */
2887         RNA_def_enum(ot->srna, "placement", placement_items, 0, "Placement", "Placement for detected features");
2888         RNA_def_int(ot->srna, "margin", 16, 0, INT_MAX, "Margin", "Only corners further than margin pixels from the image edges are considered", 0, 300);
2889         RNA_def_int(ot->srna, "min_trackability", 16, 0, INT_MAX, "Trackability", "Minimum trackability score to add a corner", 0, 300);
2890         RNA_def_int(ot->srna, "min_distance", 120, 0, INT_MAX, "Distance", "Minimal distance accepted between two corners", 0, 300);
2891 }
2892
2893 /********************** frame jump operator *********************/
2894
2895 static int frame_jump_exec(bContext *C, wmOperator *op)
2896 {
2897         Scene *scene = CTX_data_scene(C);
2898         SpaceClip *sc = CTX_wm_space_clip(C);
2899         MovieClip *clip = ED_space_clip_get_clip(sc);
2900         MovieTrackingTrack *track;
2901         int pos = RNA_enum_get(op->ptr, "position");
2902         int delta;
2903
2904         if (pos <= 1) { /* jump to path */
2905                 track = BKE_tracking_track_get_active(&clip->tracking);
2906
2907                 if (!track)
2908                         return OPERATOR_CANCELLED;
2909
2910                 delta = pos == 1 ? 1 : -1;
2911
2912                 while (sc->user.framenr + delta >= SFRA && sc->user.framenr + delta <= EFRA) {
2913                         int framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, sc->user.framenr + delta);
2914                         MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, framenr);
2915
2916                         if (!marker || marker->flag & MARKER_DISABLED)
2917                                 break;
2918
2919                         sc->user.framenr += delta;
2920                 }
2921         }
2922         else {  /* to to failed frame */
2923                 if (clip->tracking.reconstruction.flag & TRACKING_RECONSTRUCTED) {
2924                         int a = ED_space_clip_get_clip_frame_number(sc);
2925                         MovieTracking *tracking = &clip->tracking;
2926                         MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
2927
2928                         delta = pos == 3 ? 1 : -1;
2929
2930                         a += delta;
2931
2932                         while (a + delta >= SFRA && a + delta <= EFRA) {
2933                                 MovieReconstructedCamera *cam;
2934
2935                                 cam = BKE_tracking_camera_get_reconstructed(tracking, object, a);
2936
2937                                 if (!cam) {
2938                                         sc->user.framenr = BKE_movieclip_remap_clip_to_scene_frame(clip, a);
2939
2940                                         break;
2941                                 }
2942
2943                                 a += delta;
2944                         }
2945                 }
2946         }
2947
2948         if (CFRA != sc->user.framenr) {
2949                 CFRA = sc->user.framenr;
2950                 sound_seek_scene(CTX_data_main(C), CTX_data_scene(C));
2951
2952                 WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2953         }
2954
2955         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
2956
2957         return OPERATOR_FINISHED;
2958 }
2959
2960 void CLIP_OT_frame_jump(wmOperatorType *ot)
2961 {
2962         static EnumPropertyItem position_items[] = {
2963                 {0, "PATHSTART",    0, "Path Start",        "Jump to start of current path"},
2964                 {1, "PATHEND",      0, "Path End",          "Jump to end of current path"},
2965                 {2, "FAILEDPREV",   0, "Previous Failed",   "Jump to previous failed frame"},
2966                 {2, "FAILNEXT",     0, "Next Failed",       "Jump to next failed frame"},
2967                 {0, NULL, 0, NULL, NULL}
2968         };
2969
2970         /* identifiers */
2971         ot->name = "Jump to Frame";
2972         ot->description = "Jump to special frame";
2973         ot->idname = "CLIP_OT_frame_jump";
2974
2975         /* api callbacks */
2976         ot->exec = frame_jump_exec;
2977         ot->poll = ED_space_clip_poll;
2978
2979         /* flags */
2980         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2981
2982         /* properties */
2983         RNA_def_enum(ot->srna, "position", position_items, 0, "Position", "Position to jump to");
2984 }
2985
2986 /********************** join tracks operator *********************/
2987
2988 static int join_tracks_exec(bContext *C, wmOperator *op)
2989 {
2990         SpaceClip *sc = CTX_wm_space_clip(C);
2991         MovieClip *clip = ED_space_clip_get_clip(sc);
2992         MovieTracking *tracking = &clip->tracking;
2993         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2994         MovieTrackingTrack *act_track, *track, *next;
2995
2996         act_track = BKE_tracking_track_get_active(tracking);
2997
2998         if (!act_track) {
2999                 BKE_report(op->reports, RPT_ERROR, "No active track to join to");
3000                 return OPERATOR_CANCELLED;
3001         }
3002
3003         track = tracksbase->first;
3004         while (track) {
3005                 next = track->next;
3006
3007                 if (TRACK_VIEW_SELECTED(sc, track) && track != act_track) {
3008                         BKE_tracking_tracks_join(tracking, act_track, track);
3009
3010                         if (tracking->stabilization.rot_track == track)
3011                                 tracking->stabilization.rot_track = act_track;
3012
3013                         BKE_tracking_track_free(track);
3014                         BLI_freelinkN(tracksbase, track);
3015                 }
3016
3017                 track = next;
3018         }
3019
3020         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
3021
3022         return OPERATOR_FINISHED;
3023 }
3024
3025 void CLIP_OT_join_tracks(wmOperatorType *ot)
3026 {
3027         /* identifiers */
3028         ot->name = "Join Tracks";
3029         ot->description = "Join selected tracks";
3030         ot->idname = "CLIP_OT_join_tracks";
3031
3032         /* api callbacks */
3033         ot->exec = join_tracks_exec;
3034         ot->poll = ED_space_clip_tracking_poll;
3035
3036         /* flags */
3037         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3038 }
3039
3040 /********************** lock tracks operator *********************/
3041
3042 static int lock_tracks_exec(bContext *C, wmOperator *op)
3043 {
3044         SpaceClip *sc = CTX_wm_space_clip(C);
3045         MovieClip *clip = ED_space_clip_get_clip(sc);
3046         MovieTracking *tracking = &clip->tracking;
3047         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
3048         MovieTrackingTrack *track = tracksbase->first;
3049         int action = RNA_enum_get(op->ptr, "action");
3050
3051         while (track) {
3052                 if (TRACK_VIEW_SELECTED(sc, track)) {
3053                         if (action == 0)
3054                                 track->flag |= TRACK_LOCKED;
3055                         else if (action == 1)
3056                                 track->flag &= ~TRACK_LOCKED;
3057                         else track->flag ^= TRACK_LOCKED;
3058                 }
3059
3060                 track = track->next;
3061         }
3062
3063         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
3064
3065         return OPERATOR_FINISHED;
3066 }
3067
3068 void CLIP_OT_lock_tracks(wmOperatorType *ot)
3069 {
3070         static EnumPropertyItem actions_items[] = {
3071                 {0, "LOCK", 0, "Lock", "Lock selected tracks"},
3072                 {1, "UNLOCK", 0, "Unlock", "Unlock selected tracks"},
3073                 {2, "TOGGLE", 0, "Toggle", "Toggle locked flag for selected tracks"},
3074                 {0, NULL, 0, NULL, NULL}
3075         };
3076
3077         /* identifiers */
3078         ot->name = "Lock Tracks";
3079         ot->description = "Lock/unlock selected tracks";
3080         ot->idname = "CLIP_OT_lock_tracks";
3081
3082         /* api callbacks */
3083         ot->exec = lock_tracks_exec;
3084         ot->poll = ED_space_clip_tracking_poll;
3085
3086         /* flags */
3087         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3088
3089         /* properties */
3090         RNA_def_enum(ot->srna, "action", actions_items, 0, "Action", "Lock action to execute");
3091 }
3092
3093 /********************** set keyframe operator *********************/
3094
3095 static int set_solver_keyframe_exec(bContext *C, wmOperator *op)
3096 {
3097         SpaceClip *sc = CTX_wm_space_clip(C);
3098         MovieClip *clip = ED_space_clip_get_clip(sc);
3099         MovieTracking *tracking = &clip->tracking;
3100         MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
3101         int keyframe = RNA_enum_get(op->ptr, "keyframe");
3102         int framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, sc->user.framenr);
3103
3104         if (keyframe == 0)
3105                 object->keyframe1 = framenr;
3106         else
3107                 object->keyframe2 = framenr;
3108
3109         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
3110
3111         return OPERATOR_FINISHED;
3112 }
3113
3114 void CLIP_OT_set_solver_keyframe(wmOperatorType *ot)
3115 {
3116         static EnumPropertyItem keyframe_items[] = {
3117                 {0, "KEYFRAME_A", 0, "Keyframe A", ""},
3118                 {1, "KEYFRAME_B", 0, "Keyframe B", ""},
3119                 {0, NULL, 0, NULL, NULL}
3120         };
3121
3122         /* identifiers */
3123         ot->name = "Set Solver Keyframe";
3124         ot->description = "Set keyframe used by solver";
3125         ot->idname = "CLIP_OT_set_solver_keyframe";
3126
3127         /* api callbacks */
3128         ot->exec = set_solver_keyframe_exec;
3129         ot->poll = ED_space_clip_tracking_poll;
3130
3131         /* flags */
3132         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3133
3134         /* properties */
3135         RNA_def_enum(ot->srna, "keyframe", keyframe_items, 0, "Keyframe", "Keyframe to set");
3136 }
3137
3138 /********************** track copy color operator *********************/
3139
3140 static int track_copy_color_exec(bContext *C, wmOperator *UNUSED(op))
3141 {
3142         SpaceClip *sc = CTX_wm_space_clip(C);
3143         MovieClip *clip = ED_space_clip_get_clip(sc);
3144         MovieTracking *tracking = &clip->tracking;
3145         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
3146         MovieTrackingTrack *track, *act_track = BKE_tracking_track_get_active(tracking);
3147
3148         if (!act_track)
3149                 return OPERATOR_CANCELLED;
3150
3151         track = tracksbase->first;
3152         while (track) {
3153                 if (TRACK_VIEW_SELECTED(sc, track) && track != act_track) {
3154                         track->flag &= ~TRACK_CUSTOMCOLOR;
3155
3156                         if (act_track->flag & TRACK_CUSTOMCOLOR) {
3157                                 copy_v3_v3(track->color, act_track->color);
3158                                 track->flag |= TRACK_CUSTOMCOLOR;
3159                         }
3160                 }
3161
3162                 track = track->next;
3163         }
3164
3165         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
3166
3167         return OPERATOR_FINISHED;
3168 }
3169
3170 void CLIP_OT_track_copy_color(wmOperatorType *ot)
3171 {
3172         /* identifiers */
3173         ot->name = "Copy Color";
3174         ot->description = "Copy color to all selected tracks";
3175         ot->idname = "CLIP_OT_track_copy_color";
3176
3177         /* api callbacks */
3178         ot->exec = track_copy_color_exec;
3179         ot->poll = ED_space_clip_tracking_poll;
3180
3181         /* flags */
3182         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3183 }
3184
3185 /********************** add 2d stabilization tracks operator *********************/
3186
3187 static int stabilize_2d_poll(bContext *C)
3188 {
3189         if (ED_space_clip_tracking_poll(C)) {
3190                 SpaceClip *sc = CTX_wm_space_clip(C);
3191                 MovieClip *clip = ED_space_clip_get_clip(sc);
3192                 MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(&clip->tracking);
3193
3194                 return tracking_object->flag & TRACKING_OBJECT_CAMERA;
3195         }
3196
3197         return FALSE;
3198 }
3199
3200 static int stabilize_2d_add_exec(bContext *C, wmOperator *UNUSED(op))
3201 {
3202         SpaceClip *sc = CTX_wm_space_clip(C);
3203         MovieClip *clip = ED_space_clip_get_clip(sc);
3204         MovieTracking *tracking = &clip->tracking;
3205         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
3206         MovieTrackingTrack *track;
3207         MovieTrackingStabilization *stab = &tracking->stabilization;
3208         int update = 0;
3209
3210         track = tracksbase->first;
3211         while (track) {
3212                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_USE_2D_STAB) == 0) {
3213                         track->flag |= TRACK_USE_2D_STAB;
3214                         stab->tot_track++;
3215
3216                         update = 1;
3217                 }
3218
3219                 track = track->next;
3220         }
3221
3222         if (update) {
3223                 stab->ok = 0;
3224
3225                 DAG_id_tag_update(&clip->id, 0);
3226                 WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
3227         }
3228
3229         return OPERATOR_FINISHED;
3230 }
3231
3232 void CLIP_OT_stabilize_2d_add(wmOperatorType *ot)
3233 {
3234         /* identifiers */
3235         ot->name = "Add Stabilization Tracks";
3236         ot->description = "Add selected tracks to 2D stabilization tool";
3237         ot->idname = "CLIP_OT_stabilize_2d_add";
3238
3239         /* api callbacks */
3240         ot->exec = stabilize_2d_add_exec;
3241         ot->poll = stabilize_2d_poll;
3242
3243         /* flags */
3244         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3245 }
3246
3247 /********************** remove 2d stabilization tracks operator *********************/
3248
3249 static int stabilize_2d_remove_exec(bContext *C, wmOperator *UNUSED(op))
3250 {
3251         SpaceClip *sc = CTX_wm_space_clip(C);
3252         MovieClip *clip = ED_space_clip_get_clip(sc);
3253         MovieTracking *tracking = &clip->tracking;
3254         MovieTrackingStabilization *stab = &tracking->stabilization;
3255         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
3256         MovieTrackingTrack *track;
3257         int a = 0, update = 0;
3258
3259         track = tracksbase->first;
3260         while (track) {