use bool for rna funcs.
[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 "BLF_translation.h"
35
36 #include "BKE_context.h"
37 #include "BKE_sketch.h"
38
39 #include "RNA_define.h"
40 #include "RNA_access.h"
41
42 #include "ED_view3d.h"
43 #include "ED_screen.h"
44
45 #include "BIF_gl.h"
46 #include "ED_armature.h"
47 #include "armature_intern.h"
48 #include "BIF_retarget.h"
49 #include "BIF_generate.h"
50
51 #include "ED_transform.h"
52
53 #include "WM_api.h"
54 #include "WM_types.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 const char *BIF_listTemplates(const bContext *UNUSED(C))
169 {
170         GHashIterator ghi;
171         const char *menu_header = IFACE_("Template %t|None %x0|");
172         char *p;
173
174         if (TEMPLATES_MENU != NULL) {
175                 MEM_freeN(TEMPLATES_MENU);
176         }
177
178         TEMPLATES_MENU = MEM_callocN(sizeof(char) * (BLI_ghash_size(TEMPLATES_HASH) * 32 + 30), "skeleton template menu");
179
180         p = TEMPLATES_MENU;
181
182         p += sprintf(TEMPLATES_MENU, "%s", menu_header);
183
184         BLI_ghashIterator_init(&ghi, TEMPLATES_HASH);
185
186         while (BLI_ghashIterator_notDone(&ghi)) {
187                 Object *ob = BLI_ghashIterator_getValue(&ghi);
188                 int key = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&ghi));
189
190                 p += sprintf(p, "|%s %%x%i", ob->id.name + 2, key);
191
192                 BLI_ghashIterator_step(&ghi);
193         }
194
195         return TEMPLATES_MENU;
196 }
197
198 int   BIF_currentTemplate(const bContext *C)
199 {
200         ToolSettings *ts = CTX_data_tool_settings(C);
201
202         if (TEMPLATES_CURRENT == 0 && ts->skgen_template != NULL) {
203                 GHashIterator ghi;
204                 BLI_ghashIterator_init(&ghi, TEMPLATES_HASH);
205
206                 while (BLI_ghashIterator_notDone(&ghi)) {
207                         Object *ob = BLI_ghashIterator_getValue(&ghi);
208                         int key = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&ghi));
209
210                         if (ob == ts->skgen_template) {
211                                 TEMPLATES_CURRENT = key;
212                                 break;
213                         }
214
215                         BLI_ghashIterator_step(&ghi);
216                 }
217         }
218
219         return TEMPLATES_CURRENT;
220 }
221
222 static RigGraph *sk_makeTemplateGraph(const bContext *C, Object *ob)
223 {
224         Object *obedit = CTX_data_edit_object(C);
225         if (ob == obedit) {
226                 return NULL;
227         }
228
229         if (ob != NULL) {
230                 if (TEMPLATE_RIGG && TEMPLATE_RIGG->ob != ob) {
231                         RIG_freeRigGraph((BGraph *)TEMPLATE_RIGG);
232                         TEMPLATE_RIGG = NULL;
233                 }
234
235                 if (TEMPLATE_RIGG == NULL) {
236                         bArmature *arm;
237
238                         arm = ob->data;
239
240                         TEMPLATE_RIGG = RIG_graphFromArmature(C, ob, arm);
241                 }
242         }
243
244         return TEMPLATE_RIGG;
245 }
246
247 int BIF_nbJointsTemplate(const bContext *C)
248 {
249         ToolSettings *ts = CTX_data_tool_settings(C);
250         RigGraph *rg = sk_makeTemplateGraph(C, ts->skgen_template);
251
252         if (rg) {
253                 return RIG_nbJoints(rg);
254         }
255         else {
256                 return -1;
257         }
258 }
259
260 const char *BIF_nameBoneTemplate(const bContext *C)
261 {
262         ToolSettings *ts = CTX_data_tool_settings(C);
263         SK_Sketch *stk = contextSketch(C, 1);
264         RigGraph *rg;
265         int index = 0;
266
267         if (stk && stk->active_stroke != NULL) {
268                 index = stk->active_stroke->nb_points;
269         }
270
271         rg = sk_makeTemplateGraph(C, ts->skgen_template);
272
273         if (rg == NULL) {
274                 return "";
275         }
276
277         return RIG_nameBone(rg, 0, index);
278 }
279
280 void  BIF_freeTemplates(bContext *UNUSED(C))
281 {
282         if (TEMPLATES_MENU != NULL) {
283                 MEM_freeN(TEMPLATES_MENU);
284                 TEMPLATES_MENU = NULL;
285         }
286
287         if (TEMPLATES_HASH != NULL) {
288                 BLI_ghash_free(TEMPLATES_HASH, NULL, NULL);
289                 TEMPLATES_HASH = NULL;
290         }
291
292         if (TEMPLATE_RIGG != NULL) {
293                 RIG_freeRigGraph((BGraph *)TEMPLATE_RIGG);
294                 TEMPLATE_RIGG = NULL;
295         }
296 }
297
298 void  BIF_setTemplate(bContext *C, int index)
299 {
300         ToolSettings *ts = CTX_data_tool_settings(C);
301         if (index > 0) {
302                 ts->skgen_template = BLI_ghash_lookup(TEMPLATES_HASH, SET_INT_IN_POINTER(index));
303         }
304         else {
305                 ts->skgen_template = NULL;
306
307                 if (TEMPLATE_RIGG != NULL) {
308                         RIG_freeRigGraph((BGraph *)TEMPLATE_RIGG);
309                 }
310                 TEMPLATE_RIGG = NULL;
311         }
312 }
313
314 /*********************** CONVERSION ***************************/
315
316 static void sk_autoname(bContext *C, ReebArc *arc)
317 {
318         ToolSettings *ts = CTX_data_tool_settings(C);
319         if (ts->skgen_retarget_options & SK_RETARGET_AUTONAME) {
320                 if (arc == NULL) {
321                         char *num = ts->skgen_num_string;
322                         int i = atoi(num);
323                         i++;
324                         BLI_snprintf(num, 8, "%i", i);
325                 }
326                 else {
327                         char *side = ts->skgen_side_string;
328                         int valid = 0;
329                         int caps = 0;
330
331                         if (side[0] == '\0') {
332                                 valid = 1;
333                         }
334                         else if (strcmp(side, "R") == 0 || strcmp(side, "L") == 0) {
335                                 valid = 1;
336                                 caps = 1;
337                         }
338                         else if (strcmp(side, "r") == 0 || strcmp(side, "l") == 0) {
339                                 valid = 1;
340                                 caps = 0;
341                         }
342
343                         if (valid) {
344                                 if (arc->head->p[0] < 0) {
345                                         BLI_snprintf(side, 8, caps ? "R" : "r");
346                                 }
347                                 else {
348                                         BLI_snprintf(side, 8, caps ? "L" : "l");
349                                 }
350                         }
351                 }
352         }
353 }
354
355 static ReebNode *sk_pointToNode(SK_Point *pt, float imat[4][4], float tmat[3][3])
356 {
357         ReebNode *node;
358
359         node = MEM_callocN(sizeof(ReebNode), "reeb node");
360         copy_v3_v3(node->p, pt->p);
361         mul_m4_v3(imat, node->p);
362
363         copy_v3_v3(node->no, pt->no);
364         mul_m3_v3(tmat, node->no);
365
366         return node;
367 }
368
369 static ReebArc *sk_strokeToArc(SK_Stroke *stk, float imat[4][4], float tmat[3][3])
370 {
371         ReebArc *arc;
372         int i;
373
374         arc = MEM_callocN(sizeof(ReebArc), "reeb arc");
375         arc->head = sk_pointToNode(stk->points, imat, tmat);
376         arc->tail = sk_pointToNode(sk_lastStrokePoint(stk), imat, tmat);
377
378         arc->bcount = stk->nb_points - 2; /* first and last are nodes, don't count */
379         arc->buckets = MEM_callocN(sizeof(EmbedBucket) * arc->bcount, "Buckets");
380
381         for (i = 0; i < arc->bcount; i++) {
382                 copy_v3_v3(arc->buckets[i].p, stk->points[i + 1].p);
383                 mul_m4_v3(imat, arc->buckets[i].p);
384
385                 copy_v3_v3(arc->buckets[i].no, stk->points[i + 1].no);
386                 mul_m3_v3(tmat, arc->buckets[i].no);
387         }
388
389         return arc;
390 }
391
392 static void sk_retargetStroke(bContext *C, SK_Stroke *stk)
393 {
394         ToolSettings *ts = CTX_data_tool_settings(C);
395         Object *obedit = CTX_data_edit_object(C);
396         float imat[4][4];
397         float tmat[3][3];
398         ReebArc *arc;
399         RigGraph *rg;
400
401         invert_m4_m4(imat, obedit->obmat);
402
403         copy_m3_m4(tmat, obedit->obmat);
404         transpose_m3(tmat);
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         glTranslatef(pt->p[0], pt->p[1], pt->p[2]);
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         glRotatef(angle * (float)(180.0 / M_PI) + 180.0f, axis[0], axis[1], axis[2]);
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         glRotatef(angle * (float)(180.0 / M_PI), axis[0], axis[1], axis[2]);
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                 glLoadName(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], int *dist, 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 < *dist) {
645                                         *dist = 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                 int dist = 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, &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                 int dist = SNAP_MIN_DISTANCE * 2;
768                 int index;
769
770                 closest_pt = sk_snapPointStroke(C, sketch->over.target, dd->mval, &dist, &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);
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
926         if (last != NULL) {
927                 copy_v3_v3(fp, last->p);
928         }
929
930         initgrabz(ar->regiondata, fp[0], fp[1], fp[2]);
931
932         /* method taken from editview.c - mouse_cursor() */
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);
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                 sketch->depth_peels.first = sketch->depth_peels.last = NULL;
982
983                 mvalf[0] = dd->mval[0];
984                 mvalf[1] = dd->mval[1];
985                 peelObjectsContext(C, &sketch->depth_peels, mvalf, SNAP_ALL);
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                 int dist = 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, NULL, 0);
1074                         }
1075                         else {
1076                                 spt = sk_snapPointStroke(C, snap_stk, dd->mval, &dist, 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(C, mval, &dist, vec, no, SNAP_NOT_SELECTED);
1090                 if (found == 1) {
1091                         pt->type = dd->type;
1092                         pt->mode = PT_SNAP;
1093                         copy_v3_v3(pt->p, vec);
1094
1095                         point_added = 1;
1096                 }
1097         }
1098
1099         return point_added;
1100 }
1101
1102 static int sk_addStrokeSnapPoint(bContext *C, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd)
1103 {
1104         int point_added;
1105         ARegion *ar = CTX_wm_region(C);
1106         RegionView3D *rv3d = ar->regiondata;
1107         SK_Point pt;
1108
1109         sk_initPoint(&pt, dd, rv3d->viewinv[2]);
1110
1111         point_added = sk_getStrokeSnapPoint(C, &pt, sketch, stk, dd);
1112
1113         if (point_added) {
1114                 float final_p[3];
1115                 float length, distance;
1116                 int total;
1117                 int i;
1118
1119                 copy_v3_v3(final_p, pt.p);
1120
1121                 sk_projectDrawPoint(C, pt.p, stk, dd);
1122                 sk_appendStrokePoint(stk, &pt);
1123
1124                 /* update all previous point to give smooth Z progresion */
1125                 total = 0;
1126                 length = 0;
1127                 for (i = stk->nb_points - 2; i > 0; i--) {
1128                         length += len_v3v3(stk->points[i].p, stk->points[i + 1].p);
1129                         total++;
1130                         if (stk->points[i].mode == PT_SNAP || stk->points[i].type == PT_EXACT) {
1131                                 break;
1132                         }
1133                 }
1134
1135                 if (total > 1) {
1136                         distance = sk_distanceDepth(C, final_p, stk->points[i].p);
1137
1138                         sk_interpolateDepth(C, stk, i + 1, stk->nb_points - 2, length, distance);
1139                 }
1140
1141                 copy_v3_v3(stk->points[stk->nb_points - 1].p, final_p);
1142
1143                 point_added = 1;
1144         }
1145
1146         return point_added;
1147 }
1148
1149 static void sk_addStrokePoint(bContext *C, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd, short snap)
1150 {
1151         ToolSettings *ts = CTX_data_tool_settings(C);
1152         int point_added = 0;
1153
1154         if (snap) {
1155                 point_added = sk_addStrokeSnapPoint(C, sketch, stk, dd);
1156         }
1157
1158         if (point_added == 0) {
1159                 point_added = sk_addStrokeDrawPoint(C, sketch, stk, dd);
1160         }
1161
1162         if (stk == sketch->active_stroke && ts->bone_sketching & BONE_SKETCHING_ADJUST) {
1163                 sk_updateOverdraw(C, sketch, stk, dd);
1164         }
1165 }
1166
1167 static void sk_getStrokePoint(bContext *C, SK_Point *pt, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd, short snap)
1168 {
1169         int point_added = 0;
1170
1171         if (snap) {
1172                 point_added = sk_getStrokeSnapPoint(C, pt, sketch, stk, dd);
1173                 LAST_SNAP_POINT_VALID = 1;
1174                 copy_v3_v3(LAST_SNAP_POINT, pt->p);
1175         }
1176         else {
1177                 LAST_SNAP_POINT_VALID = 0;
1178         }
1179
1180         if (point_added == 0) {
1181                 point_added = sk_getStrokeDrawPoint(C, pt, sketch, stk, dd);
1182         }
1183 }
1184
1185 /********************************************/
1186
1187 static void *headPoint(void *arg);
1188 static void *tailPoint(void *arg);
1189 static void *nextPoint(void *arg);
1190 static void *nextNPoint(void *arg, int n);
1191 static void *peekPoint(void *arg, int n);
1192 static void *previousPoint(void *arg);
1193 static int   iteratorStopped(void *arg);
1194
1195 static void initIteratorFct(SK_StrokeIterator *iter)
1196 {
1197         iter->head = headPoint;
1198         iter->tail = tailPoint;
1199         iter->peek = peekPoint;
1200         iter->next = nextPoint;
1201         iter->nextN = nextNPoint;
1202         iter->previous = previousPoint;
1203         iter->stopped = iteratorStopped;
1204 }
1205
1206 static SK_Point *setIteratorValues(SK_StrokeIterator *iter, int index)
1207 {
1208         SK_Point *pt = NULL;
1209
1210         if (index >= 0 && index < iter->length) {
1211                 pt = &(iter->stroke->points[iter->start + (iter->stride * index)]);
1212                 iter->p = pt->p;
1213                 iter->no = pt->no;
1214                 iter->size = pt->size;
1215         }
1216         else {
1217                 iter->p = NULL;
1218                 iter->no = NULL;
1219                 iter->size = 0;
1220         }
1221
1222         return pt;
1223 }
1224
1225 void initStrokeIterator(BArcIterator *arg, SK_Stroke *stk, int start, int end)
1226 {
1227         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1228
1229         initIteratorFct(iter);
1230         iter->stroke = stk;
1231
1232         if (start < end) {
1233                 iter->start = start + 1;
1234                 iter->end = end - 1;
1235                 iter->stride = 1;
1236         }
1237         else {
1238                 iter->start = start - 1;
1239                 iter->end = end + 1;
1240                 iter->stride = -1;
1241         }
1242
1243         iter->length = iter->stride * (iter->end - iter->start + 1);
1244
1245         iter->index = -1;
1246 }
1247
1248
1249 static void *headPoint(void *arg)
1250 {
1251         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1252         SK_Point *result = NULL;
1253
1254         result = &(iter->stroke->points[iter->start - iter->stride]);
1255         iter->p = result->p;
1256         iter->no = result->no;
1257         iter->size = result->size;
1258
1259         return result;
1260 }
1261
1262 static void *tailPoint(void *arg)
1263 {
1264         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1265         SK_Point *result = NULL;
1266
1267         result = &(iter->stroke->points[iter->end + iter->stride]);
1268         iter->p = result->p;
1269         iter->no = result->no;
1270         iter->size = result->size;
1271
1272         return result;
1273 }
1274
1275 static void *nextPoint(void *arg)
1276 {
1277         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1278         SK_Point *result = NULL;
1279
1280         iter->index++;
1281         if (iter->index < iter->length) {
1282                 result = setIteratorValues(iter, iter->index);
1283         }
1284
1285         return result;
1286 }
1287
1288 static void *nextNPoint(void *arg, int n)
1289 {
1290         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1291         SK_Point *result = NULL;
1292
1293         iter->index += n;
1294
1295         /* check if passed end */
1296         if (iter->index < iter->length) {
1297                 result = setIteratorValues(iter, iter->index);
1298         }
1299
1300         return result;
1301 }
1302
1303 static void *peekPoint(void *arg, int n)
1304 {
1305         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1306         SK_Point *result = NULL;
1307         int index = iter->index + n;
1308
1309         /* check if passed end */
1310         if (index < iter->length) {
1311                 result = setIteratorValues(iter, index);
1312         }
1313
1314         return result;
1315 }
1316
1317 static void *previousPoint(void *arg)
1318 {
1319         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1320         SK_Point *result = NULL;
1321
1322         if (iter->index > 0) {
1323                 iter->index--;
1324                 result = setIteratorValues(iter, iter->index);
1325         }
1326
1327         return result;
1328 }
1329
1330 static int iteratorStopped(void *arg)
1331 {
1332         SK_StrokeIterator *iter = (SK_StrokeIterator *)arg;
1333
1334         if (iter->index >= iter->length) {
1335                 return 1;
1336         }
1337         else {
1338                 return 0;
1339         }
1340 }
1341
1342 static void sk_convertStroke(bContext *C, SK_Stroke *stk)
1343 {
1344         Object *obedit = CTX_data_edit_object(C);
1345         ToolSettings *ts = CTX_data_tool_settings(C);
1346         bArmature *arm = obedit->data;
1347         SK_Point *head;
1348         EditBone *parent = NULL;
1349         float invmat[4][4]; /* move in caller function */
1350         float tmat[3][3];
1351         int head_index = 0;
1352         int i;
1353
1354         head = NULL;
1355
1356         invert_m4_m4(invmat, obedit->obmat);
1357
1358         copy_m3_m4(tmat, obedit->obmat);
1359         transpose_m3(tmat);
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(void *i1, void *i2)
1492 {
1493         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_clip(ar, v3d, mval, ray_start, ray_end);
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_sortlist(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 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                 short start_val[2], end_val[2];
1785                 short dist;
1786
1787                 if ((ED_view3d_project_short_global(ar, gest->stk->points[0].p,           start_val, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
1788                     (ED_view3d_project_short_global(ar, sk_lastStrokePoint(gest->stk)->p, end_val,   V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
1789                 {
1790
1791                         dist = MAX2(ABS(start_val[0] - end_val[0]), ABS(start_val[1] - end_val[1]));
1792
1793                         /* if gesture is a circle */
1794                         if (dist <= 20) {
1795                                 SK_Intersection *isect;
1796
1797                                 /* check if it circled around an exact point */
1798                                 for (isect = gest->intersections.first; isect; isect = isect->next) {
1799                                         /* only delete strokes that are crossed twice */
1800                                         if (isect->next && isect->next->stroke == isect->stroke) {
1801                                                 int start_index, end_index;
1802                                                 int i;
1803
1804                                                 start_index = MIN2(isect->after, isect->next->after);
1805                                                 end_index = MAX2(isect->before, isect->next->before);
1806
1807                                                 for (i = start_index; i <= end_index; i++) {
1808                                                         if (isect->stroke->points[i].type == PT_EXACT) {
1809                                                                 return 1; /* at least one exact point found, stop detect here */
1810                                                         }
1811                                                 }
1812
1813                                                 /* skip next */
1814                                                 isect = isect->next;
1815                                         }
1816                                 }
1817                         }
1818                 }
1819         }
1820
1821         return 0;
1822 }
1823
1824 void sk_applyMergeGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1825 {
1826         SK_Intersection *isect;
1827
1828         /* check if it circled around an exact point */
1829         for (isect = gest->intersections.first; isect; isect = isect->next) {
1830                 /* only merge strokes that are crossed twice */
1831                 if (isect->next && isect->next->stroke == isect->stroke) {
1832                         int start_index, end_index;
1833                         int i;
1834
1835                         start_index = MIN2(isect->after, isect->next->after);
1836                         end_index = MAX2(isect->before, isect->next->before);
1837
1838                         for (i = start_index; i <= end_index; i++) {
1839                                 /* if exact, switch to continuous */
1840                                 if (isect->stroke->points[i].type == PT_EXACT) {
1841                                         isect->stroke->points[i].type = PT_CONTINUOUS;
1842                                 }
1843                         }
1844
1845                         /* skip next */
1846                         isect = isect->next;
1847                 }
1848         }
1849 }
1850
1851 int sk_detectReverseGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1852 {
1853         if (gest->nb_segments > 2 && gest->nb_intersections == 2 && gest->nb_self_intersections == 0) {
1854                 SK_Intersection *isect;
1855
1856                 /* check if it circled around an exact point */
1857                 for (isect = gest->intersections.first; isect; isect = isect->next) {
1858                         /* only delete strokes that are crossed twice */
1859                         if (isect->next && isect->next->stroke == isect->stroke) {
1860                                 float start_v[3], end_v[3];
1861                                 float angle;
1862
1863                                 if (isect->gesture_index < isect->next->gesture_index) {
1864                                         sub_v3_v3v3(start_v, isect->p, gest->stk->points[0].p);
1865                                         sub_v3_v3v3(end_v, sk_lastStrokePoint(gest->stk)->p, isect->next->p);
1866                                 }
1867                                 else {
1868                                         sub_v3_v3v3(start_v, isect->next->p, gest->stk->points[0].p);
1869                                         sub_v3_v3v3(end_v, sk_lastStrokePoint(gest->stk)->p, isect->p);
1870                                 }
1871
1872                                 angle = RAD2DEGF(angle_v2v2(start_v, end_v));
1873
1874                                 if (angle > 120) {
1875                                         return 1;
1876                                 }
1877
1878                                 /* skip next */
1879                                 isect = isect->next;
1880                         }
1881                 }
1882         }
1883
1884         return 0;
1885 }
1886
1887 void sk_applyReverseGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1888 {
1889         SK_Intersection *isect;
1890
1891         for (isect = gest->intersections.first; isect; isect = isect->next) {
1892                 /* only reverse strokes that are crossed twice */
1893                 if (isect->next && isect->next->stroke == isect->stroke) {
1894                         sk_reverseStroke(isect->stroke);
1895
1896                         /* skip next */
1897                         isect = isect->next;
1898                 }
1899         }
1900 }
1901
1902 int sk_detectConvertGesture(bContext *UNUSED(C), SK_Gesture *gest, SK_Sketch *UNUSED(sketch))
1903 {
1904         if (gest->nb_segments == 3 && gest->nb_self_intersections == 1) {
1905                 return 1;
1906         }
1907         return 0;
1908 }
1909
1910 void sk_applyConvertGesture(bContext *C, SK_Gesture *UNUSED(gest), SK_Sketch *sketch)
1911 {
1912         sk_convert(C, sketch);
1913 }
1914
1915 static void sk_initGesture(bContext *C, SK_Gesture *gest, SK_Sketch *sketch)
1916 {
1917         gest->intersections.first = gest->intersections.last = NULL;
1918         gest->self_intersections.first = gest->self_intersections.last = NULL;
1919
1920         gest->segments = sk_createStroke();
1921         gest->stk = sketch->gesture;
1922
1923         gest->nb_self_intersections = sk_getSelfIntersections(C, &gest->self_intersections, gest->stk);
1924         gest->nb_intersections = sk_getIntersections(C, &gest->intersections, sketch, gest->stk);
1925         gest->nb_segments = sk_getSegments(gest->segments, gest->stk);
1926 }
1927
1928 static void sk_freeGesture(SK_Gesture *gest)
1929 {
1930         sk_freeStroke(gest->segments);
1931         BLI_freelistN(&gest->intersections);
1932         BLI_freelistN(&gest->self_intersections);
1933 }
1934
1935 static void sk_applyGesture(bContext *C, SK_Sketch *sketch)
1936 {
1937         SK_Gesture gest;
1938         SK_GestureAction *act;
1939
1940         sk_initGesture(C, &gest, sketch);
1941
1942         /* detect and apply */
1943         for (act = GESTURE_ACTIONS; act->apply != NULL; act++) {
1944                 if (act->detect(C, &gest, sketch)) {
1945                         act->apply(C, &gest, sketch);
1946                         break;
1947                 }
1948         }
1949
1950         sk_freeGesture(&gest);
1951 }
1952
1953 /********************************************/
1954
1955
1956 static int sk_selectStroke(bContext *C, SK_Sketch *sketch, const int mval[2], int extend)
1957 {
1958         ViewContext vc;
1959         rcti rect;
1960         unsigned int buffer[MAXPICKBUF];
1961         short hits;
1962
1963         view3d_set_viewcontext(C, &vc);
1964
1965         rect.xmin = mval[0] - 5;
1966         rect.xmax = mval[0] + 5;
1967         rect.ymin = mval[1] - 5;
1968         rect.ymax = mval[1] + 5;
1969
1970         hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect);
1971
1972         if (hits > 0) {
1973                 int besthitresult = -1;
1974
1975                 if (hits == 1) {
1976                         besthitresult = buffer[3];
1977                 }
1978                 else {
1979                         besthitresult = buffer[3];
1980                         /* loop and get best hit */
1981                 }
1982
1983                 if (besthitresult > 0) {
1984                         SK_Stroke *selected_stk = BLI_findlink(&sketch->strokes, besthitresult - 1);
1985
1986                         if (extend == 0) {
1987                                 sk_selectAllSketch(sketch, -1);
1988
1989                                 selected_stk->selected = 1;
1990                         }
1991                         else {
1992                                 selected_stk->selected ^= 1;
1993                         }
1994
1995
1996                 }
1997                 return 1;
1998         }
1999
2000         return 0;
2001 }
2002
2003 #if 0 /* UNUSED 2.5 */
2004 static void sk_queueRedrawSketch(SK_Sketch *sketch)
2005 {
2006         if (sketch->active_stroke != NULL)
2007         {
2008                 SK_Point *last = sk_lastStrokePoint(sketch->active_stroke);
2009
2010                 if (last != NULL)
2011                 {
2012 //                      XXX
2013 //                      allqueue(REDRAWVIEW3D, 0);
2014                 }
2015         }
2016 }
2017 #endif
2018
2019 static void sk_drawSketch(Scene *scene, View3D *UNUSED(v3d), SK_Sketch *sketch, int with_names)
2020 {
2021         ToolSettings *ts = scene->toolsettings;
2022         SK_Stroke *stk;
2023
2024         glClear(GL_DEPTH_BUFFER_BIT);
2025         glEnable(GL_DEPTH_TEST);
2026
2027         if (with_names) {
2028                 int id;
2029                 for (id = 1, stk = sketch->strokes.first; stk; id++, stk = stk->next) {
2030                         sk_drawStroke(stk, id, NULL, -1, -1);
2031                 }
2032
2033                 glLoadName(-1);
2034         }
2035         else {
2036                 float selected_rgb[3] = {1, 0, 0};
2037                 float unselected_rgb[3] = {1, 0.5, 0};
2038
2039                 for (stk = sketch->strokes.first; stk; stk = stk->next) {
2040                         int start = -1;
2041                         int end = -1;
2042
2043                         if (sk_hasOverdraw(sketch, stk)) {
2044                                 sk_adjustIndexes(sketch, &start, &end);
2045                         }
2046
2047                         sk_drawStroke(stk, -1, (stk->selected == 1 ? selected_rgb : unselected_rgb), start, end);
2048
2049                         if (stk->selected == 1) {
2050                                 sk_drawStrokeSubdivision(ts, stk);
2051                         }
2052                 }
2053
2054                 if (sketch->active_stroke != NULL) {
2055                         SK_Point *last = sk_lastStrokePoint(sketch->active_stroke);
2056
2057                         if (ts->bone_sketching & BONE_SKETCHING_QUICK) {
2058                                 sk_drawStrokeSubdivision(ts, sketch->active_stroke);
2059                         }
2060
2061                         if (last != NULL) {
2062                                 GLUquadric *quad = gluNewQuadric();
2063                                 gluQuadricNormals(quad, GLU_SMOOTH);
2064
2065                                 glPushMatrix();
2066
2067                                 glEnable(GL_BLEND);
2068                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2069
2070                                 switch (sketch->next_point.mode) {
2071                                         case PT_SNAP:
2072                                                 glColor3f(0, 1, 0);
2073                                                 break;
2074                                         case PT_PROJECT:
2075                                                 glColor3f(0, 0, 0);
2076                                                 break;
2077                                 }
2078
2079                                 sk_drawPoint(quad, &sketch->next_point, 0.1);
2080
2081                                 glColor4f(selected_rgb[0], selected_rgb[1], selected_rgb[2], 0.3);
2082
2083                                 sk_drawEdge(quad, last, &sketch->next_point, 0.1);
2084
2085                                 glDisable(GL_BLEND);
2086
2087                                 glPopMatrix();
2088
2089                                 gluDeleteQuadric(quad);
2090                         }
2091                 }
2092         }
2093
2094 #if 0
2095         if (sketch->depth_peels.first != NULL)
2096         {
2097                 float colors[8][3] = {
2098                         {1, 0, 0},
2099                         {0, 1, 0},
2100                         {0, 0, 1},
2101                         {1, 1, 0},
2102                         {1, 0, 1},
2103                         {0, 1, 1},
2104                         {1, 1, 1},
2105                         {0, 0, 0}
2106                 };
2107                 DepthPeel *p;
2108                 GLUquadric *quad = gluNewQuadric();
2109                 gluQuadricNormals(quad, GLU_SMOOTH);
2110
2111                 for (p = sketch->depth_peels.first; p; p = p->next)
2112                 {
2113                         int index = GET_INT_FROM_POINTER(p->ob);
2114                         index = (index >> 5) & 7;
2115
2116                         glColor3fv(colors[index]);
2117                         glPushMatrix();
2118                         glTranslatef(p->p[0], p->p[1], p->p[2]);
2119                         gluSphere(quad, 0.02, 8, 8);
2120                         glPopMatrix();
2121                 }
2122
2123                 gluDeleteQuadric(quad);
2124         }
2125 #endif
2126
2127         glDisable(GL_DEPTH_TEST);
2128
2129         /* only draw gesture in active area */
2130         if (sketch->gesture != NULL /* && area_is_active_area(G.vd->area) */) {
2131                 float gesture_rgb[3] = {0, 0.5, 1};
2132                 sk_drawStroke(sketch->gesture, -1, gesture_rgb, -1, -1);
2133         }
2134 }
2135
2136 static int sk_finish_stroke(bContext *C, SK_Sketch *sketch)
2137 {
2138         ToolSettings *ts = CTX_data_tool_settings(C);
2139
2140         if (sketch->active_stroke != NULL) {
2141                 SK_Stroke *stk = sketch->active_stroke;
2142
2143                 sk_endStroke(C, sketch);
2144
2145                 if (ts->bone_sketching & BONE_SKETCHING_QUICK) {
2146                         if (ts->bone_sketching_convert == SK_CONVERT_RETARGET) {
2147                                 sk_retargetStroke(C, stk);
2148                         }
2149                         else {
2150                                 sk_convertStroke(C, stk);
2151                         }
2152 //                      XXX
2153 //                      BIF_undo_push("Convert Sketch");
2154                         sk_removeStroke(sketch, stk);
2155 //                      XXX
2156 //                      allqueue(REDRAWBUTSEDIT, 0);
2157                 }
2158
2159 //              XXX
2160 //              allqueue(REDRAWVIEW3D, 0);
2161                 return 1;
2162         }
2163
2164         return 0;
2165 }
2166
2167 static void sk_start_draw_stroke(SK_Sketch *sketch)
2168 {
2169         if (sketch->active_stroke == NULL) {
2170                 sk_startStroke(sketch);
2171                 sk_selectAllSketch(sketch, -1);
2172
2173                 sketch->active_stroke->selected = 1;
2174         }
2175 }
2176
2177 static void sk_start_draw_gesture(SK_Sketch *sketch)
2178 {
2179         sketch->gesture = sk_createStroke();
2180 }
2181
2182 static int sk_draw_stroke(bContext *C, SK_Sketch *sketch, SK_Stroke *stk, SK_DrawData *dd, short snap)
2183 {
2184         if (sk_stroke_filtermval(dd)) {
2185                 sk_addStrokePoint(C, sketch, stk, dd, snap);
2186                 sk_updateDrawData(dd);
2187                 sk_updateNextPoint(sketch, stk);
2188                 
2189                 return 1;
2190         }
2191
2192         return 0;
2193 }
2194
2195 static int ValidSketchViewContext(ViewContext *vc)
2196 {
2197         Object *obedit = vc->obedit;
2198         Scene *scene = vc->scene;
2199
2200         if (obedit &&
2201             obedit->type == OB_ARMATURE &&
2202             scene->toolsettings->bone_sketching & BONE_SKETCHING)
2203         {
2204                 return 1;
2205         }
2206         else {
2207                 return 0;
2208         }
2209 }
2210
2211 int BDR_drawSketchNames(ViewContext *vc)
2212 {
2213         if (ValidSketchViewContext(vc)) {
2214                 SK_Sketch *sketch = viewcontextSketch(vc, 0);
2215                 if (sketch) {
2216                         sk_drawSketch(vc->scene, vc->v3d, sketch, 1);
2217                         return 1;
2218                 }
2219         }
2220
2221         return 0;
2222 }
2223
2224 void BDR_drawSketch(const bContext *C)
2225 {
2226         if (ED_operator_sketch_mode(C)) {
2227                 SK_Sketch *sketch = contextSketch(C, 0);
2228                 if (sketch) {
2229                         sk_drawSketch(CTX_data_scene(C), CTX_wm_view3d(C), sketch, 0);
2230                 }
2231         }
2232 }
2233
2234 static int sketch_delete(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSED(event))
2235 {
2236         SK_Sketch *sketch = contextSketch(C, 0);
2237         if (sketch) {
2238                 sk_deleteSelectedStrokes(sketch);
2239 //                      allqueue(REDRAWVIEW3D, 0);
2240         }
2241         WM_event_add_notifier(C, NC_SCREEN | ND_SKETCH | NA_REMOVED, NULL);
2242         return OPERATOR_FINISHED;
2243 }
2244
2245 void BIF_sk_selectStroke(bContext *C, const int mval[2], short extend)
2246 {
2247         ToolSettings *ts = CTX_data_tool_settings(C);
2248         SK_Sketch *sketch = contextSketch(C, 0);
2249
2250         if (sketch != NULL && ts->bone_sketching & BONE_SKETCHING) {
2251                 if (sk_selectStroke(C, sketch, mval, extend))
2252                         ED_area_tag_redraw(CTX_wm_area(C));
2253         }
2254 }
2255
2256 void BIF_convertSketch(bContext *C)
2257 {
2258         if (ED_operator_sketch_full_mode(C)) {
2259                 SK_Sketch *sketch = contextSketch(C, 0);
2260                 if (sketch) {
2261                         sk_convert(C, sketch);
2262 //                      BIF_undo_push("Convert Sketch");
2263 //                      allqueue(REDRAWVIEW3D, 0);
2264 //                      allqueue(REDRAWBUTSEDIT, 0);
2265                 }
2266         }
2267 }
2268
2269 void BIF_deleteSketch(bContext *C)
2270 {
2271         if (ED_operator_sketch_full_mode(C)) {
2272                 SK_Sketch *sketch = contextSketch(C, 0);
2273                 if (sketch) {
2274                         sk_deleteSelectedStrokes(sketch);
2275 //                      BIF_undo_push("Convert Sketch");
2276 //                      allqueue(REDRAWVIEW3D, 0);
2277                 }
2278         }
2279 }
2280
2281 #if 0
2282 void BIF_selectAllSketch(bContext *C, int mode)
2283 {
2284         if (BIF_validSketchMode(C))
2285         {
2286                 SK_Sketch *sketch = contextSketch(C, 0);
2287                 if (sketch)
2288                 {
2289                         sk_selectAllSketch(sketch, mode);
2290 //                      XXX
2291 //                      allqueue(REDRAWVIEW3D, 0);
2292                 }
2293         }
2294 }
2295 #endif
2296
2297 SK_Sketch *contextSketch(const bContext *C, int create)
2298 {
2299         Object *obedit = CTX_data_edit_object(C);
2300         SK_Sketch *sketch = NULL;
2301
2302         if (obedit && obedit->type == OB_ARMATURE) {
2303                 bArmature *arm = obedit->data;
2304         
2305                 if (arm->sketch == NULL && create) {
2306                         arm->sketch = createSketch();
2307                 }
2308                 sketch = arm->sketch;
2309         }
2310
2311         return sketch;
2312 }
2313
2314 SK_Sketch *viewcontextSketch(ViewContext *vc, int create)
2315 {
2316         Object *obedit = vc->obedit;
2317         SK_Sketch *sketch = NULL;
2318
2319         if (obedit && obedit->type == OB_ARMATURE) {
2320                 bArmature *arm = obedit->data;
2321         
2322                 if (arm->sketch == NULL && create) {
2323                         arm->sketch = createSketch();
2324                 }
2325                 sketch = arm->sketch;
2326         }
2327
2328         return sketch;
2329 }
2330
2331 static int sketch_convert(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSED(event))
2332 {
2333         SK_Sketch *sketch = contextSketch(C, 0);
2334         if (sketch != NULL) {
2335                 sk_convert(C, sketch);
2336                 ED_area_tag_redraw(CTX_wm_area(C));
2337         }
2338         return OPERATOR_FINISHED;
2339 }
2340
2341 static int sketch_cancel(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSED(event))
2342 {
2343         SK_Sketch *sketch = contextSketch(C, 0);
2344         if (sketch != NULL) {
2345                 sk_cancelStroke(sketch);
2346                 ED_area_tag_redraw(CTX_wm_area(C));
2347                 return OPERATOR_FINISHED;
2348         }
2349         return OPERATOR_PASS_THROUGH;
2350 }
2351
2352 static int sketch_finish(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSED(event))
2353 {
2354         SK_Sketch *sketch = contextSketch(C, 0);
2355         if (sketch != NULL) {
2356                 if (sk_finish_stroke(C, sketch)) {
2357                         ED_area_tag_redraw(CTX_wm_area(C));
2358                         return OPERATOR_FINISHED;
2359                 }
2360         }
2361         return OPERATOR_PASS_THROUGH;
2362 }
2363
2364 static int sketch_select(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
2365 {
2366         SK_Sketch *sketch = contextSketch(C, 0);
2367         if (sketch) {
2368                 short extend = 0;
2369                 if (sk_selectStroke(C, sketch, event->mval, extend))
2370                         ED_area_tag_redraw(CTX_wm_area(C));
2371         }
2372
2373         return OPERATOR_FINISHED;
2374 }
2375
2376 static int sketch_draw_stroke_cancel(bContext *C, wmOperator *op)
2377 {
2378         SK_Sketch *sketch = contextSketch(C, 1); /* create just to be sure */
2379         sk_cancelStroke(sketch);
2380         MEM_freeN(op->customdata);
2381         return OPERATOR_CANCELLED;
2382 }
2383
2384 static int sketch_draw_stroke(bContext *C, wmOperator *op, wmEvent *event)
2385 {
2386         short snap = RNA_boolean_get(op->ptr, "snap");
2387         SK_DrawData *dd;
2388         SK_Sketch *sketch = contextSketch(C, 1);
2389
2390         op->customdata = dd = MEM_callocN(sizeof("SK_DrawData"), "SketchDrawData");
2391         sk_initDrawData(dd, event->mval);
2392
2393         sk_start_draw_stroke(sketch);
2394
2395         sk_draw_stroke(C, sketch, sketch->active_stroke, dd, snap);
2396
2397         WM_event_add_modal_handler(C, op);
2398
2399         return OPERATOR_RUNNING_MODAL;
2400 }
2401
2402 static int sketch_draw_gesture_cancel(bContext *C, wmOperator *op)
2403 {
2404         SK_Sketch *sketch = contextSketch(C, 1); /* create just to be sure */
2405         sk_cancelStroke(sketch);
2406         MEM_freeN(op->customdata);
2407         return OPERATOR_CANCELLED;
2408 }
2409
2410 static int sketch_draw_gesture(bContext *C, wmOperator *op, wmEvent *event)
2411 {
2412         short 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, wmEvent *event, short gesture, SK_Stroke *stk)
2429 {
2430         short 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;
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, 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, 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, wmEvent *event)
2499 {
2500         short 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;
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