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