Cleanup: transform snap arguments
[blender.git] / source / blender / editors / armature / editarmature_sketch.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  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/editors/armature/editarmature_sketch.c
22  *  \ingroup edarmature
23  */
24
25 #include "MEM_guardedalloc.h"
26
27 #include "DNA_object_types.h"
28 #include "DNA_scene_types.h"
29 #include "DNA_armature_types.h"
30
31 #include "BLI_blenlib.h"
32 #include "BLI_math.h"
33
34 #include "BKE_context.h"
35 #include "BKE_sketch.h"
36
37 #include "RNA_define.h"
38 #include "RNA_access.h"
39
40 #include "ED_view3d.h"
41 #include "ED_screen.h"
42
43 #include "BIF_gl.h"
44 #include "ED_armature.h"
45 #include "armature_intern.h"
46 #include "BIF_retarget.h"
47 #include "BIF_generate.h"
48
49 #include "ED_transform.h"
50
51 #include "WM_api.h"
52 #include "WM_types.h"
53
54 #include "GPU_select.h"
55
56 typedef int (*GestureDetectFct)(bContext *, SK_Gesture *, SK_Sketch *);
57 typedef void (*GestureApplyFct)(bContext *, SK_Gesture *, SK_Sketch *);
58
59 typedef struct SK_GestureAction {
60         char name[64];
61         GestureDetectFct detect;
62         GestureApplyFct apply;
63 } SK_GestureAction;
64
65 #if 0 /* UNUSED 2.5 */
66 static SK_Point boneSnap;
67 #endif
68
69 static int LAST_SNAP_POINT_VALID = 0;
70 static float LAST_SNAP_POINT[3];
71
72
73 typedef struct SK_StrokeIterator {
74         HeadFct     head;
75         TailFct     tail;
76         PeekFct     peek;
77         NextFct     next;
78         NextNFct    nextN;
79         PreviousFct previous;
80         StoppedFct  stopped;
81
82         float *p, *no;
83         float size;
84
85         int length;
86         int index;
87         /*********************************/
88         SK_Stroke *stroke;
89         int start;
90         int end;
91         int stride;
92 } SK_StrokeIterator;
93
94 /******************** PROTOTYPES ******************************/
95
96 void initStrokeIterator(BArcIterator *iter, SK_Stroke *stk, int start, int end);
97
98 int sk_detectCutGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
99 void sk_applyCutGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
100 int sk_detectTrimGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
101 void sk_applyTrimGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
102 int sk_detectCommandGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
103 void sk_applyCommandGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
104 int sk_detectDeleteGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
105 void sk_applyDeleteGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
106 int sk_detectMergeGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
107 void sk_applyMergeGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
108 int sk_detectReverseGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
109 void sk_applyReverseGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
110 int sk_detectConvertGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
111 void sk_applyConvertGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch);
112
113 SK_Sketch *contextSketch(const bContext *c, int create);
114 SK_Sketch *viewcontextSketch(ViewContext *vc, int create);
115
116 void sk_resetOverdraw(SK_Sketch *sketch);
117 int sk_hasOverdraw(SK_Sketch *sketch, SK_Stroke *stk);
118
119 /******************** GESTURE ACTIONS ******************************/
120
121 static SK_GestureAction GESTURE_ACTIONS[] = {
122         {"Cut", sk_detectCutGesture, sk_applyCutGesture},
123         {"Trim", sk_detectTrimGesture, sk_applyTrimGesture},
124         {"Command", sk_detectCommandGesture, sk_applyCommandGesture},
125         {"Delete", sk_detectDeleteGesture, sk_applyDeleteGesture},
126         {"Merge", sk_detectMergeGesture, sk_applyMergeGesture},
127         {"Reverse", sk_detectReverseGesture, sk_applyReverseGesture},
128         {"Convert", sk_detectConvertGesture, sk_applyConvertGesture},
129         {"", NULL, NULL}
130 };
131
132 /******************** TEMPLATES UTILS *************************/
133
134 static char  *TEMPLATES_MENU = NULL;
135 static int TEMPLATES_CURRENT = 0;
136 static GHash *TEMPLATES_HASH = NULL;
137 static RigGraph *TEMPLATE_RIGG = NULL;
138
139 void BIF_makeListTemplates(const bContext *C)
140 {
141         Object *obedit = CTX_data_edit_object(C);
142         Scene *scene = CTX_data_scene(C);
143         ToolSettings *ts = CTX_data_tool_settings(C);
144         Base *base;
145         int index = 0;
146
147         if (TEMPLATES_HASH != NULL) {
148                 BLI_ghash_free(TEMPLATES_HASH, NULL, NULL);
149         }
150
151         TEMPLATES_HASH = BLI_ghash_int_new("makeListTemplates gh");
152         TEMPLATES_CURRENT = 0;
153
154         for (base = FIRSTBASE; base; base = base->next) {
155                 Object *ob = base->object;
156
157                 if (ob != obedit && ob->type == OB_ARMATURE) {
158                         index++;
159                         BLI_ghash_insert(TEMPLATES_HASH, SET_INT_IN_POINTER(index), ob);
160
161                         if (ob == ts->skgen_template) {
162                                 TEMPLATES_CURRENT = index;
163                         }
164                 }
165         }
166 }
167
168 #if 0  /* UNUSED */
169 const char *BIF_listTemplates(const bContext *UNUSED(C))
170 {
171         GHashIterator ghi;
172         const char *menu_header = IFACE_("Template %t|None %x0|");
173         char *p;
174         const size_t template_size = (BLI_ghash_size(TEMPLATES_HASH) * 32 + 30);
175
176         if (TEMPLATES_MENU != NULL) {
177                 MEM_freeN(TEMPLATES_MENU);
178         }
179
180         TEMPLATES_MENU = MEM_callocN(sizeof(char) * template_size, "skeleton template menu");
181
182         p = TEMPLATES_MENU;
183         p += BLI_strncpy_rlen(p, menu_header, template_size);
184
185         BLI_ghashIterator_init(&ghi, TEMPLATES_HASH);
186
187         while (!BLI_ghashIterator_done(&ghi)) {
188                 Object *ob = BLI_ghashIterator_getValue(&ghi);
189                 int key = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&ghi));
190
191                 p += sprintf(p, "|%s %%x%i", ob->id.name + 2, key);
192
193                 BLI_ghashIterator_step(&ghi);
194         }
195
196         return TEMPLATES_MENU;
197 }
198 #endif
199
200 int   BIF_currentTemplate(const bContext *C)
201 {
202         ToolSettings *ts = CTX_data_tool_settings(C);
203
204         if (TEMPLATES_CURRENT == 0 && ts->skgen_template != NULL) {
205                 GHashIterator ghi;
206                 BLI_ghashIterator_init(&ghi, TEMPLATES_HASH);
207
208                 while (!BLI_ghashIterator_done(&ghi)) {
209                         Object *ob = BLI_ghashIterator_getValue(&ghi);
210                         int key = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&ghi));
211
212                         if (ob == ts->skgen_template) {
213                                 TEMPLATES_CURRENT = key;
214                                 break;
215                         }
216
217                         BLI_ghashIterator_step(&ghi);
218                 }
219         }
220
221         return TEMPLATES_CURRENT;
222 }
223
224 static RigGraph *sk_makeTemplateGraph(const bContext *C, Object *ob)
225 {
226         Object *obedit = CTX_data_edit_object(C);
227         if (ob == obedit) {
228                 return NULL;
229         }
230
231         if (ob != NULL) {
232                 if (TEMPLATE_RIGG && TEMPLATE_RIGG->ob != ob) {
233                         RIG_freeRigGraph((BGraph *)TEMPLATE_RIGG);
234                         TEMPLATE_RIGG = NULL;
235                 }
236
237                 if (TEMPLATE_RIGG == NULL) {
238                         bArmature *arm;
239
240                         arm = ob->data;
241
242                         TEMPLATE_RIGG = RIG_graphFromArmature(C, ob, arm);
243                 }
244         }
245
246         return TEMPLATE_RIGG;
247 }
248
249 int BIF_nbJointsTemplate(const bContext *C)
250 {
251         ToolSettings *ts = CTX_data_tool_settings(C);
252         RigGraph *rg = sk_makeTemplateGraph(C, ts->skgen_template);
253
254         if (rg) {
255                 return RIG_nbJoints(rg);
256         }
257         else {
258                 return -1;
259         }
260 }
261
262 const char *BIF_nameBoneTemplate(const bContext *C)
263 {
264         ToolSettings *ts = CTX_data_tool_settings(C);
265         SK_Sketch *stk = contextSketch(C, 1);
266         RigGraph *rg;
267         int index = 0;
268
269         if (stk && stk->active_stroke != NULL) {
270                 index = stk->active_stroke->nb_points;
271         }
272
273         rg = sk_makeTemplateGraph(C, ts->skgen_template);
274
275         if (rg == NULL) {
276                 return "";
277         }
278
279         return RIG_nameBone(rg, 0, index);
280 }
281
282 void  BIF_freeTemplates(bContext *UNUSED(C))
283 {
284         if (TEMPLATES_MENU != NULL) {
285                 MEM_freeN(TEMPLATES_MENU);
286                 TEMPLATES_MENU = NULL;
287         }
288
289         if (TEMPLATES_HASH != NULL) {
290                 BLI_ghash_free(TEMPLATES_HASH, NULL, NULL);
291                 TEMPLATES_HASH = NULL;
292         }
293
294         if (TEMPLATE_RIGG != NULL) {
295                 RIG_freeRigGraph((BGraph *)TEMPLATE_RIGG);
296                 TEMPLATE_RIGG = NULL;
297         }
298 }
299
300 void  BIF_setTemplate(bContext *C, int index)
301 {
302         ToolSettings *ts = CTX_data_tool_settings(C);
303         if (index > 0) {
304                 ts->skgen_template = BLI_ghash_lookup(TEMPLATES_HASH, SET_INT_IN_POINTER(index));
305         }
306         else {
307                 ts->skgen_template = NULL;
308
309                 if (TEMPLATE_RIGG != NULL) {
310                         RIG_freeRigGraph((BGraph *)TEMPLATE_RIGG);
311                 }
312                 TEMPLATE_RIGG = NULL;
313         }
314 }
315
316 /*********************** CONVERSION ***************************/
317
318 static void sk_autoname(bContext *C, ReebArc *arc)
319 {
320         ToolSettings *ts = CTX_data_tool_settings(C);
321         if (ts->skgen_retarget_options & SK_RETARGET_AUTONAME) {
322                 if (arc == NULL) {
323                         char *num = ts->skgen_num_string;
324                         int i = atoi(num);
325                         i++;
326                         BLI_snprintf(num, 8, "%i", i);
327                 }
328                 else {
329                         char *side = ts->skgen_side_string;
330                         int valid = 0;
331                         int caps = 0;
332
333                         if (side[0] == '\0') {
334                                 valid = 1;
335                         }
336                         else if (STREQ(side, "R") || STREQ(side, "L")) {
337                                 valid = 1;
338                                 caps = 1;
339                         }
340                         else if (STREQ(side, "r") || STREQ(side, "l")) {
341                                 valid = 1;
342                                 caps = 0;
343                         }
344
345                         if (valid) {
346                                 if (arc->head->p[0] < 0) {
347                                         BLI_snprintf(side, 8, caps ? "R" : "r");
348                                 }
349                                 else {
350                                         BLI_snprintf(side, 8, caps ? "L" : "l");
351                                 }
352                         }
353                 }
354         }
355 }
356
357 static ReebNode *sk_pointToNode(SK_Point *pt, float imat[4][4], float tmat[3][3])
358 {
359         ReebNode *node;
360
361         node = MEM_callocN(sizeof(ReebNode), "reeb node");
362         copy_v3_v3(node->p, pt->p);
363         mul_m4_v3(imat, node->p);
364
365         copy_v3_v3(node->no, pt->no);
366         mul_m3_v3(tmat, node->no);
367
368         return node;
369 }
370
371 static ReebArc *sk_strokeToArc(SK_Stroke *stk, float imat[4][4], float tmat[3][3])
372 {
373         ReebArc *arc;
374         int i;
375
376         arc = MEM_callocN(sizeof(ReebArc), "reeb arc");
377         arc->head = sk_pointToNode(stk->points, imat, tmat);
378         arc->tail = sk_pointToNode(sk_lastStrokePoint(stk), imat, tmat);
379
380         arc->bcount = stk->nb_points - 2; /* first and last are nodes, don't count */
381         arc->buckets = MEM_callocN(sizeof(EmbedBucket) * arc->bcount, "Buckets");
382
383         for (i = 0; i < arc->bcount; i++) {
384                 copy_v3_v3(arc->buckets[i].p, stk->points[i + 1].p);
385                 mul_m4_v3(imat, arc->buckets[i].p);
386
387                 copy_v3_v3(arc->buckets[i].no, stk->points[i + 1].no);
388                 mul_m3_v3(tmat, arc->buckets[i].no);
389         }
390
391         return arc;
392 }
393
394 static void sk_retargetStroke(bContext *C, SK_Stroke *stk)
395 {
396         ToolSettings *ts = CTX_data_tool_settings(C);
397         Object *obedit = CTX_data_edit_object(C);
398         float imat[4][4];
399         float tmat[3][3];
400         ReebArc *arc;
401         RigGraph *rg;
402
403         invert_m4_m4(imat, obedit->obmat);
404         transpose_m3_m4(tmat, obedit->obmat);
405
406         arc = sk_strokeToArc(stk, imat, tmat);
407
408         sk_autoname(C, arc);
409
410         rg = sk_makeTemplateGraph(C, ts->skgen_template);
411
412         BIF_retargetArc(C, arc, rg);
413
414         sk_autoname(C, NULL);
415
416         MEM_freeN(arc->head);
417         MEM_freeN(arc->tail);
418         REEB_freeArc((BArc *)arc);
419 }
420
421 /**************************************************************/
422
423 static void sk_cancelStroke(SK_Sketch *sketch)
424 {
425         if (sketch->active_stroke != NULL) {
426                 sk_resetOverdraw(sketch);
427                 sk_removeStroke(sketch, sketch->active_stroke);
428         }
429 }
430
431
432 static float sk_clampPointSize(SK_Point *pt, float size)
433 {
434         return max_ff(size * pt->size, size / 2);
435 }
436
437 static void sk_drawPoint(GLUquadric *quad, SK_Point *pt, float size)
438 {
439         glTranslate3fv(pt->p);
440         gluSphere(quad, sk_clampPointSize(pt, size), 8, 8);
441 }
442
443 static void sk_drawEdge(GLUquadric *quad, SK_Point *pt0, SK_Point *pt1, float size)
444 {
445         float vec1[3], vec2[3] = {0, 0, 1}, axis[3];
446         float angle, length;
447
448         sub_v3_v3v3(vec1, pt1->p, pt0->p);
449         length = normalize_v3(vec1);
450         cross_v3_v3v3(axis, vec2, vec1);
451
452         if (is_zero_v3(axis)) {
453                 axis[1] = 1;
454         }
455
456         angle = angle_normalized_v3v3(vec2, vec1);
457
458         glRotate3fv(angle * (float)(180.0 / M_PI) + 180.0f, axis);
459
460         gluCylinder(quad, sk_clampPointSize(pt1, size), sk_clampPointSize(pt0, size), length, 8, 8);
461 }
462
463 static void sk_drawNormal(GLUquadric *quad, SK_Point *pt, float size, float height)
464 {
465         float vec2[3] = {0, 0, 1}, axis[3];
466         float angle;
467         
468         glPushMatrix();
469
470         cross_v3_v3v3(axis, vec2, pt->no);
471
472         if (is_zero_v3(axis)) {
473                 axis[1] = 1;
474         }
475
476         angle = angle_normalized_v3v3(vec2, pt->no);
477
478         glRotate3fv(angle * (float)(180.0 / M_PI), axis);
479
480         glColor3f(0, 1, 1);
481         gluCylinder(quad, sk_clampPointSize(pt, size), 0, sk_clampPointSize(pt, height), 10, 2);
482
483         glPopMatrix();
484 }
485
486 static void sk_drawStroke(SK_Stroke *stk, int id, float color[3], int start, int end)
487 {
488         float rgb[3];
489         int i;
490         GLUquadric *quad = gluNewQuadric();
491         gluQuadricNormals(quad, GLU_SMOOTH);
492
493         if (id != -1) {
494                 GPU_select_load_id(id);
495
496                 for (i = 0; i < stk->nb_points; i++) {
497                         glPushMatrix();
498
499                         sk_drawPoint(quad, stk->points + i, 0.1);
500
501                         if (i > 0) {
502                                 sk_drawEdge(quad, stk->points + i - 1, stk->points + i, 0.1);
503                         }
504
505                         glPopMatrix();
506                 }
507
508         }
509         else {
510                 float d_rgb[3] = {1, 1, 1};
511
512                 copy_v3_v3(rgb, color);
513                 sub_v3_v3(d_rgb, rgb);
514                 mul_v3_fl(d_rgb, 1.0f / (float)stk->nb_points);
515
516                 for (i = 0; i < stk->nb_points; i++) {
517                         SK_Point *pt = stk->points + i;
518
519                         glPushMatrix();
520
521                         if (pt->type == PT_EXACT) {
522                                 glColor3f(0, 0, 0);
523                                 sk_drawPoint(quad, pt, 0.15);
524                                 sk_drawNormal(quad, pt, 0.05, 0.9);
525                         }
526
527                         if (i >= start && i <= end) {
528                                 glColor3f(0.3, 0.3, 0.3);
529                         }
530                         else {
531                                 glColor3fv(rgb);
532                         }
533
534                         if (pt->type != PT_EXACT) {
535
536                                 sk_drawPoint(quad, pt, 0.1);
537                         }
538
539                         if (i > 0) {
540                                 sk_drawEdge(quad, pt - 1, pt, 0.1);
541                         }
542
543                         glPopMatrix();
544
545                         add_v3_v3(rgb, d_rgb);
546                 }
547         }
548
549         gluDeleteQuadric(quad);
550 }
551
552 static void drawSubdividedStrokeBy(ToolSettings *toolsettings, BArcIterator *iter, NextSubdivisionFunc next_subdividion)
553 {
554         SK_Stroke *stk = ((SK_StrokeIterator *)iter)->stroke;
555         float head[3], tail[3];
556         int bone_start = 0;
557         int end = iter->length;
558         int index;
559         GLUquadric *quad = gluNewQuadric();
560         gluQuadricNormals(quad, GLU_SMOOTH);
561
562         iter->head(iter);
563         copy_v3_v3(head, iter->p);
564
565         index = next_subdividion(toolsettings, iter, bone_start, end, head, tail);
566         while (index != -1) {
567                 SK_Point *pt = stk->points + index;
568
569                 glPushMatrix();
570
571                 glColor3f(0, 1, 0);
572                 sk_drawPoint(quad, pt, 0.15);
573
574                 sk_drawNormal(quad, pt, 0.05, 0.9);
575
576                 glPopMatrix();
577
578                 copy_v3_v3(head, tail);
579                 bone_start = index; // start next bone from current index
580
581                 index = next_subdividion(toolsettings, iter, bone_start, end, head, tail);
582         }
583
584         gluDeleteQuadric(quad);
585 }
586
587 static void sk_drawStrokeSubdivision(ToolSettings *toolsettings, SK_Stroke *stk)
588 {
589         int head_index = -1;
590         int i;
591
592         if (toolsettings->bone_sketching_convert == SK_CONVERT_RETARGET) {
593                 return;
594         }
595
596
597         for (i = 0; i < stk->nb_points; i++) {
598                 SK_Point *pt = stk->points + i;
599
600                 if (pt->type == PT_EXACT || i == stk->nb_points - 1) /* stop on exact or on last point */ {
601                         if (head_index == -1) {
602                                 head_index = i;
603                         }
604                         else {
605                                 if (i - head_index > 1) {
606                                         SK_StrokeIterator sk_iter;
607                                         BArcIterator *iter = (BArcIterator *)&sk_iter;
608
609                                         initStrokeIterator(iter, stk, head_index, i);
610
611                                         if (toolsettings->bone_sketching_convert == SK_CONVERT_CUT_ADAPTATIVE) {
612                                                 drawSubdividedStrokeBy(toolsettings, iter, nextAdaptativeSubdivision);
613                                         }
614                                         else if (toolsettings->bone_sketching_convert == SK_CONVERT_CUT_LENGTH) {
615                                                 drawSubdividedStrokeBy(toolsettings, iter, nextLengthSubdivision);
616                                         }
617                                         else if (toolsettings->bone_sketching_convert == SK_CONVERT_CUT_FIXED) {
618                                                 drawSubdividedStrokeBy(toolsettings, iter, nextFixedSubdivision);
619                                         }
620
621                                 }
622
623                                 head_index = i;
624                         }
625                 }
626         }
627 }
628
629 static SK_Point *sk_snapPointStroke(bContext *C, SK_Stroke *stk, int mval[2], float *r_dist_px, int *index, int all_pts)
630 {
631         ARegion *ar = CTX_wm_region(C);
632         SK_Point *pt = NULL;
633         int i;
634
635         for (i = 0; i < stk->nb_points; i++) {
636                 if (all_pts || stk->points[i].type == PT_EXACT) {
637                         short pval[2];
638                         int pdist;
639
640                         if (ED_view3d_project_short_global(ar, stk->points[i].p, pval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
641
642                                 pdist = ABS(pval[0] - mval[0]) + ABS(pval[1] - mval[1]);
643
644                                 if (pdist < *r_dist_px) {
645                                         *r_dist_px = pdist;
646                                         pt = stk->points + i;
647
648                                         if (index != NULL) {
649                                                 *index = i;
650                                         }
651                                 }
652                         }
653                 }
654         }
655
656         return pt;
657 }
658
659 #if 0 /* UNUSED 2.5 */
660 static SK_Point *sk_snapPointArmature(bContext *C, Object *ob, ListBase *ebones, int mval[2], int *dist)
661 {
662         ARegion *ar = CTX_wm_region(C);
663         SK_Point *pt = NULL;
664         EditBone *bone;
665
666         for (bone = ebones->first; bone; bone = bone->next)
667         {
668                 float vec[3];
669                 short pval[2];
670                 int pdist;
671
672                 if ((bone->flag & BONE_CONNECTED) == 0)
673                 {
674                         copy_v3_v3(vec, bone->head);
675                         mul_m4_v3(ob->obmat, vec);
676                         if (ED_view3d_project_short_noclip(ar, vec, pval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
677
678                                 pdist = ABS(pval[0] - mval[0]) + ABS(pval[1] - mval[1]);
679
680                                 if (pdist < *dist)
681                                 {
682                                         *dist = pdist;
683                                         pt = &boneSnap;
684                                         copy_v3_v3(pt->p, vec);
685                                         pt->type = PT_EXACT;
686                                 }
687                         }
688                 }
689
690
691                 copy_v3_v3(vec, bone->tail);
692                 mul_m4_v3(ob->obmat, vec);
693                 if (ED_view3d_project_short_noclip(ar, vec, pval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
694
695                         pdist = ABS(pval[0] - mval[0]) + ABS(pval[1] - mval[1]);
696
697                         if (pdist < *dist)
698                         {
699                                 *dist = pdist;
700                                 pt = &boneSnap;
701                                 copy_v3_v3(pt->p, vec);
702                                 pt->type = PT_EXACT;
703                         }
704                 }
705         }
706
707         return pt;
708 }
709 #endif
710
711 void sk_resetOverdraw(SK_Sketch *sketch)
712 {
713         sketch->over.target = NULL;
714         sketch->over.start = -1;
715         sketch->over.end = -1;
716         sketch->over.count = 0;
717 }
718
719 int sk_hasOverdraw(SK_Sketch *sketch, SK_Stroke *stk)
720 {
721         return sketch->over.target &&
722                sketch->over.count >= SK_OVERDRAW_LIMIT &&
723                (sketch->over.target == stk || stk == NULL) &&
724                (sketch->over.start != -1 || sketch->over.end != -1);
725 }
726
727 static void sk_updateOverdraw(bContext *C, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd)
728 {
729         if (sketch->over.target == NULL) {
730                 SK_Stroke *target;
731                 int closest_index = -1;
732                 float dist_px = SNAP_MIN_DISTANCE * 2;
733
734                 for (target = sketch->strokes.first; target; target = target->next) {
735                         if (target != stk) {
736                                 int index;
737
738                                 SK_Point *spt = sk_snapPointStroke(C, target, dd->mval, &dist_px, &index, 1);
739
740                                 if (spt != NULL) {
741                                         sketch->over.target = target;
742                                         closest_index = index;
743                                 }
744                         }
745                 }
746
747                 if (sketch->over.target != NULL) {
748                         if (closest_index > -1) {
749                                 if (sk_lastStrokePoint(stk)->type == PT_EXACT) {
750                                         sketch->over.count = SK_OVERDRAW_LIMIT;
751                                 }
752                                 else {
753                                         sketch->over.count++;
754                                 }
755                         }
756
757                         if (stk->nb_points == 1) {
758                                 sketch->over.start = closest_index;
759                         }
760                         else {
761                                 sketch->over.end = closest_index;
762                         }
763                 }
764         }
765         else if (sketch->over.target != NULL) {
766                 SK_Point *closest_pt = NULL;
767                 float dist_px = SNAP_MIN_DISTANCE * 2;
768                 int index;
769
770                 closest_pt = sk_snapPointStroke(C, sketch->over.target, dd->mval, &dist_px, &index, 1);
771
772                 if (closest_pt != NULL) {
773                         if (sk_lastStrokePoint(stk)->type == PT_EXACT) {
774                                 sketch->over.count = SK_OVERDRAW_LIMIT;
775                         }
776                         else {
777                                 sketch->over.count++;
778                         }
779
780                         sketch->over.end = index;
781                 }
782                 else {
783                         sketch->over.end = -1;
784                 }
785         }
786 }
787
788 /* return 1 on reverse needed */
789 static int sk_adjustIndexes(SK_Sketch *sketch, int *start, int *end)
790 {
791         int retval = 0;
792
793         *start = sketch->over.start;
794         *end = sketch->over.end;
795
796         if (*start == -1) {
797                 *start = 0;
798         }
799
800         if (*end == -1) {
801                 *end = sketch->over.target->nb_points - 1;
802         }
803
804         if (*end < *start) {
805                 int tmp = *start;
806                 *start = *end;
807                 *end = tmp;
808                 retval = 1;
809         }
810
811         return retval;
812 }
813
814 static void sk_endOverdraw(SK_Sketch *sketch)
815 {
816         SK_Stroke *stk = sketch->active_stroke;
817
818         if (sk_hasOverdraw(sketch, NULL)) {
819                 int start;
820                 int end;
821
822                 if (sk_adjustIndexes(sketch, &start, &end)) {
823                         sk_reverseStroke(stk);
824                 }
825
826                 if (stk->nb_points > 1) {
827                         stk->points->type = sketch->over.target->points[start].type;
828                         sk_lastStrokePoint(stk)->type = sketch->over.target->points[end].type;
829                 }
830
831                 sk_insertStrokePoints(sketch->over.target, stk->points, stk->nb_points, start, end);
832
833                 sk_removeStroke(sketch, stk);
834
835                 sk_resetOverdraw(sketch);
836         }
837 }
838
839
840 static void sk_startStroke(SK_Sketch *sketch)
841 {
842         SK_Stroke *stk = sk_createStroke();
843
844         BLI_addtail(&sketch->strokes, stk);
845         sketch->active_stroke = stk;
846
847         sk_resetOverdraw(sketch);
848 }
849
850 static void sk_endStroke(bContext *C, SK_Sketch *sketch)
851 {
852         ToolSettings *ts = CTX_data_tool_settings(C);
853         sk_shrinkStrokeBuffer(sketch->active_stroke);
854
855         if (ts->bone_sketching & BONE_SKETCHING_ADJUST) {
856                 sk_endOverdraw(sketch);
857         }
858
859         sketch->active_stroke = NULL;
860 }
861
862 static void sk_updateDrawData(SK_DrawData *dd)
863 {
864         dd->type = PT_CONTINUOUS;
865
866         dd->previous_mval[0] = dd->mval[0];
867         dd->previous_mval[1] = dd->mval[1];
868 }
869
870 static float sk_distanceDepth(bContext *C, float p1[3], float p2[3])
871 {
872         ARegion *ar = CTX_wm_region(C);
873         RegionView3D *rv3d = ar->regiondata;
874         float vec[3];
875         float distance;
876
877         sub_v3_v3v3(vec, p1, p2);
878
879         project_v3_v3v3(vec, vec, rv3d->viewinv[2]);
880
881         distance = len_v3(vec);
882
883         if (dot_v3v3(rv3d->viewinv[2], vec) > 0) {
884                 distance *= -1;
885         }
886
887         return distance;
888 }
889
890 static void sk_interpolateDepth(bContext *C, SK_Stroke *stk, int start, int end, float length, float distance)
891 {
892         ARegion *ar = CTX_wm_region(C);
893         ScrArea *sa = CTX_wm_area(C);
894         View3D *v3d = sa->spacedata.first;
895
896         float progress = 0;
897         int i;
898
899         progress = len_v3v3(stk->points[start].p, stk->points[start - 1].p);
900
901         for (i = start; i <= end; i++) {
902                 float ray_start[3], ray_normal[3];
903                 float delta = len_v3v3(stk->points[i].p, stk->points[i + 1].p);
904                 float pval[2] = {0, 0};
905
906                 ED_view3d_project_float_global(ar, stk->points[i].p, pval, V3D_PROJ_TEST_NOP);
907                 ED_view3d_win_to_ray(ar, v3d, pval, ray_start, ray_normal, false);
908
909                 mul_v3_fl(ray_normal, distance * progress / length);
910                 add_v3_v3(stk->points[i].p, ray_normal);
911
912                 progress += delta;
913         }
914 }
915
916 static void sk_projectDrawPoint(bContext *C, float vec[3], SK_Stroke *stk, SK_DrawData *dd)
917 {
918         ARegion *ar = CTX_wm_region(C);
919         /* copied from grease pencil, need fixing */
920         SK_Point *last = sk_lastStrokePoint(stk);
921         short cval[2];
922         float fp[3] = {0, 0, 0};
923         float dvec[3];
924         float mval_f[2];
925         float zfac;
926
927         if (last != NULL) {
928                 copy_v3_v3(fp, last->p);
929         }
930
931         zfac = ED_view3d_calc_zfac(ar->regiondata, fp, NULL);
932
933         if (ED_view3d_project_short_global(ar, fp, cval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
934                 VECSUB2D(mval_f, cval, dd->mval);
935                 ED_view3d_win_to_delta(ar, mval_f, dvec, zfac);
936                 sub_v3_v3v3(vec, fp, dvec);
937         }
938         else {
939                 zero_v3(vec);
940         }
941 }
942
943 static int sk_getStrokeDrawPoint(bContext *C, SK_Point *pt, SK_Sketch *UNUSED(sketch), SK_Stroke *stk, SK_DrawData *dd)
944 {
945         pt->type = dd->type;
946         pt->mode = PT_PROJECT;
947         sk_projectDrawPoint(C, pt->p, stk, dd);
948
949         return 1;
950 }
951
952 static int sk_addStrokeDrawPoint(bContext *C, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd)
953 {
954         ARegion *ar = CTX_wm_region(C);
955         RegionView3D *rv3d = ar->regiondata;
956         SK_Point pt;
957
958         sk_initPoint(&pt, dd, rv3d->viewinv[2]);
959
960         sk_getStrokeDrawPoint(C, &pt, sketch, stk, dd);
961
962         sk_appendStrokePoint(stk, &pt);
963
964         return 1;
965 }
966
967 static int sk_getStrokeSnapPoint(bContext *C, SK_Point *pt, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd)
968 {
969         ToolSettings *ts = CTX_data_tool_settings(C);
970         int point_added = 0;
971
972         if (ts->snap_mode == SCE_SNAP_MODE_VOLUME) {
973                 DepthPeel *p1, *p2;
974                 float *last_p = NULL;
975                 float dist = FLT_MAX;
976                 float p[3] = {0};
977                 float size = 0;
978                 float mvalf[2];
979
980                 BLI_freelistN(&sketch->depth_peels);
981                 BLI_listbase_clear(&sketch->depth_peels);
982
983                 mvalf[0] = dd->mval[0];
984                 mvalf[1] = dd->mval[1];
985                 peelObjectsContext(C, mvalf, SNAP_ALL, &sketch->depth_peels);
986
987                 if (stk->nb_points > 0 && stk->points[stk->nb_points - 1].type == PT_CONTINUOUS) {
988                         last_p = stk->points[stk->nb_points - 1].p;
989                 }
990                 else if (LAST_SNAP_POINT_VALID) {
991                         last_p = LAST_SNAP_POINT;
992                 }
993
994
995                 for (p1 = sketch->depth_peels.first; p1; p1 = p1->next) {
996                         if (p1->flag == 0) {
997                                 float vec[3];
998                                 float new_dist;
999                                 float new_size = 0;
1000
1001                                 p2 = NULL;
1002                                 p1->flag = 1;
1003
1004                                 /* if peeling objects, take the first and last from each object */
1005                                 if (ts->snap_flag & SCE_SNAP_PEEL_OBJECT) {
1006                                         DepthPeel *peel;
1007                                         for (peel = p1->next; peel; peel = peel->next) {
1008                                                 if (peel->ob == p1->ob) {
1009                                                         peel->flag = 1;
1010                                                         p2 = peel;
1011                                                 }
1012                                         }
1013                                 }
1014                                 /* otherwise, pair first with second and so on */
1015                                 else {
1016                                         for (p2 = p1->next; p2 && p2->ob != p1->ob; p2 = p2->next) {
1017                                                 /* nothing to do here */
1018                                         }
1019                                 }
1020
1021                                 if (p2) {
1022                                         p2->flag = 1;
1023
1024                                         add_v3_v3v3(vec, p1->p, p2->p);
1025                                         mul_v3_fl(vec, 0.5f);
1026                                         new_size = len_v3v3(p1->p, p2->p);
1027                                 }
1028                                 else {
1029                                         copy_v3_v3(vec, p1->p);
1030                                 }
1031
1032                                 if (last_p == NULL) {
1033                                         copy_v3_v3(p, vec);
1034                                         size = new_size;
1035                                         dist = 0;
1036                                         break;
1037                                 }
1038
1039                                 new_dist = len_v3v3(last_p, vec);
1040
1041                                 if (new_dist < dist) {
1042                                         copy_v3_v3(p, vec);
1043                                         dist = new_dist;
1044                                         size = new_size;
1045                                 }
1046                         }
1047                 }
1048
1049                 if (dist != FLT_MAX) {
1050                         pt->type = dd->type;
1051                         pt->mode = PT_SNAP;
1052                         pt->size = size / 2;
1053                         copy_v3_v3(pt->p, p);
1054
1055                         point_added = 1;
1056                 }
1057
1058                 //BLI_freelistN(&depth_peels);
1059         }
1060         else {
1061                 SK_Stroke *snap_stk;
1062                 float vec[3];
1063                 float no[3];
1064                 float mval[2];
1065                 int found = 0;
1066                 float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
1067
1068                 /* snap to strokes */
1069                 // if (ts->snap_mode == SCE_SNAP_MODE_VERTEX) /* snap all the time to strokes */
1070                 for (snap_stk = sketch->strokes.first; snap_stk; snap_stk = snap_stk->next) {
1071                         SK_Point *spt = NULL;
1072                         if (snap_stk == stk) {
1073                                 spt = sk_snapPointStroke(C, snap_stk, dd->mval, &dist_px, NULL, 0);
1074                         }
1075                         else {
1076                                 spt = sk_snapPointStroke(C, snap_stk, dd->mval, &dist_px, NULL, 1);
1077                         }
1078
1079                         if (spt != NULL) {
1080                                 copy_v3_v3(pt->p, spt->p);
1081                                 point_added = 1;
1082                         }
1083                 }
1084                 
1085                 mval[0] = dd->mval[0];
1086                 mval[1] = dd->mval[1];
1087
1088                 /* try to snap to closer object */
1089                 found = snapObjectsContext(
1090                         C, mval, SNAP_NOT_SELECTED,
1091                         vec, no, &dist_px);
1092                 if (found == 1) {
1093                         pt->type = dd->type;
1094                         pt->mode = PT_SNAP;
1095                         copy_v3_v3(pt->p, vec);
1096
1097                         point_added = 1;
1098                 }
1099         }
1100
1101         return point_added;
1102 }
1103
1104 static int sk_addStrokeSnapPoint(bContext *C, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd)
1105 {
1106         int point_added;
1107         ARegion *ar = CTX_wm_region(C);
1108         RegionView3D *rv3d = ar->regiondata;
1109         SK_Point pt;
1110
1111         sk_initPoint(&pt, dd, rv3d->viewinv[2]);
1112
1113         point_added = sk_getStrokeSnapPoint(C, &pt, sketch, stk, dd);
1114
1115         if (point_added) {
1116                 float final_p[3];
1117                 float length, distance;
1118                 int total;
1119                 int i;
1120
1121                 copy_v3_v3(final_p, pt.p);
1122
1123                 sk_projectDrawPoint(C, pt.p, stk, dd);
1124                 sk_appendStrokePoint(stk, &pt);
1125
1126                 /* update all previous point to give smooth Z progresion */
1127                 total = 0;
1128                 length = 0;
1129                 for (i = stk->nb_points - 2; i > 0; i--) {
1130                         length += len_v3v3(stk->points[i].p, stk->points[i + 1].p);
1131                         total++;
1132                         if (stk->points[i].mode == PT_SNAP || stk->points[i].type == PT_EXACT) {
1133                                 break;
1134                         }
1135                 }
1136
1137                 if (total > 1) {
1138                         distance = sk_distanceDepth(C, final_p, stk->points[i].p);
1139
1140                         sk_interpolateDepth(C, stk, i + 1, stk->nb_points - 2, length, distance);
1141                 }
1142
1143                 copy_v3_v3(stk->points[stk->nb_points - 1].p, final_p);
1144
1145                 point_added = 1;
1146         }
1147
1148         return point_added;
1149 }
1150
1151 static void sk_addStrokePoint(bContext *C, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd, const bool snap)
1152 {
1153         ToolSettings *ts = CTX_data_tool_settings(C);
1154         int point_added = 0;
1155
1156         if (snap) {
1157                 point_added = sk_addStrokeSnapPoint(C, sketch, stk, dd);
1158         }
1159
1160         if (point_added == 0) {
1161                 point_added = sk_addStrokeDrawPoint(C, sketch, stk, dd);
1162         }
1163
1164         if (stk == sketch->active_stroke && ts->bone_sketching & BONE_SKETCHING_ADJUST) {
1165                 sk_updateOverdraw(C, sketch, stk, dd);
1166         }
1167 }
1168
1169 static void sk_getStrokePoint(bContext *C, SK_Point *pt, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd, const bool snap)
1170 {
1171         int point_added = 0;
1172
1173         if (snap) {
1174                 point_added = sk_getStrokeSnapPoint(C, pt, sketch, stk, dd);
1175                 LAST_SNAP_POINT_VALID = 1;
1176                 copy_v3_v3(LAST_SNAP_POINT, pt->p);
1177         }
1178         else {
1179                 LAST_SNAP_POINT_VALID = 0;
1180         }
1181
1182         if (point_added == 0) {
1183                 point_added = sk_getStrokeDrawPoint(C, pt, sketch, stk, dd);
1184         }
1185 }
1186
1187 /********************************************/
1188
1189 static void *headPoint(void *arg);
1190 static void *tailPoint(void *arg);
1191 static void *nextPoint(void *arg);
1192 static void *nextNPoint(void *arg, int n);
1193 static void *peekPoint(void *arg, int n);
1194 static void *previousPoint(void *arg);
1195 static int   iteratorStopped(void *arg);
1196
1197 static void initIteratorFct(SK_StrokeIterator *iter)
1198 {
1199         iter->head = headPoint;
1200         iter->tail = tailPoint;
1201         iter->peek = peekPoint;
1202         iter->next = nextPoint;
1203         iter->nextN = nextNPoint;
1204         iter->previous = previousPoint;
1205         iter->stopped = iteratorStopped;
1206 }
1207
1208 static SK_Point *setIteratorValues(SK_StrokeIterator *iter, int index)
1209 {
1210         SK_Point *pt = NULL;
1211
1212         if (index >= 0 && index < iter->length) {
1213                 pt = &(iter->stroke->points[iter->start + (iter->stride * index)]);
1214                 iter->p = pt->p;
1215                 iter->no = pt->no;
1216                 iter->size = pt->size;
1217         }
1218         else {
1219                 iter->p = NULL;
1220                 iter->no = NULL;
1221                 iter->size = 0;
1222         }
1223
1224         return pt;
1225 }
1226
1227 void initStrokeIterator(BArcIterator *arg, SK_Stroke *stk, int start, int end)
1228 {
1229         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1230
1231         initIteratorFct(iter);
1232         iter->stroke = stk;
1233
1234         if (start < end) {
1235                 iter->start = start + 1;
1236                 iter->end = end - 1;
1237                 iter->stride = 1;
1238         }
1239         else {
1240                 iter->start = start - 1;
1241                 iter->end = end + 1;
1242                 iter->stride = -1;
1243         }
1244
1245         iter->length = iter->stride * (iter->end - iter->start + 1);
1246
1247         iter->index = -1;
1248 }
1249
1250
1251 static void *headPoint(void *arg)
1252 {
1253         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1254         SK_Point *result = NULL;
1255
1256         result = &(iter->stroke->points[iter->start - iter->stride]);
1257         iter->p = result->p;
1258         iter->no = result->no;
1259         iter->size = result->size;
1260
1261         return result;
1262 }
1263
1264 static void *tailPoint(void *arg)
1265 {
1266         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1267         SK_Point *result = NULL;
1268
1269         result = &(iter->stroke->points[iter->end + iter->stride]);
1270         iter->p = result->p;
1271         iter->no = result->no;
1272         iter->size = result->size;
1273
1274         return result;
1275 }
1276
1277 static void *nextPoint(void *arg)
1278 {
1279         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1280         SK_Point *result = NULL;
1281
1282         iter->index++;
1283         if (iter->index < iter->length) {
1284                 result = setIteratorValues(iter, iter->index);
1285         }
1286
1287         return result;
1288 }
1289
1290 static void *nextNPoint(void *arg, int n)
1291 {
1292         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1293         SK_Point *result = NULL;
1294
1295         iter->index += n;
1296
1297         /* check if passed end */
1298         if (iter->index < iter->length) {
1299                 result = setIteratorValues(iter, iter->index);
1300         }
1301
1302         return result;
1303 }
1304
1305 static void *peekPoint(void *arg, int n)
1306 {
1307         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1308         SK_Point *result = NULL;
1309         int index = iter->index + n;
1310
1311         /* check if passed end */
1312         if (index < iter->length) {
1313                 result = setIteratorValues(iter, index);
1314         }
1315
1316         return result;
1317 }
1318
1319 static void *previousPoint(void *arg)
1320 {
1321         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1322         SK_Point *result = NULL;
1323
1324         if (iter->index > 0) {
1325                 iter->index--;
1326                 result = setIteratorValues(iter, iter->index);
1327         }
1328
1329         return result;
1330 }
1331
1332 static int iteratorStopped(void *arg)
1333 {
1334         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1335
1336         if (iter->index >= iter->length) {
1337                 return 1;
1338         }
1339         else {
1340                 return 0;
1341         }
1342 }
1343
1344 static void sk_convertStroke(bContext *C, SK_Stroke *stk)
1345 {
1346         Object *obedit = CTX_data_edit_object(C);
1347         ToolSettings *ts = CTX_data_tool_settings(C);
1348         bArmature *arm = obedit->data;
1349         SK_Point *head;
1350         EditBone *parent = NULL;
1351         float invmat[4][4]; /* move in caller function */
1352         float tmat[3][3];
1353         int head_index = 0;
1354         int i;
1355
1356         head = NULL;
1357
1358         invert_m4_m4(invmat, obedit->obmat);
1359         transpose_m3_m4(tmat, obedit->obmat);
1360
1361         for (i = 0; i < stk->nb_points; i++) {
1362                 SK_Point *pt = stk->points + i;
1363
1364                 if (pt->type == PT_EXACT) {
1365                         if (head == NULL) {
1366                                 head_index = i;
1367                                 head = pt;
1368                         }
1369                         else {
1370                                 EditBone *bone = NULL;
1371                                 EditBone *new_parent;
1372
1373                                 if (i - head_index > 1) {
1374                                         SK_StrokeIterator sk_iter;
1375                                         BArcIterator *iter = (BArcIterator *)&sk_iter;
1376
1377                                         initStrokeIterator(iter, stk, head_index, i);
1378
1379                                         if (ts->bone_sketching_convert == SK_CONVERT_CUT_ADAPTATIVE) {
1380                                                 bone = subdivideArcBy(ts, arm, arm->edbo, iter, invmat, tmat, nextAdaptativeSubdivision);
1381                                         }
1382                                         else if (ts->bone_sketching_convert == SK_CONVERT_CUT_LENGTH) {
1383                                                 bone = subdivideArcBy(ts, arm, arm->edbo, iter, invmat, tmat, nextLengthSubdivision);
1384                                         }
1385                                         else if (ts->bone_sketching_convert == SK_CONVERT_CUT_FIXED) {
1386                                                 bone = subdivideArcBy(ts, arm, arm->edbo, iter, invmat, tmat, nextFixedSubdivision);
1387                                         }
1388                                 }
1389
1390                                 if (bone == NULL) {
1391                                         bone = ED_armature_edit_bone_add(arm, "Bone");
1392
1393                                         copy_v3_v3(bone->head, head->p);
1394                                         copy_v3_v3(bone->tail, pt->p);
1395
1396                                         mul_m4_v3(invmat, bone->head);
1397                                         mul_m4_v3(invmat, bone->tail);
1398                                         setBoneRollFromNormal(bone, head->no, invmat, tmat);
1399                                 }
1400
1401                                 new_parent = bone;
1402                                 bone->flag |= BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL;
1403
1404                                 /* move to end of chain */
1405                                 while (bone->parent != NULL) {
1406                                         bone = bone->parent;
1407                                         bone->flag |= BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL;
1408                                 }
1409
1410                                 if (parent != NULL) {
1411                                         bone->parent = parent;
1412                                         bone->flag |= BONE_CONNECTED;
1413                                 }
1414
1415                                 parent = new_parent;
1416                                 head_index = i;
1417                                 head = pt;
1418                         }
1419                 }
1420         }
1421 }
1422
1423 static void sk_convert(bContext *C, SK_Sketch *sketch)
1424 {
1425         ToolSettings *ts = CTX_data_tool_settings(C);
1426         SK_Stroke *stk;
1427
1428         for (stk = sketch->strokes.first; stk; stk = stk->next) {
1429                 if (stk->selected == 1) {
1430                         if (ts->bone_sketching_convert == SK_CONVERT_RETARGET) {
1431                                 sk_retargetStroke(C, stk);
1432                         }
1433                         else {
1434                                 sk_convertStroke(C, stk);
1435                         }
1436 //                      XXX
1437 //                      allqueue(REDRAWBUTSEDIT, 0);
1438                 }
1439         }
1440 }
1441 /******************* GESTURE *************************/
1442
1443
1444 /* returns the number of self intersections */
1445 static int sk_getSelfIntersections(bContext *C, ListBase *list, SK_Stroke *gesture)
1446 {
1447         ARegion *ar = CTX_wm_region(C);
1448         int added = 0;
1449         int s_i;
1450
1451         for (s_i = 0; s_i < gesture->nb_points - 1; s_i++) {
1452                 float s_p1[3] = {0, 0, 0};
1453                 float s_p2[3] = {0, 0, 0};
1454                 int g_i;
1455
1456                 ED_view3d_project_float_global(ar, gesture->points[s_i].p, s_p1, V3D_PROJ_TEST_NOP);
1457                 ED_view3d_project_float_global(ar, gesture->points[s_i + 1].p, s_p2, V3D_PROJ_TEST_NOP);
1458
1459                 /* start checking from second next, because two consecutive cannot intersect */
1460                 for (g_i = s_i + 2; g_i < gesture->nb_points - 1; g_i++) {
1461                         float g_p1[3] = {0, 0, 0};
1462                         float g_p2[3] = {0, 0, 0};
1463                         float vi[3];
1464                         float lambda;
1465
1466                         ED_view3d_project_float_global(ar, gesture->points[g_i].p, g_p1, V3D_PROJ_TEST_NOP);
1467                         ED_view3d_project_float_global(ar, gesture->points[g_i + 1].p, g_p2, V3D_PROJ_TEST_NOP);
1468
1469                         if (isect_line_line_strict_v3(s_p1, s_p2, g_p1, g_p2, vi, &lambda)) {
1470                                 SK_Intersection *isect = MEM_callocN(sizeof(SK_Intersection), "Intersection");
1471
1472                                 isect->gesture_index = g_i;
1473                                 isect->before = s_i;
1474                                 isect->after = s_i + 1;
1475                                 isect->stroke = gesture;
1476
1477                                 sub_v3_v3v3(isect->p, gesture->points[s_i + 1].p, gesture->points[s_i].p);
1478                                 mul_v3_fl(isect->p, lambda);
1479                                 add_v3_v3(isect->p, gesture->points[s_i].p);
1480
1481                                 BLI_addtail(list, isect);
1482
1483                                 added++;
1484                         }
1485                 }
1486         }
1487
1488         return added;
1489 }
1490
1491 static int cmpIntersections(const void *i1, const void *i2)
1492 {
1493         const SK_Intersection *isect1 = i1, *isect2 = i2;
1494
1495         if (isect1->stroke == isect2->stroke) {
1496                 if (isect1->before < isect2->before) {
1497                         return -1;
1498                 }
1499                 else if (isect1->before > isect2->before) {
1500                         return 1;
1501                 }
1502                 else {
1503                         if (isect1->lambda < isect2->lambda) {
1504                                 return -1;
1505                         }
1506                         else if (isect1->lambda > isect2->lambda) {
1507                                 return 1;
1508                         }
1509                 }
1510         }
1511
1512         return 0;
1513 }
1514
1515
1516 /* returns the maximum number of intersections per stroke */
1517 static int sk_getIntersections(bContext *C, ListBase *list, SK_Sketch *sketch, SK_Stroke *gesture)
1518 {
1519         ARegion *ar = CTX_wm_region(C);
1520         ScrArea *sa = CTX_wm_area(C);
1521         View3D *v3d = sa->spacedata.first;
1522         SK_Stroke *stk;
1523         int added = 0;
1524
1525         for (stk = sketch->strokes.first; stk; stk = stk->next) {
1526                 int s_added = 0;
1527                 int s_i;
1528
1529                 for (s_i = 0; s_i < stk->nb_points - 1; s_i++) {
1530                         float s_p1[3] = {0, 0, 0};
1531                         float s_p2[3] = {0, 0, 0};
1532                         int g_i;
1533
1534                         ED_view3d_project_float_global(ar, stk->points[s_i].p, s_p1, V3D_PROJ_TEST_NOP);
1535                         ED_view3d_project_float_global(ar, stk->points[s_i + 1].p, s_p2, V3D_PROJ_TEST_NOP);
1536
1537                         for (g_i = 0; g_i < gesture->nb_points - 1; g_i++) {
1538                                 float g_p1[3] = {0, 0, 0};
1539                                 float g_p2[3] = {0, 0, 0};
1540                                 float vi[3];
1541                                 float lambda;
1542
1543                                 ED_view3d_project_float_global(ar, gesture->points[g_i].p, g_p1, V3D_PROJ_TEST_NOP);
1544                                 ED_view3d_project_float_global(ar, gesture->points[g_i + 1].p, g_p2, V3D_PROJ_TEST_NOP);
1545
1546                                 if (isect_line_line_strict_v3(s_p1, s_p2, g_p1, g_p2, vi, &lambda)) {
1547                                         SK_Intersection *isect = MEM_callocN(sizeof(SK_Intersection), "Intersection");
1548                                         float ray_start[3], ray_end[3];
1549                                         float mval[2];
1550
1551                                         isect->gesture_index = g_i;
1552                                         isect->before = s_i;
1553                                         isect->after = s_i + 1;
1554                                         isect->stroke = stk;
1555                                         isect->lambda = lambda;
1556
1557                                         mval[0] = vi[0];
1558                                         mval[1] = vi[1];
1559                                         ED_view3d_win_to_segment(ar, v3d, mval, ray_start, ray_end, true);
1560
1561                                         isect_line_line_v3(stk->points[s_i].p,
1562                                                            stk->points[s_i + 1].p,
1563                                                            ray_start,
1564                                                            ray_end,
1565                                                            isect->p,
1566                                                            vi);
1567
1568                                         BLI_addtail(list, isect);
1569
1570                                         s_added++;
1571                                 }
1572                         }
1573                 }
1574
1575                 added = MAX2(s_added, added);
1576         }
1577
1578         BLI_listbase_sort(list, cmpIntersections);
1579
1580         return added;
1581 }
1582
1583 static int sk_getSegments(SK_Stroke *segments, SK_Stroke *gesture)
1584 {
1585         SK_StrokeIterator sk_iter;
1586         BArcIterator *iter = (BArcIterator *)&sk_iter;
1587
1588         float CORRELATION_THRESHOLD = 0.99f;
1589         float *vec;
1590         int i, j;
1591
1592         sk_appendStrokePoint(segments, &gesture->points[0]);
1593         vec = segments->points[segments->nb_points - 1].p;
1594
1595         initStrokeIterator(iter, gesture, 0, gesture->nb_points - 1);
1596
1597         for (i = 1, j = 0; i < gesture->nb_points; i++) {
1598                 float n[3];
1599
1600                 /* Calculate normal */
1601                 sub_v3_v3v3(n, gesture->points[i].p, vec);
1602
1603                 if (calcArcCorrelation(iter, j, i, vec, n) < CORRELATION_THRESHOLD) {
1604                         j = i - 1;
1605                         sk_appendStrokePoint(segments, &gesture->points[j]);
1606                         vec = segments->points[segments->nb_points - 1].p;
1607                         segments->points[segments->nb_points - 1].type = PT_EXACT;
1608                 }
1609         }
1610
1611         sk_appendStrokePoint(segments, &gesture->points[gesture->nb_points - 1]);
1612
1613         return segments->nb_points - 1;
1614 }
1615
1616 int sk_detectCutGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1617 {
1618         if (gest->nb_segments == 1 && gest->nb_intersections == 1) {
1619                 return 1;
1620         }
1621
1622         return 0;
1623 }
1624
1625 void sk_applyCutGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1626 {
1627         SK_Intersection *isect;
1628
1629         for (isect = gest->intersections.first; isect; isect = isect->next) {
1630                 SK_Point pt;
1631
1632                 pt.type = PT_EXACT;
1633                 pt.mode = PT_PROJECT; /* take mode from neighboring points */
1634                 copy_v3_v3(pt.p, isect->p);
1635                 copy_v3_v3(pt.no, isect->stroke->points[isect->before].no);
1636
1637                 sk_insertStrokePoint(isect->stroke, &pt, isect->after);
1638         }
1639 }
1640
1641 int sk_detectTrimGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1642 {
1643         if (gest->nb_segments == 2 && gest->nb_intersections == 1 && gest->nb_self_intersections == 0) {
1644                 float s1[3], s2[3];
1645                 float angle;
1646
1647                 sub_v3_v3v3(s1, gest->segments->points[1].p, gest->segments->points[0].p);
1648                 sub_v3_v3v3(s2, gest->segments->points[2].p, gest->segments->points[1].p);
1649
1650                 angle = RAD2DEGF(angle_v2v2(s1, s2));
1651
1652                 if (angle > 60 && angle < 120) {
1653                         return 1;
1654                 }
1655         }
1656
1657         return 0;
1658 }
1659
1660 void sk_applyTrimGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1661 {
1662         SK_Intersection *isect;
1663         float trim_dir[3];
1664
1665         sub_v3_v3v3(trim_dir, gest->segments->points[2].p, gest->segments->points[1].p);
1666
1667         for (isect = gest->intersections.first; isect; isect = isect->next) {
1668                 SK_Point pt;
1669                 float stroke_dir[3];
1670
1671                 pt.type = PT_EXACT;
1672                 pt.mode = PT_PROJECT; /* take mode from neighboring points */
1673                 copy_v3_v3(pt.p, isect->p);
1674                 copy_v3_v3(pt.no, isect->stroke->points[isect->before].no);
1675
1676                 sub_v3_v3v3(stroke_dir, isect->stroke->points[isect->after].p, isect->stroke->points[isect->before].p);
1677
1678                 /* same direction, trim end */
1679                 if (dot_v3v3(stroke_dir, trim_dir) > 0) {
1680                         sk_replaceStrokePoint(isect->stroke, &pt, isect->after);
1681                         sk_trimStroke(isect->stroke, 0, isect->after);
1682                 }
1683                 /* else, trim start */
1684                 else {
1685                         sk_replaceStrokePoint(isect->stroke, &pt, isect->before);
1686                         sk_trimStroke(isect->stroke, isect->before, isect->stroke->nb_points - 1);
1687                 }
1688
1689         }
1690 }
1691
1692 int sk_detectCommandGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1693 {
1694         if (gest->nb_segments > 2 && gest->nb_intersections == 2 && gest->nb_self_intersections == 1) {
1695                 SK_Intersection *isect, *self_isect;
1696
1697                 /* get the last intersection of the first pair */
1698                 for (isect = gest->intersections.first; isect; isect = isect->next) {
1699                         if (isect->stroke == isect->next->stroke) {
1700                                 isect = isect->next;
1701                                 break;
1702                         }
1703                 }
1704
1705                 self_isect = gest->self_intersections.first;
1706
1707                 if (isect && isect->gesture_index < self_isect->gesture_index) {
1708                         return 1;
1709                 }
1710         }
1711
1712         return 0;
1713 }
1714
1715 void sk_applyCommandGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1716 {
1717         SK_Intersection *isect;
1718         int command = 1;
1719
1720 /*      XXX */
1721 /*      command = pupmenu("Action %t|Flatten %x1|Straighten %x2|Polygonize %x3"); */
1722         if (command < 1) return;
1723
1724         for (isect = gest->intersections.first; isect; isect = isect->next) {
1725                 SK_Intersection *i2;
1726
1727                 i2 = isect->next;
1728
1729                 if (i2 && i2->stroke == isect->stroke) {
1730                         switch (command) {
1731                                 case 1:
1732                                         sk_flattenStroke(isect->stroke, isect->before, i2->after);
1733                                         break;
1734                                 case 2:
1735                                         sk_straightenStroke(isect->stroke, isect->before, i2->after, isect->p, i2->p);
1736                                         break;
1737                                 case 3:
1738                                         sk_polygonizeStroke(isect->stroke, isect->before, i2->after);
1739                                         break;
1740                         }
1741
1742                         isect = i2;
1743                 }
1744         }
1745 }
1746
1747 int sk_detectDeleteGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1748 {
1749         if (gest->nb_segments == 2 && gest->nb_intersections == 2) {
1750                 float s1[3], s2[3];
1751                 float angle;
1752
1753                 sub_v3_v3v3(s1, gest->segments->points[1].p, gest->segments->points[0].p);
1754                 sub_v3_v3v3(s2, gest->segments->points[2].p, gest->segments->points[1].p);
1755
1756                 angle = RAD2DEGF(angle_v2v2(s1, s2));
1757
1758                 if (angle > 120) {
1759                         return 1;
1760                 }
1761         }
1762
1763         return 0;
1764 }
1765
1766 void sk_applyDeleteGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *sketch)
1767 {
1768         SK_Intersection *isect;
1769
1770         for (isect = gest->intersections.first; isect; isect = isect->next) {
1771                 /* only delete strokes that are crossed twice */
1772                 if (isect->next && isect->next->stroke == isect->stroke) {
1773                         isect = isect->next;
1774
1775                         sk_removeStroke(sketch, isect->stroke);
1776                 }
1777         }
1778 }
1779
1780 int sk_detectMergeGesture(bContext *C, SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1781 {
1782         ARegion *ar = CTX_wm_region(C);
1783         if (gest->nb_segments > 2 && gest->nb_intersections == 2) {
1784                 int start_val[2], end_val[2];
1785                 int dist;
1786
1787                 if ((ED_view3d_project_int_global(ar, gest->stk->points[0].p,           start_val, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
1788                     (ED_view3d_project_int_global(ar, sk_lastStrokePoint(gest->stk)->p, end_val,   V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
1789                 {
1790                         dist = len_manhattan_v2v2_int(start_val, end_val);
1791
1792                         /* if gesture is a circle */
1793                         if (dist <= 20) {
1794                                 SK_Intersection *isect;
1795
1796                                 /* check if it circled around an exact point */
1797                                 for (isect = gest->intersections.first; isect; isect = isect->next) {
1798                                         /* only delete strokes that are crossed twice */
1799                                         if (isect->next && isect->next->stroke == isect->stroke) {
1800                                                 int start_index, end_index;
1801                                                 int i;
1802
1803                                                 start_index = MIN2(isect->after, isect->next->after);
1804                                                 end_index = MAX2(isect->before, isect->next->before);
1805
1806                                                 for (i = start_index; i <= end_index; i++) {
1807                                                         if (isect->stroke->points[i].type == PT_EXACT) {
1808                                                                 return 1; /* at least one exact point found, stop detect here */
1809                                                         }
1810                                                 }
1811
1812                                                 /* skip next */
1813                                                 isect = isect->next;
1814                                         }
1815                                 }
1816                         }
1817                 }
1818         }
1819
1820         return 0;
1821 }
1822
1823 void sk_applyMergeGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1824 {
1825         SK_Intersection *isect;
1826
1827         /* check if it circled around an exact point */
1828         for (isect = gest->intersections.first; isect; isect = isect->next) {
1829                 /* only merge strokes that are crossed twice */
1830                 if (isect->next && isect->next->stroke == isect->stroke) {
1831                         int start_index, end_index;
1832                         int i;
1833
1834                         start_index = MIN2(isect->after, isect->next->after);
1835                         end_index = MAX2(isect->before, isect->next->before);
1836
1837                         for (i = start_index; i <= end_index; i++) {
1838                                 /* if exact, switch to continuous */
1839                                 if (isect->stroke->points[i].type == PT_EXACT) {
1840                                         isect->stroke->points[i].type = PT_CONTINUOUS;
1841                                 }
1842                         }
1843
1844                         /* skip next */
1845                         isect = isect->next;
1846                 }
1847         }
1848 }
1849
1850 int sk_detectReverseGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1851 {
1852         if (gest->nb_segments > 2 && gest->nb_intersections == 2 && gest->nb_self_intersections == 0) {
1853                 SK_Intersection *isect;
1854
1855                 /* check if it circled around an exact point */
1856                 for (isect = gest->intersections.first; isect; isect = isect->next) {
1857                         /* only delete strokes that are crossed twice */
1858                         if (isect->next && isect->next->stroke == isect->stroke) {
1859                                 float start_v[3], end_v[3];
1860                                 float angle;
1861
1862                                 if (isect->gesture_index < isect->next->gesture_index) {
1863                                         sub_v3_v3v3(start_v, isect->p, gest->stk->points[0].p);
1864                                         sub_v3_v3v3(end_v, sk_lastStrokePoint(gest->stk)->p, isect->next->p);
1865                                 }
1866                                 else {
1867                                         sub_v3_v3v3(start_v, isect->next->p, gest->stk->points[0].p);
1868                                         sub_v3_v3v3(end_v, sk_lastStrokePoint(gest->stk)->p, isect->p);
1869                                 }
1870
1871                                 angle = RAD2DEGF(angle_v2v2(start_v, end_v));
1872
1873                                 if (angle > 120) {
1874                                         return 1;
1875                                 }
1876
1877                                 /* skip next */
1878                                 isect = isect->next;
1879                         }
1880                 }
1881         }
1882
1883         return 0;
1884 }
1885
1886 void sk_applyReverseGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1887 {
1888         SK_Intersection *isect;
1889
1890         for (isect = gest->intersections.first; isect; isect = isect->next) {
1891                 /* only reverse strokes that are crossed twice */
1892                 if (isect->next && isect->next->stroke == isect->stroke) {
1893                         sk_reverseStroke(isect->stroke);
1894
1895                         /* skip next */
1896                         isect = isect->next;
1897                 }
1898         }
1899 }
1900
1901 int sk_detectConvertGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1902 {
1903         if (gest->nb_segments == 3 && gest->nb_self_intersections == 1) {
1904                 return 1;
1905         }
1906         return 0;
1907 }
1908
1909 void sk_applyConvertGesture(bContext *C, SK_Gesture *UNUSED(gest), SK_Sketch *sketch)
1910 {
1911         sk_convert(C, sketch);
1912 }
1913
1914 static void sk_initGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch)
1915 {
1916         BLI_listbase_clear(&gest->intersections);
1917         BLI_listbase_clear(&gest->self_intersections);
1918
1919         gest->segments = sk_createStroke();
1920         gest->stk = sketch->gesture;
1921
1922         gest->nb_self_intersections = sk_getSelfIntersections(C, &gest->self_intersections, gest->stk);
1923         gest->nb_intersections = sk_getIntersections(C, &gest->intersections, sketch, gest->stk);
1924         gest->nb_segments = sk_getSegments(gest->segments, gest->stk);
1925 }
1926
1927 static void sk_freeGesture(SK_Gesture *gest)
1928 {
1929         sk_freeStroke(gest->segments);
1930         BLI_freelistN(&gest->intersections);
1931         BLI_freelistN(&gest->self_intersections);
1932 }
1933
1934 static void sk_applyGesture(bContext *C, SK_Sketch *sketch)
1935 {
1936         SK_Gesture gest;
1937         SK_GestureAction *act;
1938
1939         sk_initGesture(C, &gest, sketch);
1940
1941         /* detect and apply */
1942         for (act = GESTURE_ACTIONS; act->apply != NULL; act++) {
1943                 if (act->detect(C, &gest, sketch)) {
1944                         act->apply(C, &gest, sketch);
1945                         break;
1946                 }
1947         }
1948
1949         sk_freeGesture(&gest);
1950 }
1951
1952 /********************************************/
1953
1954
1955 static bool sk_selectStroke(bContext *C, SK_Sketch *sketch, const int mval[2], const bool extend)
1956 {
1957         ViewContext vc;
1958         rcti rect;
1959         unsigned int buffer[MAXPICKBUF];
1960         short hits;
1961
1962         view3d_set_viewcontext(C, &vc);
1963
1964         rect.xmin = mval[0] - 5;
1965         rect.xmax = mval[0] + 5;
1966         rect.ymin = mval[1] - 5;
1967         rect.ymax = mval[1] + 5;
1968
1969         hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect, true);
1970
1971         if (hits > 0) {
1972                 int besthitresult = -1;
1973
1974                 if (hits == 1) {
1975                         besthitresult = buffer[3];
1976                 }
1977                 else {
1978                         besthitresult = buffer[3];
1979                         /* loop and get best hit */
1980                 }
1981
1982                 if (besthitresult > 0) {
1983                         SK_Stroke *selected_stk = BLI_findlink(&sketch->strokes, besthitresult - 1);
1984
1985                         if (extend == 0) {
1986                                 sk_selectAllSketch(sketch, -1);
1987
1988                                 selected_stk->selected = 1;
1989                         }
1990                         else {
1991                                 selected_stk->selected ^= 1;
1992                         }
1993
1994
1995                 }
1996                 return 1;
1997         }
1998
1999         return 0;
2000 }
2001
2002 #if 0 /* UNUSED 2.5 */
2003 static void sk_queueRedrawSketch(SK_Sketch *sketch)
2004 {
2005         if (sketch->active_stroke != NULL)
2006         {
2007                 SK_Point *last = sk_lastStrokePoint(sketch->active_stroke);
2008
2009                 if (last != NULL)
2010                 {
2011 //                      XXX
2012 //                      allqueue(REDRAWVIEW3D, 0);
2013                 }
2014         }
2015 }
2016 #endif
2017
2018 static void sk_drawSketch(Scene *scene, View3D *UNUSED(v3d), SK_Sketch *sketch, int with_names)
2019 {
2020         ToolSettings *ts = scene->toolsettings;
2021         SK_Stroke *stk;
2022
2023         glClear(GL_DEPTH_BUFFER_BIT);
2024         glEnable(GL_DEPTH_TEST);
2025
2026         if (with_names) {
2027                 int id;
2028                 for (id = 1, stk = sketch->strokes.first; stk; id++, stk = stk->next) {
2029                         sk_drawStroke(stk, id, NULL, -1, -1);
2030                 }
2031
2032                 GPU_select_load_id(-1);
2033         }
2034         else {
2035                 float selected_rgb[3] = {1, 0, 0};
2036                 float unselected_rgb[3] = {1, 0.5, 0};
2037
2038                 for (stk = sketch->strokes.first; stk; stk = stk->next) {
2039                         int start = -1;
2040                         int end = -1;
2041
2042                         if (sk_hasOverdraw(sketch, stk)) {
2043                                 sk_adjustIndexes(sketch, &start, &end);
2044                         }
2045
2046                         sk_drawStroke(stk, -1, (stk->selected == 1 ? selected_rgb : unselected_rgb), start, end);
2047
2048                         if (stk->selected == 1) {
2049                                 sk_drawStrokeSubdivision(ts, stk);
2050                         }
2051                 }
2052
2053                 if (sketch->active_stroke != NULL) {
2054                         SK_Point *last = sk_lastStrokePoint(sketch->active_stroke);
2055
2056                         if (ts->bone_sketching & BONE_SKETCHING_QUICK) {
2057                                 sk_drawStrokeSubdivision(ts, sketch->active_stroke);
2058                         }
2059
2060                         if (last != NULL) {
2061                                 GLUquadric *quad = gluNewQuadric();
2062                                 gluQuadricNormals(quad, GLU_SMOOTH);
2063
2064                                 glPushMatrix();
2065
2066                                 glEnable(GL_BLEND);
2067                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2068
2069                                 switch (sketch->next_point.mode) {
2070                                         case PT_SNAP:
2071                                                 glColor3f(0, 1, 0);
2072                                                 break;
2073                                         case PT_PROJECT:
2074                                                 glColor3f(0, 0, 0);
2075                                                 break;
2076                                 }
2077
2078                                 sk_drawPoint(quad, &sketch->next_point, 0.1);
2079
2080                                 glColor4f(selected_rgb[0], selected_rgb[1], selected_rgb[2], 0.3);
2081
2082                                 sk_drawEdge(quad, last, &sketch->next_point, 0.1);
2083
2084                                 glDisable(GL_BLEND);
2085
2086                                 glPopMatrix();
2087
2088                                 gluDeleteQuadric(quad);
2089                         }
2090                 }
2091         }
2092
2093 #if 0
2094         if (BLI_listbase_is_empty(&sketch->depth_peels) == false) {
2095                 float colors[8][3] = {
2096                         {1, 0, 0},
2097                         {0, 1, 0},
2098                         {0, 0, 1},
2099                         {1, 1, 0},
2100                         {1, 0, 1},
2101                         {0, 1, 1},
2102                         {1, 1, 1},
2103                         {0, 0, 0}
2104                 };
2105                 DepthPeel *p;
2106                 GLUquadric *quad = gluNewQuadric();
2107                 gluQuadricNormals(quad, GLU_SMOOTH);
2108
2109                 for (p = sketch->depth_peels.first; p; p = p->next)
2110                 {
2111                         int index = GET_INT_FROM_POINTER(p->ob);
2112                         index = (index >> 5) & 7;
2113
2114                         glColor3fv(colors[index]);
2115                         glPushMatrix();
2116                         glTranslate3fv(p->p);
2117                         gluSphere(quad, 0.02, 8, 8);
2118                         glPopMatrix();
2119                 }
2120
2121                 gluDeleteQuadric(quad);
2122         }
2123 #endif
2124
2125         glDisable(GL_DEPTH_TEST);
2126
2127         /* only draw gesture in active area */
2128         if (sketch->gesture != NULL /* && area_is_active_area(G.vd->area) */) {
2129                 float gesture_rgb[3] = {0, 0.5, 1};
2130                 sk_drawStroke(sketch->gesture, -1, gesture_rgb, -1, -1);
2131         }
2132 }
2133
2134 static int sk_finish_stroke(bContext *C, SK_Sketch *sketch)
2135 {
2136         ToolSettings *ts = CTX_data_tool_settings(C);
2137
2138         if (sketch->active_stroke != NULL) {
2139                 SK_Stroke *stk = sketch->active_stroke;
2140
2141                 sk_endStroke(C, sketch);
2142
2143                 if (ts->bone_sketching & BONE_SKETCHING_QUICK) {
2144                         if (ts->bone_sketching_convert == SK_CONVERT_RETARGET) {
2145                                 sk_retargetStroke(C, stk);
2146                         }
2147                         else {
2148                                 sk_convertStroke(C, stk);
2149                         }
2150 //                      XXX
2151 //                      BIF_undo_push("Convert Sketch");
2152                         sk_removeStroke(sketch, stk);
2153 //                      XXX
2154 //                      allqueue(REDRAWBUTSEDIT, 0);
2155                 }
2156
2157 //              XXX
2158 //              allqueue(REDRAWVIEW3D, 0);
2159                 return 1;
2160         }
2161
2162         return 0;
2163 }
2164
2165 static void sk_start_draw_stroke(SK_Sketch *sketch)
2166 {
2167         if (sketch->active_stroke == NULL) {
2168                 sk_startStroke(sketch);
2169                 sk_selectAllSketch(sketch, -1);
2170
2171                 sketch->active_stroke->selected = 1;
2172         }
2173 }
2174
2175 static void sk_start_draw_gesture(SK_Sketch *sketch)
2176 {
2177         sketch->gesture = sk_createStroke();
2178 }
2179
2180 static int sk_draw_stroke(bContext *C, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd, bool snap)
2181 {
2182         if (sk_stroke_filtermval(dd)) {
2183                 sk_addStrokePoint(C, sketch, stk, dd, snap);
2184                 sk_updateDrawData(dd);
2185                 sk_updateNextPoint(sketch, stk);
2186                 
2187                 return 1;
2188         }
2189
2190         return 0;
2191 }
2192
2193 static int ValidSketchViewContext(ViewContext *vc)
2194 {
2195         Object *obedit = vc->obedit;
2196         Scene *scene = vc->scene;
2197
2198         if (obedit &&
2199             obedit->type == OB_ARMATURE &&
2200             scene->toolsettings->bone_sketching & BONE_SKETCHING)
2201         {
2202                 return 1;
2203         }
2204         else {
2205                 return 0;
2206         }
2207 }
2208
2209 int BDR_drawSketchNames(ViewContext *vc)
2210 {
2211         if (ValidSketchViewContext(vc)) {
2212                 SK_Sketch *sketch = viewcontextSketch(vc, 0);
2213                 if (sketch) {
2214                         sk_drawSketch(vc->scene, vc->v3d, sketch, 1);
2215                         return 1;
2216                 }
2217         }
2218
2219         return 0;
2220 }
2221
2222 void BDR_drawSketch(const bContext *C)
2223 {
2224         if (ED_operator_sketch_mode(C)) {
2225                 SK_Sketch *sketch = contextSketch(C, 0);
2226                 if (sketch) {
2227                         sk_drawSketch(CTX_data_scene(C), CTX_wm_view3d(C), sketch, 0);
2228                 }
2229         }
2230 }
2231
2232 static int sketch_delete(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
2233 {
2234         SK_Sketch *sketch = contextSketch(C, 0);
2235         if (sketch) {
2236                 sk_deleteSelectedStrokes(sketch);
2237 //                      allqueue(REDRAWVIEW3D, 0);
2238         }
2239         WM_event_add_notifier(C, NC_SCREEN | ND_SKETCH | NA_REMOVED, NULL);
2240         return OPERATOR_FINISHED;
2241 }
2242
2243 bool BIF_sk_selectStroke(bContext *C, const int mval[2], const bool extend)
2244 {
2245         ToolSettings *ts = CTX_data_tool_settings(C);
2246         SK_Sketch *sketch = contextSketch(C, 0);
2247
2248         if (sketch != NULL && ts->bone_sketching & BONE_SKETCHING) {
2249                 if (sk_selectStroke(C, sketch, mval, extend)) {
2250                         ED_area_tag_redraw(CTX_wm_area(C));
2251                         return true;
2252                 }
2253         }
2254
2255         return false;
2256 }
2257
2258 void BIF_convertSketch(bContext *C)
2259 {
2260         if (ED_operator_sketch_full_mode(C)) {
2261                 SK_Sketch *sketch = contextSketch(C, 0);
2262                 if (sketch) {
2263                         sk_convert(C, sketch);
2264 //                      BIF_undo_push("Convert Sketch");
2265 //                      allqueue(REDRAWVIEW3D, 0);
2266 //                      allqueue(REDRAWBUTSEDIT, 0);
2267                 }
2268         }
2269 }
2270
2271 void BIF_deleteSketch(bContext *C)
2272 {
2273         if (ED_operator_sketch_full_mode(C)) {
2274                 SK_Sketch *sketch = contextSketch(C, 0);
2275                 if (sketch) {
2276                         sk_deleteSelectedStrokes(sketch);
2277 //                      BIF_undo_push("Convert Sketch");
2278 //                      allqueue(REDRAWVIEW3D, 0);
2279                 }
2280         }
2281 }
2282
2283 #if 0
2284 void BIF_selectAllSketch(bContext *C, int mode)
2285 {
2286         if (BIF_validSketchMode(C))
2287         {
2288                 SK_Sketch *sketch = contextSketch(C, 0);
2289                 if (sketch)
2290                 {
2291                         sk_selectAllSketch(sketch, mode);
2292 //                      XXX
2293 //                      allqueue(REDRAWVIEW3D, 0);
2294                 }
2295         }
2296 }
2297 #endif
2298
2299 SK_Sketch *contextSketch(const bContext *C, int create)
2300 {
2301         Object *obedit = CTX_data_edit_object(C);
2302         SK_Sketch *sketch = NULL;
2303
2304         if (obedit && obedit->type == OB_ARMATURE) {
2305                 bArmature *arm = obedit->data;
2306         
2307                 if (arm->sketch == NULL && create) {
2308                         arm->sketch = createSketch();
2309                 }
2310                 sketch = arm->sketch;
2311         }
2312
2313         return sketch;
2314 }
2315
2316 SK_Sketch *viewcontextSketch(ViewContext *vc, int create)
2317 {
2318         Object *obedit = vc->obedit;
2319         SK_Sketch *sketch = NULL;
2320
2321         if (obedit && obedit->type == OB_ARMATURE) {
2322                 bArmature *arm = obedit->data;
2323         
2324                 if (arm->sketch == NULL && create) {
2325                         arm->sketch = createSketch();
2326                 }
2327                 sketch = arm->sketch;
2328         }
2329
2330         return sketch;
2331 }
2332
2333 static int sketch_convert(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
2334 {
2335         SK_Sketch *sketch = contextSketch(C, 0);
2336         if (sketch != NULL) {
2337                 sk_convert(C, sketch);
2338                 ED_area_tag_redraw(CTX_wm_area(C));
2339         }
2340         return OPERATOR_FINISHED;
2341 }
2342
2343 static int sketch_cancel_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
2344 {
2345         SK_Sketch *sketch = contextSketch(C, 0);
2346         if (sketch != NULL) {
2347                 sk_cancelStroke(sketch);
2348                 ED_area_tag_redraw(CTX_wm_area(C));
2349                 return OPERATOR_FINISHED;
2350         }
2351         return OPERATOR_PASS_THROUGH;
2352 }
2353
2354 static int sketch_finish(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
2355 {
2356         SK_Sketch *sketch = contextSketch(C, 0);
2357         if (sketch != NULL) {
2358                 if (sk_finish_stroke(C, sketch)) {
2359                         ED_area_tag_redraw(CTX_wm_area(C));
2360                         return OPERATOR_FINISHED;
2361                 }
2362         }
2363         return OPERATOR_PASS_THROUGH;
2364 }
2365
2366 static int sketch_select(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
2367 {
2368         SK_Sketch *sketch = contextSketch(C, 0);
2369         if (sketch) {
2370                 short extend = 0;
2371                 if (sk_selectStroke(C, sketch, event->mval, extend))
2372                         ED_area_tag_redraw(CTX_wm_area(C));
2373         }
2374
2375         return OPERATOR_FINISHED;
2376 }
2377
2378 static void sketch_draw_stroke_cancel(bContext *C, wmOperator *op)
2379 {
2380         SK_Sketch *sketch = contextSketch(C, 1); /* create just to be sure */
2381         sk_cancelStroke(sketch);
2382         MEM_freeN(op->customdata);
2383 }
2384
2385 static int sketch_draw_stroke(bContext *C, wmOperator *op, const wmEvent *event)
2386 {
2387         const bool snap = RNA_boolean_get(op->ptr, "snap");
2388         SK_DrawData *dd;
2389         SK_Sketch *sketch = contextSketch(C, 1);
2390
2391         op->customdata = dd = MEM_callocN(sizeof(SK_DrawData), "SketchDrawData");
2392         sk_initDrawData(dd, event->mval);
2393
2394         sk_start_draw_stroke(sketch);
2395
2396         sk_draw_stroke(C, sketch, sketch->active_stroke, dd, snap);
2397
2398         WM_event_add_modal_handler(C, op);
2399
2400         return OPERATOR_RUNNING_MODAL;
2401 }
2402
2403 static void sketch_draw_gesture_cancel(bContext *C, wmOperator *op)
2404 {
2405         SK_Sketch *sketch = contextSketch(C, 1); /* create just to be sure */
2406         sk_cancelStroke(sketch);
2407         MEM_freeN(op->customdata);
2408 }
2409
2410 static int sketch_draw_gesture(bContext *C, wmOperator *op, const wmEvent *event)
2411 {
2412         const bool snap = RNA_boolean_get(op->ptr, "snap");
2413         SK_DrawData *dd;
2414         SK_Sketch *sketch = contextSketch(C, 1); /* create just to be sure */
2415         sk_cancelStroke(sketch);
2416
2417         op->customdata = dd = MEM_callocN(sizeof(SK_DrawData), "SketchDrawData");
2418         sk_initDrawData(dd, event->mval);
2419
2420         sk_start_draw_gesture(sketch);
2421         sk_draw_stroke(C, sketch, sketch->gesture, dd, snap);
2422
2423         WM_event_add_modal_handler(C, op);
2424
2425         return OPERATOR_RUNNING_MODAL;
2426 }
2427
2428 static int sketch_draw_modal(bContext *C, wmOperator *op, const wmEvent *event, short gesture, SK_Stroke *stk)
2429 {
2430         bool snap = RNA_boolean_get(op->ptr, "snap");
2431         SK_DrawData *dd = op->customdata;
2432         SK_Sketch *sketch = contextSketch(C, 1); /* create just to be sure */
2433         int retval = OPERATOR_RUNNING_MODAL;
2434
2435         switch (event->type) {
2436                 case LEFTCTRLKEY:
2437                 case RIGHTCTRLKEY:
2438                         snap = event->ctrl != 0;
2439                         RNA_boolean_set(op->ptr, "snap", snap);
2440                         break;
2441                 case MOUSEMOVE:
2442                 case INBETWEEN_MOUSEMOVE:
2443                         dd->mval[0] = event->mval[0];
2444                         dd->mval[1] = event->mval[1];
2445                         sk_draw_stroke(C, sketch, stk, dd, snap);
2446                         ED_area_tag_redraw(CTX_wm_area(C));
2447                         break;
2448                 case ESCKEY:
2449                         op->type->cancel(C, op);
2450                         ED_area_tag_redraw(CTX_wm_area(C));
2451                         retval = OPERATOR_CANCELLED;
2452                         break;
2453                 case LEFTMOUSE:
2454                         if (event->val == KM_RELEASE) {
2455                                 if (gesture == 0) {
2456                                         sk_endContinuousStroke(stk);
2457                                         sk_filterLastContinuousStroke(stk);
2458                                         sk_updateNextPoint(sketch, stk);
2459                                         ED_area_tag_redraw(CTX_wm_area(C));
2460                                         MEM_freeN(op->customdata);
2461                                         retval = OPERATOR_FINISHED;
2462                                 }
2463                                 else {
2464                                         sk_endContinuousStroke(stk);
2465                                         sk_filterLastContinuousStroke(stk);
2466
2467                                         if (stk->nb_points > 1) {
2468                                                 /* apply gesture here */
2469                                                 sk_applyGesture(C, sketch);
2470                                         }
2471
2472                                         sk_freeStroke(stk);
2473                                         sketch->gesture = NULL;
2474
2475                                         ED_area_tag_redraw(CTX_wm_area(C));
2476                                         MEM_freeN(op->customdata);
2477                                         retval = OPERATOR_FINISHED;
2478                                 }
2479                         }
2480                         break;
2481         }
2482
2483         return retval;
2484 }
2485
2486 static int sketch_draw_stroke_modal(bContext *C, wmOperator *op, const wmEvent *event)
2487 {
2488         SK_Sketch *sketch = contextSketch(C, 1); /* create just to be sure */
2489         return sketch_draw_modal(C, op, event, 0, sketch->active_stroke);
2490 }
2491
2492 static int sketch_draw_gesture_modal(bContext *C, wmOperator *op, const wmEvent *event)
2493 {
2494         SK_Sketch *sketch = contextSketch(C, 1); /* create just to be sure */
2495         return sketch_draw_modal(C, op, event, 1, sketch->gesture);
2496 }
2497
2498 static int sketch_draw_preview(bContext *C, wmOperator *op, const wmEvent *event)
2499 {
2500         const bool snap = RNA_boolean_get(op->ptr, "snap");
2501         SK_Sketch *sketch = contextSketch(C, 0);
2502
2503         if (sketch) {
2504                 SK_DrawData dd;
2505
2506                 sk_initDrawData(&dd, event->mval);
2507                 sk_getStrokePoint(C, &sketch->next_point, sketch, sketch->active_stroke, &dd, snap);
2508                 ED_area_tag_redraw(CTX_wm_area(C));
2509         }
2510
2511         return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
2512 }
2513
2514 /* ============================================== Poll Functions ============================================= */
2515
2516 int ED_operator_sketch_mode_active_stroke(bContext *C)
2517 {
2518         ToolSettings *ts = CTX_data_tool_settings(C);
2519         SK_Sketch *sketch = contextSketch(C, 0);
2520
2521         if (ts->bone_sketching & BONE_SKETCHING &&
2522             sketch != NULL &&
2523             sketch->active_stroke != NULL)
2524         {
2525                 return 1;
2526         }
2527         else {
2528                 return 0;
2529         }
2530 }
2531
2532 static int ED_operator_sketch_mode_gesture(bContext *C)
2533 {
2534         ToolSettings *ts = CTX_data_tool_settings(C);
2535         SK_Sketch *sketch = contextSketch(C, 0);
2536
2537         if (ts->bone_sketching & BONE_SKETCHING &&
2538             (ts->bone_sketching & BONE_SKETCHING_QUICK) == 0 &&
2539             sketch != NULL &&
2540             sketch->active_stroke == NULL)
2541         {
2542                 return 1;
2543         }
2544         else {
2545                 return 0;
2546         }
2547 }
2548
2549 int ED_operator_sketch_full_mode(bContext *C)
2550 {
2551         Object *obedit = CTX_data_edit_object(C);
2552         ToolSettings *ts = CTX_data_tool_settings(C);
2553
2554         if (obedit &&
2555             obedit->type == OB_ARMATURE &&
2556             ts->bone_sketching & BONE_SKETCHING &&
2557             (ts->bone_sketching & BONE_SKETCHING_QUICK) == 0)
2558         {
2559                 return 1;
2560         }
2561         else {
2562                 return 0;
2563         }
2564 }
2565
2566 int ED_operator_sketch_mode(const bContext *C)
2567 {
2568         Object *obedit = CTX_data_edit_object(C);
2569         ToolSettings *ts = CTX_data_tool_settings(C);
2570
2571         if (obedit &&
2572             obedit->type == OB_ARMATURE &&
2573             ts->bone_sketching & BONE_SKETCHING)
2574         {
2575                 return 1;
2576         }
2577         else {
2578                 return 0;
2579         }
2580 }
2581
2582 /* ================================================ Operators ================================================ */
2583
2584 void SKETCH_OT_delete(wmOperatorType *ot)
2585 {
2586         /* identifiers */
2587         ot->name = "Delete";
2588         ot->idname = "SKETCH_OT_delete";
2589         ot->description = "Delete a sketch stroke";
2590
2591         /* api callbacks */
2592         ot->invoke = sketch_delete;
2593
2594         ot->poll = ED_operator_sketch_full_mode;
2595
2596         /* flags */
2597 //      ot->flag = OPTYPE_UNDO;
2598 }
2599
2600 void SKETCH_OT_select(wmOperatorType *ot)
2601 {
2602         /* identifiers */
2603         ot->name = "Select";
2604         ot->idname = "SKETCH_OT_select";
2605         ot->description = "Select a sketch stroke";
2606
2607         /* api callbacks */
2608         ot->invoke = sketch_select;
2609
2610         ot->poll = ED_operator_sketch_full_mode;
2611
2612         /* flags */
2613 //      ot->flag = OPTYPE_UNDO;
2614 }
2615
2616 void SKETCH_OT_cancel_stroke(wmOperatorType *ot)
2617 {
2618         /* identifiers */
2619         ot->name = "Cancel Stroke";
2620         ot->idname = "SKETCH_OT_cancel_stroke";
2621         ot->description = "Cancel the current sketch stroke";
2622
2623         /* api callbacks */
2624         ot->invoke = sketch_cancel_invoke;
2625
2626         ot->poll = ED_operator_sketch_mode_active_stroke;
2627
2628         /* flags */
2629 //      ot->flag = OPTYPE_UNDO;
2630 }
2631
2632 void SKETCH_OT_convert(wmOperatorType *ot)
2633 {
2634         /* identifiers */
2635         ot->name = "Convert";
2636         ot->idname = "SKETCH_OT_convert";
2637         ot->description = "Convert the selected sketch strokes to bone chains";
2638
2639         /* api callbacks */
2640         ot->invoke = sketch_convert;
2641
2642         ot->poll = ED_operator_sketch_full_mode;
2643
2644         /* flags */
2645         ot->flag = OPTYPE_UNDO;
2646 }
2647
2648 void SKETCH_OT_finish_stroke(wmOperatorType *ot)
2649 {
2650         /* identifiers */
2651         ot->name = "End Stroke";
2652         ot->idname = "SKETCH_OT_finish_stroke";
2653         ot->description = "End and keep the current sketch stroke";
2654
2655         /* api callbacks */
2656         ot->invoke = sketch_finish;
2657
2658         ot->poll = ED_operator_sketch_mode_active_stroke;
2659
2660         /* flags */
2661 //      ot->flag = OPTYPE_UNDO;
2662 }
2663
2664 void SKETCH_OT_draw_preview(wmOperatorType *ot)
2665 {
2666         /* identifiers */
2667         ot->name = "Draw Preview";
2668         ot->idname = "SKETCH_OT_draw_preview";
2669         ot->description = "Draw preview of current sketch stroke (internal use)";
2670
2671         /* api callbacks */
2672         ot->invoke = sketch_draw_preview;
2673
2674         ot->poll = ED_operator_sketch_mode_active_stroke;
2675
2676         RNA_def_boolean(ot->srna, "snap", 0, "Snap", "");
2677
2678         /* flags */
2679 //      ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2680 }
2681
2682 void SKETCH_OT_draw_stroke(wmOperatorType *ot)
2683 {
2684         /* identifiers */
2685         ot->name = "Draw Stroke";
2686         ot->idname = "SKETCH_OT_draw_stroke";
2687         ot->description = "Start to draw a sketch stroke";
2688
2689         /* api callbacks */
2690         ot->invoke = sketch_draw_stroke;
2691         ot->modal  = sketch_draw_stroke_modal;
2692         ot->cancel = sketch_draw_stroke_cancel;
2693
2694         ot->poll = (int (*)(bContext *))ED_operator_sketch_mode;
2695
2696         RNA_def_boolean(ot->srna, "snap", 0, "Snap", "");
2697
2698         /* flags */
2699         ot->flag = OPTYPE_BLOCKING; // OPTYPE_REGISTER|OPTYPE_UNDO
2700 }
2701
2702 void SKETCH_OT_gesture(wmOperatorType *ot)
2703 {
2704         /* identifiers */
2705         ot->name = "Gesture";
2706         ot->idname = "SKETCH_OT_gesture";
2707         ot->description = "Start to draw a gesture stroke";
2708
2709         /* api callbacks */
2710         ot->invoke = sketch_draw_gesture;
2711         ot->modal  = sketch_draw_gesture_modal;
2712         ot->cancel = sketch_draw_gesture_cancel;
2713
2714         ot->poll = ED_operator_sketch_mode_gesture;
2715
2716         RNA_def_boolean(ot->srna, "snap", 0, "Snap", "");
2717
2718         /* flags */
2719         ot->flag = OPTYPE_BLOCKING; // OPTYPE_UNDO
2720 }
2721