Cleanup: Rename view3d context set function
[blender.git] / source / blender / editors / space_view3d / view3d_select.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/space_view3d/view3d_select.c
28  *  \ingroup spview3d
29  */
30
31
32 #include <string.h>
33 #include <stdio.h>
34 #include <math.h>
35 #include <float.h>
36 #include <assert.h>
37
38 #include "DNA_action_types.h"
39 #include "DNA_armature_types.h"
40 #include "DNA_curve_types.h"
41 #include "DNA_meta_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_tracking_types.h"
47
48 #include "MEM_guardedalloc.h"
49
50 #include "BLI_math.h"
51 #include "BLI_lasso_2d.h"
52 #include "BLI_rect.h"
53 #include "BLI_linklist.h"
54 #include "BLI_listbase.h"
55 #include "BLI_string.h"
56 #include "BLI_utildefines.h"
57
58 /* vertex box select */
59 #include "IMB_imbuf_types.h"
60 #include "IMB_imbuf.h"
61 #include "BKE_global.h"
62
63 #include "BKE_armature.h"
64 #include "BKE_context.h"
65 #include "BKE_curve.h"
66 #include "BKE_depsgraph.h"
67 #include "BKE_mball.h"
68 #include "BKE_mesh.h"
69 #include "BKE_object.h"
70 #include "BKE_paint.h"
71 #include "BKE_editmesh.h"
72 #include "BKE_tracking.h"
73
74 #include "BIF_gl.h"
75 #include "BIF_glutil.h"
76
77 #include "WM_api.h"
78 #include "WM_types.h"
79
80 #include "RNA_access.h"
81 #include "RNA_define.h"
82 #include "RNA_enum_types.h"
83
84 #include "ED_armature.h"
85 #include "ED_curve.h"
86 #include "ED_particle.h"
87 #include "ED_mesh.h"
88 #include "ED_object.h"
89 #include "ED_screen.h"
90 #include "ED_sculpt.h"
91 #include "ED_mball.h"
92
93 #include "UI_interface.h"
94
95 #include "GPU_draw.h"
96
97 #include "view3d_intern.h"  /* own include */
98
99 // #include "PIL_time_utildefines.h"
100
101 float ED_view3d_select_dist_px(void)
102 {
103         return 75.0f * U.pixelsize;
104 }
105
106 /* TODO: should return whether there is valid context to continue */
107 void ED_view3d_viewcontext_init(bContext *C, ViewContext *vc)
108 {
109         memset(vc, 0, sizeof(ViewContext));
110         vc->ar = CTX_wm_region(C);
111         vc->scene = CTX_data_scene(C);
112         vc->v3d = CTX_wm_view3d(C);
113         vc->win = CTX_wm_window(C);
114         vc->rv3d = CTX_wm_region_view3d(C);
115         vc->obact = CTX_data_active_object(C);
116         vc->obedit = CTX_data_edit_object(C);
117 }
118
119 /*
120  * ob == NULL if you want global matrices
121  * */
122 void view3d_get_transformation(const ARegion *ar, RegionView3D *rv3d, Object *ob, bglMats *mats)
123 {
124         float cpy[4][4];
125         int i, j;
126
127         if (ob) {
128                 mul_m4_m4m4(cpy, rv3d->viewmat, ob->obmat);
129         }
130         else {
131                 copy_m4_m4(cpy, rv3d->viewmat);
132         }
133
134         for (i = 0; i < 4; ++i) {
135                 for (j = 0; j < 4; ++j) {
136                         mats->projection[i * 4 + j] = rv3d->winmat[i][j];
137                         mats->modelview[i * 4 + j] = cpy[i][j];
138                 }
139         }
140
141         mats->viewport[0] = ar->winrct.xmin;
142         mats->viewport[1] = ar->winrct.ymin;
143         mats->viewport[2] = ar->winx;
144         mats->viewport[3] = ar->winy;
145 }
146
147 /* ********************** view3d_select: selection manipulations ********************* */
148
149 /* local prototypes */
150
151 static void edbm_backbuf_check_and_select_verts(BMEditMesh *em, const bool select)
152 {
153         BMVert *eve;
154         BMIter iter;
155         unsigned int index = bm_wireoffs;
156
157         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
158                 if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
159                         if (EDBM_backbuf_check(index)) {
160                                 BM_vert_select_set(em->bm, eve, select);
161                         }
162                 }
163                 index++;
164         }
165 }
166
167 static void edbm_backbuf_check_and_select_edges(BMEditMesh *em, const bool select)
168 {
169         BMEdge *eed;
170         BMIter iter;
171         unsigned int index = bm_solidoffs;
172
173         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
174                 if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
175                         if (EDBM_backbuf_check(index)) {
176                                 BM_edge_select_set(em->bm, eed, select);
177                         }
178                 }
179                 index++;
180         }
181 }
182
183 static void edbm_backbuf_check_and_select_faces(BMEditMesh *em, const bool select)
184 {
185         BMFace *efa;
186         BMIter iter;
187         unsigned int index = 1;
188
189         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
190                 if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
191                         if (EDBM_backbuf_check(index)) {
192                                 BM_face_select_set(em->bm, efa, select);
193                         }
194                 }
195                 index++;
196         }
197 }
198
199
200 /* object mode, edbm_ prefix is confusing here, rename? */
201 static void edbm_backbuf_check_and_select_verts_obmode(Mesh *me, const bool select)
202 {
203         MVert *mv = me->mvert;
204         unsigned int index;
205
206         if (mv) {
207                 for (index = 1; index <= me->totvert; index++, mv++) {
208                         if (EDBM_backbuf_check(index)) {
209                                 if (!(mv->flag & ME_HIDE)) {
210                                         mv->flag = select ? (mv->flag | SELECT) : (mv->flag & ~SELECT);
211                                 }
212                         }
213                 }
214         }
215 }
216
217 /* object mode, edbm_ prefix is confusing here, rename? */
218 static void edbm_backbuf_check_and_select_tfaces(Mesh *me, const bool select)
219 {
220         MPoly *mpoly = me->mpoly;
221         unsigned int index;
222
223         if (mpoly) {
224                 for (index = 1; index <= me->totpoly; index++, mpoly++) {
225                         if (EDBM_backbuf_check(index)) {
226                                 mpoly->flag = select ? (mpoly->flag | ME_FACE_SEL) : (mpoly->flag & ~ME_FACE_SEL);
227                         }
228                 }
229         }
230 }
231
232 /* *********************** GESTURE AND LASSO ******************* */
233
234 typedef struct LassoSelectUserData {
235         ViewContext *vc;
236         const rcti *rect;
237         const rctf *rect_fl;
238         rctf       _rect_fl;
239         const int (*mcords)[2];
240         int moves;
241         bool select;
242
243         /* runtime */
244         int pass;
245         bool is_done;
246         bool is_changed;
247 } LassoSelectUserData;
248
249 static void view3d_userdata_lassoselect_init(LassoSelectUserData *r_data,
250                                              ViewContext *vc, const rcti *rect, const int (*mcords)[2],
251                                              const int moves, const bool select)
252 {
253         r_data->vc = vc;
254
255         r_data->rect = rect;
256         r_data->rect_fl = &r_data->_rect_fl;
257         BLI_rctf_rcti_copy(&r_data->_rect_fl, rect);
258
259         r_data->mcords = mcords;
260         r_data->moves = moves;
261         r_data->select = select;
262
263         /* runtime */
264         r_data->pass = 0;
265         r_data->is_done = false;
266         r_data->is_changed = false;
267 }
268
269 static int view3d_selectable_data(bContext *C)
270 {
271         Object *ob = CTX_data_active_object(C);
272
273         if (!ED_operator_region_view3d_active(C))
274                 return 0;
275
276         if (ob) {
277                 if (ob->mode & OB_MODE_EDIT) {
278                         if (ob->type == OB_FONT) {
279                                 return 0;
280                         }
281                 }
282                 else {
283                         if ((ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)) &&
284                             !BKE_paint_select_elem_test(ob))
285                         {
286                                 return 0;
287                         }
288                 }
289         }
290
291         return 1;
292 }
293
294
295 /* helper also for borderselect */
296 static bool edge_fully_inside_rect(const rctf *rect, const float v1[2], const float v2[2])
297 {
298         return BLI_rctf_isect_pt_v(rect, v1) && BLI_rctf_isect_pt_v(rect, v2);
299 }
300
301 static bool edge_inside_rect(const rctf *rect, const float v1[2], const float v2[2])
302 {
303         int d1, d2, d3, d4;
304         
305         /* check points in rect */
306         if (edge_fully_inside_rect(rect, v1, v2)) return 1;
307         
308         /* check points completely out rect */
309         if (v1[0] < rect->xmin && v2[0] < rect->xmin) return 0;
310         if (v1[0] > rect->xmax && v2[0] > rect->xmax) return 0;
311         if (v1[1] < rect->ymin && v2[1] < rect->ymin) return 0;
312         if (v1[1] > rect->ymax && v2[1] > rect->ymax) return 0;
313         
314         /* simple check lines intersecting. */
315         d1 = (v1[1] - v2[1]) * (v1[0] - rect->xmin) + (v2[0] - v1[0]) * (v1[1] - rect->ymin);
316         d2 = (v1[1] - v2[1]) * (v1[0] - rect->xmin) + (v2[0] - v1[0]) * (v1[1] - rect->ymax);
317         d3 = (v1[1] - v2[1]) * (v1[0] - rect->xmax) + (v2[0] - v1[0]) * (v1[1] - rect->ymax);
318         d4 = (v1[1] - v2[1]) * (v1[0] - rect->xmax) + (v2[0] - v1[0]) * (v1[1] - rect->ymin);
319         
320         if (d1 < 0 && d2 < 0 && d3 < 0 && d4 < 0) return 0;
321         if (d1 > 0 && d2 > 0 && d3 > 0 && d4 > 0) return 0;
322         
323         return 1;
324 }
325
326 static void do_lasso_select_pose__doSelectBone(void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
327 {
328         LassoSelectUserData *data = userData;
329         bArmature *arm = data->vc->obact->data;
330
331         if (PBONE_SELECTABLE(arm, pchan->bone)) {
332                 bool is_point_done = false;
333                 int points_proj_tot = 0;
334
335                 const int x0 = screen_co_a[0];
336                 const int y0 = screen_co_a[1];
337                 const int x1 = screen_co_b[0];
338                 const int y1 = screen_co_b[1];
339
340                 /* project head location to screenspace */
341                 if (x0 != IS_CLIPPED) {
342                         points_proj_tot++;
343                         if (BLI_rcti_isect_pt(data->rect, x0, y0) &&
344                             BLI_lasso_is_point_inside(data->mcords, data->moves, x0, y0, INT_MAX))
345                         {
346                                 is_point_done = true;
347                         }
348                 }
349
350                 /* project tail location to screenspace */
351                 if (x1 != IS_CLIPPED) {
352                         points_proj_tot++;
353                         if (BLI_rcti_isect_pt(data->rect, x1, y1) &&
354                             BLI_lasso_is_point_inside(data->mcords, data->moves, x1, y1, INT_MAX))
355                         {
356                                 is_point_done = true;
357                         }
358                 }
359
360                 /* if one of points selected, we skip the bone itself */
361                 if ((is_point_done == true) ||
362                     ((is_point_done == false) && (points_proj_tot == 2) &&
363                      BLI_lasso_is_edge_inside(data->mcords, data->moves, x0, y0, x1, y1, INT_MAX)))
364                 {
365                         if (data->select) pchan->bone->flag |=  BONE_SELECTED;
366                         else              pchan->bone->flag &= ~BONE_SELECTED;
367                         data->is_changed = true;
368                 }
369                 data->is_changed |= is_point_done;
370         }
371 }
372 static void do_lasso_select_pose(ViewContext *vc, Object *ob, const int mcords[][2], short moves, const bool select)
373 {
374         ViewContext vc_tmp;
375         LassoSelectUserData data;
376         rcti rect;
377         
378         if ((ob->type != OB_ARMATURE) || (ob->pose == NULL)) {
379                 return;
380         }
381
382         vc_tmp = *vc;
383         vc_tmp.obact = ob;
384
385         BLI_lasso_boundbox(&rect, mcords, moves);
386
387         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
388
389         ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d);
390
391         pose_foreachScreenBone(&vc_tmp, do_lasso_select_pose__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
392
393         if (data.is_changed) {
394                 bArmature *arm = ob->data;
395                 if (arm->flag & ARM_HAS_VIZ_DEPS) {
396                         /* mask modifier ('armature' mode), etc. */
397                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
398                 }
399         }
400 }
401
402 static void object_deselect_all_visible(Scene *scene, View3D *v3d)
403 {
404         Base *base;
405
406         for (base = scene->base.first; base; base = base->next) {
407                 if (BASE_SELECTABLE(v3d, base)) {
408                         ED_base_object_select(base, BA_DESELECT);
409                 }
410         }
411 }
412
413 static void do_lasso_select_objects(ViewContext *vc, const int mcords[][2], const short moves,
414                                     const bool extend, const bool select)
415 {
416         Base *base;
417         
418         if (extend == false && select)
419                 object_deselect_all_visible(vc->scene, vc->v3d);
420
421         for (base = vc->scene->base.first; base; base = base->next) {
422                 if (BASE_SELECTABLE(vc->v3d, base)) { /* use this to avoid un-needed lasso lookups */
423                         if (ED_view3d_project_base(vc->ar, base) == V3D_PROJ_RET_OK) {
424                                 if (BLI_lasso_is_point_inside(mcords, moves, base->sx, base->sy, IS_CLIPPED)) {
425
426                                         ED_base_object_select(base, select ? BA_SELECT : BA_DESELECT);
427                                         base->object->flag = base->flag;
428                                 }
429                         }
430                         if (vc->obact == base->object && (base->object->mode & OB_MODE_POSE)) {
431                                 do_lasso_select_pose(vc, base->object, mcords, moves, select);
432                         }
433                 }
434         }
435 }
436
437 static void do_lasso_select_mesh__doSelectVert(void *userData, BMVert *eve, const float screen_co[2], int UNUSED(index))
438 {
439         LassoSelectUserData *data = userData;
440
441         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
442             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
443         {
444                 BM_vert_select_set(data->vc->em->bm, eve, data->select);
445         }
446 }
447 static void do_lasso_select_mesh__doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
448 {
449         LassoSelectUserData *data = userData;
450
451         if (EDBM_backbuf_check(bm_solidoffs + index)) {
452                 const int x0 = screen_co_a[0];
453                 const int y0 = screen_co_a[1];
454                 const int x1 = screen_co_b[0];
455                 const int y1 = screen_co_b[1];
456
457                 if (data->pass == 0) {
458                         if (edge_fully_inside_rect(data->rect_fl, screen_co_a, screen_co_b)  &&
459                             BLI_lasso_is_point_inside(data->mcords, data->moves, x0, y0, IS_CLIPPED) &&
460                             BLI_lasso_is_point_inside(data->mcords, data->moves, x1, y1, IS_CLIPPED))
461                         {
462                                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
463                                 data->is_done = true;
464                         }
465                 }
466                 else {
467                         if (BLI_lasso_is_edge_inside(data->mcords, data->moves, x0, y0, x1, y1, IS_CLIPPED)) {
468                                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
469                         }
470                 }
471         }
472 }
473 static void do_lasso_select_mesh__doSelectFace(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
474 {
475         LassoSelectUserData *data = userData;
476
477         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
478             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
479         {
480                 BM_face_select_set(data->vc->em->bm, efa, data->select);
481         }
482 }
483
484 static void do_lasso_select_mesh(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
485 {
486         LassoSelectUserData data;
487         ToolSettings *ts = vc->scene->toolsettings;
488         rcti rect;
489         int bbsel;
490         
491         /* set editmesh */
492         vc->em = BKE_editmesh_from_object(vc->obedit);
493
494         BLI_lasso_boundbox(&rect, mcords, moves);
495
496         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
497
498         if (extend == false && select)
499                 EDBM_flag_disable_all(vc->em, BM_ELEM_SELECT);
500
501         /* for non zbuf projections, don't change the GL state */
502         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
503
504         glLoadMatrixf(vc->rv3d->viewmat);
505         bbsel = EDBM_backbuf_border_mask_init(vc, mcords, moves, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
506         
507         if (ts->selectmode & SCE_SELECT_VERTEX) {
508                 if (bbsel) {
509                         edbm_backbuf_check_and_select_verts(vc->em, select);
510                 }
511                 else {
512                         mesh_foreachScreenVert(vc, do_lasso_select_mesh__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
513                 }
514         }
515         if (ts->selectmode & SCE_SELECT_EDGE) {
516                 /* Does both bbsel and non-bbsel versions (need screen cos for both) */
517                 data.pass = 0;
518                 mesh_foreachScreenEdge(vc, do_lasso_select_mesh__doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
519
520                 if (data.is_done == false) {
521                         data.pass = 1;
522                         mesh_foreachScreenEdge(vc, do_lasso_select_mesh__doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
523                 }
524         }
525         
526         if (ts->selectmode & SCE_SELECT_FACE) {
527                 if (bbsel) {
528                         edbm_backbuf_check_and_select_faces(vc->em, select);
529                 }
530                 else {
531                         mesh_foreachScreenFace(vc, do_lasso_select_mesh__doSelectFace, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
532                 }
533         }
534         
535         EDBM_backbuf_free();
536         EDBM_selectmode_flush(vc->em);
537 }
538
539 static void do_lasso_select_curve__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
540 {
541         LassoSelectUserData *data = userData;
542         Object *obedit = data->vc->obedit;
543         Curve *cu = (Curve *)obedit->data;
544
545         if (BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED)) {
546                 if (bp) {
547                         bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
548                 }
549                 else {
550                         if (cu->drawflag & CU_HIDE_HANDLES) {
551                                 /* can only be (beztindex == 0) here since handles are hidden */
552                                 bezt->f1 = bezt->f2 = bezt->f3 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
553                         }
554                         else {
555                                 if (beztindex == 0) {
556                                         bezt->f1 = data->select ? (bezt->f1 | SELECT) : (bezt->f1 & ~SELECT);
557                                 }
558                                 else if (beztindex == 1) {
559                                         bezt->f2 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
560                                 }
561                                 else {
562                                         bezt->f3 = data->select ? (bezt->f3 | SELECT) : (bezt->f3 & ~SELECT);
563                                 }
564                         }
565                 }
566         }
567 }
568
569 static void do_lasso_select_curve(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
570 {
571         LassoSelectUserData data;
572         rcti rect;
573
574         BLI_lasso_boundbox(&rect, mcords, moves);
575
576         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
577
578         if (extend == false && select) {
579                 Curve *curve = (Curve *) vc->obedit->data;
580                 ED_curve_deselect_all(curve->editnurb);
581         }
582
583         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
584         nurbs_foreachScreenVert(vc, do_lasso_select_curve__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
585         BKE_curve_nurb_vert_active_validate(vc->obedit->data);
586 }
587
588 static void do_lasso_select_lattice__doSelect(void *userData, BPoint *bp, const float screen_co[2])
589 {
590         LassoSelectUserData *data = userData;
591
592         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
593             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
594         {
595                 bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
596         }
597 }
598 static void do_lasso_select_lattice(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
599 {
600         LassoSelectUserData data;
601         rcti rect;
602
603         BLI_lasso_boundbox(&rect, mcords, moves);
604
605         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
606
607         if (extend == false && select)
608                 ED_lattice_flags_set(vc->obedit, 0);
609
610         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
611         lattice_foreachScreenVert(vc, do_lasso_select_lattice__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
612 }
613
614 static void do_lasso_select_armature__doSelectBone(void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
615 {
616         LassoSelectUserData *data = userData;
617         bArmature *arm = data->vc->obedit->data;
618
619         if (data->select ? EBONE_SELECTABLE(arm, ebone) : EBONE_VISIBLE(arm, ebone)) {
620                 bool is_point_done = false;
621                 int points_proj_tot = 0;
622
623                 const int x0 = screen_co_a[0];
624                 const int y0 = screen_co_a[1];
625                 const int x1 = screen_co_b[0];
626                 const int y1 = screen_co_b[1];
627
628                 /* project head location to screenspace */
629                 if (x0 != IS_CLIPPED) {
630                         points_proj_tot++;
631                         if (BLI_rcti_isect_pt(data->rect, x0, y0) &&
632                             BLI_lasso_is_point_inside(data->mcords, data->moves, x0, y0, INT_MAX))
633                         {
634                                 is_point_done = true;
635                                 if (data->select) ebone->flag |=  BONE_ROOTSEL;
636                                 else              ebone->flag &= ~BONE_ROOTSEL;
637                         }
638                 }
639
640                 /* project tail location to screenspace */
641                 if (x1 != IS_CLIPPED) {
642                         points_proj_tot++;
643                         if (BLI_rcti_isect_pt(data->rect, x1, y1) &&
644                             BLI_lasso_is_point_inside(data->mcords, data->moves, x1, y1, INT_MAX))
645                         {
646                                 is_point_done = true;
647                                 if (data->select) ebone->flag |=  BONE_TIPSEL;
648                                 else              ebone->flag &= ~BONE_TIPSEL;
649                         }
650                 }
651
652                 /* if one of points selected, we skip the bone itself */
653                 if ((is_point_done == false) && (points_proj_tot == 2) &&
654                     BLI_lasso_is_edge_inside(data->mcords, data->moves, x0, y0, x1, y1, INT_MAX))
655                 {
656                         if (data->select) ebone->flag |=  (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
657                         else              ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
658                         data->is_changed = true;
659                 }
660
661                 data->is_changed |= is_point_done;
662         }
663 }
664
665 static void do_lasso_select_armature(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
666 {
667         LassoSelectUserData data;
668         rcti rect;
669
670         BLI_lasso_boundbox(&rect, mcords, moves);
671
672         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
673
674         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
675
676         if (extend == false && select)
677                 ED_armature_deselect_all_visible(vc->obedit);
678
679         armature_foreachScreenBone(vc, do_lasso_select_armature__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
680
681         if (data.is_changed) {
682                 bArmature *arm = vc->obedit->data;
683                 ED_armature_sync_selection(arm->edbo);
684                 ED_armature_validate_active(arm);
685                 WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obedit);
686         }
687 }
688
689 static void do_lasso_select_mball__doSelectElem(void *userData, struct MetaElem *ml, const float screen_co[2])
690 {
691         LassoSelectUserData *data = userData;
692
693         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
694             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], INT_MAX))
695         {
696                 if (data->select) ml->flag |=  SELECT;
697                 else              ml->flag &= ~SELECT;
698                 data->is_changed = true;
699         }
700 }
701 static void do_lasso_select_meta(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
702 {
703         LassoSelectUserData data;
704         rcti rect;
705
706         MetaBall *mb = (MetaBall *)vc->obedit->data;
707
708         if (extend == false && select)
709                 BKE_mball_deselect_all(mb);
710
711         BLI_lasso_boundbox(&rect, mcords, moves);
712
713         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
714
715         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
716
717         mball_foreachScreenElem(vc, do_lasso_select_mball__doSelectElem, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
718 }
719
720 static void do_lasso_select_meshobject__doSelectVert(void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
721 {
722         LassoSelectUserData *data = userData;
723
724         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
725             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
726         {
727                 SET_FLAG_FROM_TEST(mv->flag, data->select, SELECT);
728         }
729 }
730 static void do_lasso_select_paintvert(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
731 {
732         const bool use_zbuf = (vc->v3d->flag & V3D_ZBUF_SELECT) != 0;
733         Object *ob = vc->obact;
734         Mesh *me = ob->data;
735         rcti rect;
736
737         if (me == NULL || me->totvert == 0)
738                 return;
739
740         if (extend == false && select)
741                 paintvert_deselect_all_visible(ob, SEL_DESELECT, false);  /* flush selection at the end */
742
743         BLI_lasso_boundbox(&rect, mcords, moves);
744
745         if (use_zbuf) {
746                 bm_vertoffs = me->totvert + 1; /* max index array */
747
748                 EDBM_backbuf_border_mask_init(vc, mcords, moves, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
749
750                 edbm_backbuf_check_and_select_verts_obmode(me, select);
751
752                 EDBM_backbuf_free();
753         }
754         else {
755                 LassoSelectUserData data;
756
757                 view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
758
759                 ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d);
760
761                 meshobject_foreachScreenVert(vc, do_lasso_select_meshobject__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
762
763         }
764
765         if (select == false) {
766                 BKE_mesh_mselect_validate(me);
767         }
768         paintvert_flush_flags(ob);
769 }
770 static void do_lasso_select_paintface(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
771 {
772         Object *ob = vc->obact;
773         Mesh *me = ob->data;
774         rcti rect;
775
776         if (me == NULL || me->totpoly == 0)
777                 return;
778
779         if (extend == false && select)
780                 paintface_deselect_all_visible(ob, SEL_DESELECT, false);  /* flush selection at the end */
781
782         bm_vertoffs = me->totpoly + 1; /* max index array */
783
784         BLI_lasso_boundbox(&rect, mcords, moves);
785         EDBM_backbuf_border_mask_init(vc, mcords, moves, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
786         
787         edbm_backbuf_check_and_select_tfaces(me, select);
788
789         EDBM_backbuf_free();
790
791         paintface_flush_flags(ob, SELECT);
792 }
793
794 #if 0
795 static void do_lasso_select_node(int mcords[][2], short moves, const bool select)
796 {
797         SpaceNode *snode = sa->spacedata.first;
798         
799         bNode *node;
800         rcti rect;
801         int node_cent[2];
802         float node_centf[2];
803         
804         BLI_lasso_boundbox(&rect, mcords, moves);
805         
806         /* store selection in temp test flag */
807         for (node = snode->edittree->nodes.first; node; node = node->next) {
808                 node_centf[0] = BLI_RCT_CENTER_X(&node->totr);
809                 node_centf[1] = BLI_RCT_CENTER_Y(&node->totr);
810                 
811                 ipoco_to_areaco_noclip(G.v2d, node_centf, node_cent);
812                 if (BLI_rcti_isect_pt_v(&rect, node_cent) && BLI_lasso_is_point_inside(mcords, moves, node_cent[0], node_cent[1])) {
813                         if (select) {
814                                 node->flag |= SELECT;
815                         }
816                         else {
817                                 node->flag &= ~SELECT;
818                         }
819                 }
820         }
821         BIF_undo_push("Lasso select nodes");
822 }
823 #endif
824
825 static void view3d_lasso_select(bContext *C, ViewContext *vc,
826                                 const int mcords[][2], short moves,
827                                 bool extend, bool select)
828 {
829         Object *ob = CTX_data_active_object(C);
830
831         if (vc->obedit == NULL) { /* Object Mode */
832                 if (BKE_paint_select_face_test(ob))
833                         do_lasso_select_paintface(vc, mcords, moves, extend, select);
834                 else if (BKE_paint_select_vert_test(ob))
835                         do_lasso_select_paintvert(vc, mcords, moves, extend, select);
836                 else if (ob && (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT))) {
837                         /* pass */
838                 }
839                 else if (ob && (ob->mode & OB_MODE_PARTICLE_EDIT))
840                         PE_lasso_select(C, mcords, moves, extend, select);
841                 else {
842                         do_lasso_select_objects(vc, mcords, moves, extend, select);
843                         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, vc->scene);
844                 }
845         }
846         else { /* Edit Mode */
847                 switch (vc->obedit->type) {
848                         case OB_MESH:
849                                 do_lasso_select_mesh(vc, mcords, moves, extend, select);
850                                 break;
851                         case OB_CURVE:
852                         case OB_SURF:
853                                 do_lasso_select_curve(vc, mcords, moves, extend, select);
854                                 break;
855                         case OB_LATTICE:
856                                 do_lasso_select_lattice(vc, mcords, moves, extend, select);
857                                 break;
858                         case OB_ARMATURE:
859                                 do_lasso_select_armature(vc, mcords, moves, extend, select);
860                                 break;
861                         case OB_MBALL:
862                                 do_lasso_select_meta(vc, mcords, moves, extend, select);
863                                 break;
864                         default:
865                                 assert(!"lasso select on incorrect object type");
866                                 break;
867                 }
868
869                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc->obedit->data);
870         }
871 }
872
873
874 /* lasso operator gives properties, but since old code works
875  * with short array we convert */
876 static int view3d_lasso_select_exec(bContext *C, wmOperator *op)
877 {
878         ViewContext vc;
879         int mcords_tot;
880         const int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
881         
882         if (mcords) {
883                 bool extend, select;
884                 view3d_operator_needs_opengl(C);
885                 
886                 /* setup view context for argument to callbacks */
887                 ED_view3d_viewcontext_init(C, &vc);
888                 
889                 extend = RNA_boolean_get(op->ptr, "extend");
890                 select = !RNA_boolean_get(op->ptr, "deselect");
891                 view3d_lasso_select(C, &vc, mcords, mcords_tot, extend, select);
892                 
893                 MEM_freeN((void *)mcords);
894
895                 return OPERATOR_FINISHED;
896         }
897         return OPERATOR_PASS_THROUGH;
898 }
899
900 void VIEW3D_OT_select_lasso(wmOperatorType *ot)
901 {
902         ot->name = "Lasso Select";
903         ot->description = "Select items using lasso selection";
904         ot->idname = "VIEW3D_OT_select_lasso";
905         
906         ot->invoke = WM_gesture_lasso_invoke;
907         ot->modal = WM_gesture_lasso_modal;
908         ot->exec = view3d_lasso_select_exec;
909         ot->poll = view3d_selectable_data;
910         ot->cancel = WM_gesture_lasso_cancel;
911         
912         /* flags */
913         ot->flag = OPTYPE_UNDO;
914         
915         /* properties */
916         WM_operator_properties_gesture_lasso_select(ot);
917 }
918
919 /* ************************** mouse select ************************* */
920
921 /* The max number of menu items in an object select menu */
922 typedef struct SelMenuItemF {
923         char idname[MAX_ID_NAME - 2];
924         int icon;
925 } SelMenuItemF;
926
927 #define SEL_MENU_SIZE   22
928 static SelMenuItemF object_mouse_select_menu_data[SEL_MENU_SIZE];
929
930 /* special (crappy) operator only for menu select */
931 static const EnumPropertyItem *object_select_menu_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
932 {
933         EnumPropertyItem *item = NULL, item_tmp = {0};
934         int totitem = 0;
935         int i = 0;
936
937         /* don't need context but avoid docgen using this */
938         if (C == NULL || object_mouse_select_menu_data[i].idname[0] == '\0') {
939                 return DummyRNA_NULL_items;
940         }
941
942         for (; i < SEL_MENU_SIZE && object_mouse_select_menu_data[i].idname[0] != '\0'; i++) {
943                 item_tmp.name = object_mouse_select_menu_data[i].idname;
944                 item_tmp.identifier = object_mouse_select_menu_data[i].idname;
945                 item_tmp.value = i;
946                 item_tmp.icon = object_mouse_select_menu_data[i].icon;
947                 RNA_enum_item_add(&item, &totitem, &item_tmp);
948         }
949
950         RNA_enum_item_end(&item, &totitem);
951         *r_free = true;
952
953         return item;
954 }
955
956 static int object_select_menu_exec(bContext *C, wmOperator *op)
957 {
958         const int name_index = RNA_enum_get(op->ptr, "name");
959         const bool toggle = RNA_boolean_get(op->ptr, "toggle");
960         bool changed = false;
961         const char *name = object_mouse_select_menu_data[name_index].idname;
962
963         if (!toggle) {
964                 CTX_DATA_BEGIN (C, Base *, base, selectable_bases)
965                 {
966                         if (base->flag & SELECT) {
967                                 ED_base_object_select(base, BA_DESELECT);
968                                 changed = true;
969                         }
970                 }
971                 CTX_DATA_END;
972         }
973
974         CTX_DATA_BEGIN (C, Base *, base, selectable_bases)
975         {
976                 /* this is a bit dodjy, there should only be ONE object with this name, but library objects can mess this up */
977                 if (STREQ(name, base->object->id.name + 2)) {
978                         ED_base_object_activate(C, base);
979                         ED_base_object_select(base, BA_SELECT);
980                         changed = true;
981                 }
982         }
983         CTX_DATA_END;
984
985         /* weak but ensures we activate menu again before using the enum */
986         memset(object_mouse_select_menu_data, 0, sizeof(object_mouse_select_menu_data));
987
988         /* undo? */
989         if (changed) {
990                 WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C));
991                 return OPERATOR_FINISHED;
992         }
993         else {
994                 return OPERATOR_CANCELLED;
995         }
996 }
997
998 void VIEW3D_OT_select_menu(wmOperatorType *ot)
999 {
1000         PropertyRNA *prop;
1001
1002         /* identifiers */
1003         ot->name = "Select Menu";
1004         ot->description = "Menu object selection";
1005         ot->idname = "VIEW3D_OT_select_menu";
1006
1007         /* api callbacks */
1008         ot->invoke = WM_menu_invoke;
1009         ot->exec = object_select_menu_exec;
1010
1011         /* flags */
1012         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1013
1014         /* keyingset to use (dynamic enum) */
1015         prop = RNA_def_enum(ot->srna, "name", DummyRNA_NULL_items, 0, "Object Name", "");
1016         RNA_def_enum_funcs(prop, object_select_menu_enum_itemf);
1017         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_ENUM_NO_TRANSLATE);
1018         ot->prop = prop;
1019
1020         RNA_def_boolean(ot->srna, "toggle", 0, "Toggle", "Toggle selection instead of deselecting everything first");
1021 }
1022
1023 static void deselectall_except(Scene *scene, Base *b)   /* deselect all except b */
1024 {
1025         Base *base;
1026         
1027         for (base = FIRSTBASE; base; base = base->next) {
1028                 if (base->flag & SELECT) {
1029                         if (b != base) {
1030                                 ED_base_object_select(base, BA_DESELECT);
1031                         }
1032                 }
1033         }
1034 }
1035
1036 static Base *object_mouse_select_menu(
1037         bContext *C, ViewContext *vc, unsigned int *buffer, int hits,
1038         const int mval[2], bool toggle)
1039 {
1040         short baseCount = 0;
1041         bool ok;
1042         LinkNode *linklist = NULL;
1043         
1044         CTX_DATA_BEGIN (C, Base *, base, selectable_bases)
1045         {
1046                 ok = false;
1047
1048                 /* two selection methods, the CTRL select uses max dist of 15 */
1049                 if (buffer) {
1050                         for (int a = 0; a < hits; a++) {
1051                                 /* index was converted */
1052                                 if (base->selcol == (buffer[(4 * a) + 3] & ~0xFFFF0000)) {
1053                                         ok = true;
1054                                         break;
1055                                 }
1056                         }
1057                 }
1058                 else {
1059                         const int dist = 15 * U.pixelsize;
1060                         if (ED_view3d_project_base(vc->ar, base) == V3D_PROJ_RET_OK) {
1061                                 const int delta_px[2] = {base->sx - mval[0], base->sy - mval[1]};
1062                                 if (len_manhattan_v2_int(delta_px) < dist) {
1063                                         ok = true;
1064                                 }
1065                         }
1066                 }
1067
1068                 if (ok) {
1069                         baseCount++;
1070                         BLI_linklist_prepend(&linklist, base);
1071
1072                         if (baseCount == SEL_MENU_SIZE)
1073                                 break;
1074                 }
1075         }
1076         CTX_DATA_END;
1077
1078         if (baseCount == 0) {
1079                 return NULL;
1080         }
1081         if (baseCount == 1) {
1082                 Base *base = (Base *)linklist->link;
1083                 BLI_linklist_free(linklist, NULL);
1084                 return base;
1085         }
1086         else {
1087                 /* UI, full in static array values that we later use in an enum function */
1088                 LinkNode *node;
1089                 int i;
1090
1091                 memset(object_mouse_select_menu_data, 0, sizeof(object_mouse_select_menu_data));
1092
1093                 for (node = linklist, i = 0; node; node = node->next, i++) {
1094                         Base *base = node->link;
1095                         Object *ob = base->object;
1096                         const char *name = ob->id.name + 2;
1097
1098                         BLI_strncpy(object_mouse_select_menu_data[i].idname, name, MAX_ID_NAME - 2);
1099                         object_mouse_select_menu_data[i].icon = UI_icon_from_id(&ob->id);
1100                 }
1101
1102                 {
1103                         wmOperatorType *ot = WM_operatortype_find("VIEW3D_OT_select_menu", false);
1104                         PointerRNA ptr;
1105
1106                         WM_operator_properties_create_ptr(&ptr, ot);
1107                         RNA_boolean_set(&ptr, "toggle", toggle);
1108                         WM_operator_name_call_ptr(C, ot, WM_OP_INVOKE_DEFAULT, &ptr);
1109                         WM_operator_properties_free(&ptr);
1110                 }
1111
1112                 BLI_linklist_free(linklist, NULL);
1113                 return NULL;
1114         }
1115 }
1116
1117 static bool selectbuffer_has_bones(const uint *buffer, const uint hits)
1118 {
1119         unsigned int i;
1120         for (i = 0; i < hits; i++) {
1121                 if (buffer[(4 * i) + 3] & 0xFFFF0000) {
1122                         return true;
1123                 }
1124         }
1125         return false;
1126 }
1127
1128 /* utility function for mixed_bones_object_selectbuffer */
1129 static int selectbuffer_ret_hits_15(unsigned int *UNUSED(buffer), const int hits15)
1130 {
1131         return hits15;
1132 }
1133
1134 static int selectbuffer_ret_hits_9(unsigned int *buffer, const int hits15, const int hits9)
1135 {
1136         const int offs = 4 * hits15;
1137         memcpy(buffer, buffer + offs, 4 * hits9 * sizeof(unsigned int));
1138         return hits9;
1139 }
1140
1141 static int selectbuffer_ret_hits_5(unsigned int *buffer, const int hits15, const int hits9, const int hits5)
1142 {
1143         const int offs = 4 * hits15 + 4 * hits9;
1144         memcpy(buffer, buffer + offs, 4 * hits5  * sizeof(unsigned int));
1145         return hits5;
1146 }
1147
1148 /* we want a select buffer with bones, if there are... */
1149 /* so check three selection levels and compare */
1150 static int mixed_bones_object_selectbuffer(
1151         ViewContext *vc, unsigned int *buffer, const int mval[2],
1152         bool use_cycle, bool enumerate,
1153         bool *r_do_nearest)
1154 {
1155         rcti rect;
1156         int hits15, hits9 = 0, hits5 = 0;
1157         bool has_bones15 = false, has_bones9 = false, has_bones5 = false;
1158         static int last_mval[2] = {-100, -100};
1159         bool do_nearest = false;
1160         View3D *v3d = vc->v3d;
1161
1162         /* define if we use solid nearest select or not */
1163         if (use_cycle) {
1164                 if (v3d->drawtype > OB_WIRE) {
1165                         do_nearest = true;
1166                         if (len_manhattan_v2v2_int(mval, last_mval) < 3) {
1167                                 do_nearest = false;
1168                         }
1169                 }
1170                 copy_v2_v2_int(last_mval, mval);
1171         }
1172         else {
1173                 if (v3d->drawtype > OB_WIRE) {
1174                         do_nearest = true;
1175                 }
1176         }
1177
1178         if (r_do_nearest) {
1179                 *r_do_nearest = do_nearest;
1180         }
1181
1182         do_nearest = do_nearest && !enumerate;
1183
1184         const int select_mode = (do_nearest ? VIEW3D_SELECT_PICK_NEAREST : VIEW3D_SELECT_PICK_ALL);
1185         int hits = 0;
1186
1187         /* we _must_ end cache before return, use 'goto finally' */
1188         view3d_opengl_select_cache_begin();
1189
1190         BLI_rcti_init_pt_radius(&rect, mval, 14);
1191         hits15 = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, select_mode);
1192         if (hits15 == 1) {
1193                 hits = selectbuffer_ret_hits_15(buffer, hits15);
1194                 goto finally;
1195         }
1196         else if (hits15 > 0) {
1197                 int offs;
1198                 has_bones15 = selectbuffer_has_bones(buffer, hits15);
1199
1200                 offs = 4 * hits15;
1201                 BLI_rcti_init_pt_radius(&rect, mval, 9);
1202                 hits9 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode);
1203                 if (hits9 == 1) {
1204                         hits = selectbuffer_ret_hits_9(buffer, hits15, hits9);
1205                         goto finally;
1206                 }
1207                 else if (hits9 > 0) {
1208                         has_bones9 = selectbuffer_has_bones(buffer + offs, hits9);
1209
1210                         offs += 4 * hits9;
1211                         BLI_rcti_init_pt_radius(&rect, mval, 5);
1212                         hits5 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode);
1213                         if (hits5 == 1) {
1214                                 hits = selectbuffer_ret_hits_5(buffer, hits15, hits9, hits5);
1215                                 goto finally;
1216                         }
1217                         else if (hits5 > 0) {
1218                                 has_bones5 = selectbuffer_has_bones(buffer + offs, hits5);
1219                         }
1220                 }
1221
1222                 if      (has_bones5)  { hits = selectbuffer_ret_hits_5(buffer,  hits15, hits9, hits5); goto finally; }
1223                 else if (has_bones9)  { hits = selectbuffer_ret_hits_9(buffer,  hits15, hits9); goto finally; }
1224                 else if (has_bones15) { hits = selectbuffer_ret_hits_15(buffer, hits15); goto finally; }
1225
1226                 if      (hits5 > 0) { hits = selectbuffer_ret_hits_5(buffer,  hits15, hits9, hits5); goto finally; }
1227                 else if (hits9 > 0) { hits = selectbuffer_ret_hits_9(buffer,  hits15, hits9); goto finally; }
1228                 else                { hits = selectbuffer_ret_hits_15(buffer, hits15); goto finally; }
1229         }
1230
1231 finally:
1232         view3d_opengl_select_cache_end();
1233
1234         return hits;
1235 }
1236
1237 /* returns basact */
1238 static Base *mouse_select_eval_buffer(
1239         ViewContext *vc, const uint *buffer, int hits,
1240         Base *startbase, bool has_bones, bool do_nearest)
1241 {
1242         Scene *scene = vc->scene;
1243         View3D *v3d = vc->v3d;
1244         Base *base, *basact = NULL;
1245         int a;
1246         
1247         if (do_nearest) {
1248                 unsigned int min = 0xFFFFFFFF;
1249                 int selcol = 0, notcol = 0;
1250                 
1251                 
1252                 if (has_bones) {
1253                         /* we skip non-bone hits */
1254                         for (a = 0; a < hits; a++) {
1255                                 if (min > buffer[4 * a + 1] && (buffer[4 * a + 3] & 0xFFFF0000) ) {
1256                                         min = buffer[4 * a + 1];
1257                                         selcol = buffer[4 * a + 3] & 0xFFFF;
1258                                 }
1259                         }
1260                 }
1261                 else {
1262                         /* only exclude active object when it is selected... */
1263                         if (BASACT && (BASACT->flag & SELECT) && hits > 1) notcol = BASACT->selcol;
1264                         
1265                         for (a = 0; a < hits; a++) {
1266                                 if (min > buffer[4 * a + 1] && notcol != (buffer[4 * a + 3] & 0xFFFF)) {
1267                                         min = buffer[4 * a + 1];
1268                                         selcol = buffer[4 * a + 3] & 0xFFFF;
1269                                 }
1270                         }
1271                 }
1272                 
1273                 base = FIRSTBASE;
1274                 while (base) {
1275                         if (BASE_SELECTABLE(v3d, base)) {
1276                                 if (base->selcol == selcol) break;
1277                         }
1278                         base = base->next;
1279                 }
1280                 if (base) basact = base;
1281         }
1282         else {
1283                 
1284                 base = startbase;
1285                 while (base) {
1286                         /* skip objects with select restriction, to prevent prematurely ending this loop
1287                          * with an un-selectable choice */
1288                         if (base->object->restrictflag & OB_RESTRICT_SELECT) {
1289                                 base = base->next;
1290                                 if (base == NULL) base = FIRSTBASE;
1291                                 if (base == startbase) break;
1292                         }
1293                         
1294                         if (BASE_SELECTABLE(v3d, base)) {
1295                                 for (a = 0; a < hits; a++) {
1296                                         if (has_bones) {
1297                                                 /* skip non-bone objects */
1298                                                 if ((buffer[4 * a + 3] & 0xFFFF0000)) {
1299                                                         if (base->selcol == (buffer[(4 * a) + 3] & 0xFFFF))
1300                                                                 basact = base;
1301                                                 }
1302                                         }
1303                                         else {
1304                                                 if (base->selcol == (buffer[(4 * a) + 3] & 0xFFFF))
1305                                                         basact = base;
1306                                         }
1307                                 }
1308                         }
1309                         
1310                         if (basact) break;
1311                         
1312                         base = base->next;
1313                         if (base == NULL) base = FIRSTBASE;
1314                         if (base == startbase) break;
1315                 }
1316         }
1317         
1318         return basact;
1319 }
1320
1321 /* mval comes from event->mval, only use within region handlers */
1322 Base *ED_view3d_give_base_under_cursor(bContext *C, const int mval[2])
1323 {
1324         ViewContext vc;
1325         Base *basact = NULL;
1326         unsigned int buffer[MAXPICKBUF];
1327         int hits;
1328         bool do_nearest;
1329         
1330         /* setup view context for argument to callbacks */
1331         view3d_operator_needs_opengl(C);
1332         ED_view3d_viewcontext_init(C, &vc);
1333         
1334         hits = mixed_bones_object_selectbuffer(&vc, buffer, mval, false, false, &do_nearest);
1335         
1336         if (hits > 0) {
1337                 const bool has_bones = selectbuffer_has_bones(buffer, hits);
1338                 basact = mouse_select_eval_buffer(&vc, buffer, hits, vc.scene->base.first, has_bones, do_nearest);
1339         }
1340         
1341         return basact;
1342 }
1343
1344 static void deselect_all_tracks(MovieTracking *tracking)
1345 {
1346         MovieTrackingObject *object;
1347
1348         object = tracking->objects.first;
1349         while (object) {
1350                 ListBase *tracksbase = BKE_tracking_object_get_tracks(tracking, object);
1351                 MovieTrackingTrack *track = tracksbase->first;
1352
1353                 while (track) {
1354                         BKE_tracking_track_deselect(track, TRACK_AREA_ALL);
1355
1356                         track = track->next;
1357                 }
1358
1359                 object = object->next;
1360         }
1361 }
1362
1363 /* mval is region coords */
1364 static bool ed_object_select_pick(
1365         bContext *C, const int mval[2],
1366         bool extend, bool deselect, bool toggle, bool obcenter, bool enumerate, bool object)
1367 {
1368         ViewContext vc;
1369         ARegion *ar = CTX_wm_region(C);
1370         View3D *v3d = CTX_wm_view3d(C);
1371         Scene *scene = CTX_data_scene(C);
1372         Base *base, *startbase = NULL, *basact = NULL, *oldbasact = NULL;
1373         bool is_obedit;
1374         float dist = ED_view3d_select_dist_px() * 1.3333f;
1375         bool retval = false;
1376         int hits;
1377         const float mval_fl[2] = {(float)mval[0], (float)mval[1]};
1378
1379         
1380         /* setup view context for argument to callbacks */
1381         ED_view3d_viewcontext_init(C, &vc);
1382
1383         is_obedit = (vc.obedit != NULL);
1384         if (object) {
1385                 /* signal for view3d_opengl_select to skip editmode objects */
1386                 vc.obedit = NULL;
1387         }
1388         
1389         /* always start list from basact in wire mode */
1390         startbase =  FIRSTBASE;
1391         if (BASACT && BASACT->next) startbase = BASACT->next;
1392         
1393         /* This block uses the control key to make the object selected by its center point rather than its contents */
1394         /* in editmode do not activate */
1395         if (obcenter) {
1396                 
1397                 /* note; shift+alt goes to group-flush-selecting */
1398                 if (enumerate) {
1399                         basact = object_mouse_select_menu(C, &vc, NULL, 0, mval, toggle);
1400                 }
1401                 else {
1402                         base = startbase;
1403                         while (base) {
1404                                 if (BASE_SELECTABLE(v3d, base)) {
1405                                         float screen_co[2];
1406                                         if (ED_view3d_project_float_global(ar, base->object->obmat[3], screen_co,
1407                                                                            V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
1408                                         {
1409                                                 float dist_temp = len_manhattan_v2v2(mval_fl, screen_co);
1410                                                 if (base == BASACT) dist_temp += 10.0f;
1411                                                 if (dist_temp < dist) {
1412                                                         dist = dist_temp;
1413                                                         basact = base;
1414                                                 }
1415                                         }
1416                                 }
1417                                 base = base->next;
1418                                 
1419                                 if (base == NULL) base = FIRSTBASE;
1420                                 if (base == startbase) break;
1421                         }
1422                 }
1423         }
1424         else {
1425                 unsigned int buffer[MAXPICKBUF];
1426                 bool do_nearest;
1427
1428                 // TIMEIT_START(select_time);
1429
1430                 /* if objects have posemode set, the bones are in the same selection buffer */
1431                 hits = mixed_bones_object_selectbuffer(&vc, buffer, mval, true, enumerate, &do_nearest);
1432
1433                 // TIMEIT_END(select_time);
1434
1435                 if (hits > 0) {
1436                         /* note: bundles are handling in the same way as bones */
1437                         const bool has_bones = selectbuffer_has_bones(buffer, hits);
1438
1439                         /* note; shift+alt goes to group-flush-selecting */
1440                         if (enumerate) {
1441                                 basact = object_mouse_select_menu(C, &vc, buffer, hits, mval, toggle);
1442                         }
1443                         else {
1444                                 basact = mouse_select_eval_buffer(&vc, buffer, hits, startbase, has_bones, do_nearest);
1445                         }
1446                         
1447                         if (has_bones && basact) {
1448                                 if (basact->object->type == OB_CAMERA) {
1449                                         if (BASACT == basact) {
1450                                                 int i, hitresult;
1451                                                 bool changed = false;
1452
1453                                                 for (i = 0; i < hits; i++) {
1454                                                         hitresult = buffer[3 + (i * 4)];
1455
1456                                                         /* if there's bundles in buffer select bundles first,
1457                                                          * so non-camera elements should be ignored in buffer */
1458                                                         if (basact->selcol != (hitresult & 0xFFFF)) {
1459                                                                 continue;
1460                                                         }
1461
1462                                                         /* index of bundle is 1<<16-based. if there's no "bone" index
1463                                                          * in height word, this buffer value belongs to camera. not to bundle */
1464                                                         if (buffer[4 * i + 3] & 0xFFFF0000) {
1465                                                                 MovieClip *clip = BKE_object_movieclip_get(scene, basact->object, false);
1466                                                                 MovieTracking *tracking = &clip->tracking;
1467                                                                 ListBase *tracksbase;
1468                                                                 MovieTrackingTrack *track;
1469
1470                                                                 track = BKE_tracking_track_get_indexed(&clip->tracking, hitresult >> 16, &tracksbase);
1471
1472                                                                 if (TRACK_SELECTED(track) && extend) {
1473                                                                         changed = false;
1474                                                                         BKE_tracking_track_deselect(track, TRACK_AREA_ALL);
1475                                                                 }
1476                                                                 else {
1477                                                                         int oldsel = TRACK_SELECTED(track) ? 1 : 0;
1478                                                                         if (!extend)
1479                                                                                 deselect_all_tracks(tracking);
1480
1481                                                                         BKE_tracking_track_select(tracksbase, track, TRACK_AREA_ALL, extend);
1482
1483                                                                         if (oldsel != (TRACK_SELECTED(track) ? 1 : 0))
1484                                                                                 changed = true;
1485                                                                 }
1486
1487                                                                 basact->flag |= SELECT;
1488                                                                 basact->object->flag = basact->flag;
1489
1490                                                                 retval = true;
1491
1492                                                                 WM_event_add_notifier(C, NC_MOVIECLIP | ND_SELECT, track);
1493                                                                 WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
1494
1495                                                                 break;
1496                                                         }
1497                                                 }
1498
1499                                                 if (!changed) {
1500                                                         /* fallback to regular object selection if no new bundles were selected,
1501                                                          * allows to select object parented to reconstruction object */
1502                                                         basact = mouse_select_eval_buffer(&vc, buffer, hits, startbase, 0, do_nearest);
1503                                                 }
1504                                         }
1505                                 }
1506                                 else if (ED_do_pose_selectbuffer(scene, basact, buffer, hits, extend, deselect, toggle, do_nearest)) {
1507                                         /* then bone is found */
1508                                 
1509                                         /* we make the armature selected: 
1510                                          * not-selected active object in posemode won't work well for tools */
1511                                         basact->flag |= SELECT;
1512                                         basact->object->flag = basact->flag;
1513                                         
1514                                         retval = true;
1515                                         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, basact->object);
1516                                         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_ACTIVE, basact->object);
1517                                         
1518                                         /* in weightpaint, we use selected bone to select vertexgroup, so no switch to new active object */
1519                                         if (BASACT && (BASACT->object->mode & OB_MODE_WEIGHT_PAINT)) {
1520                                                 /* prevent activating */
1521                                                 basact = NULL;
1522                                         }
1523
1524                                 }
1525                                 /* prevent bone selecting to pass on to object selecting */
1526                                 if (basact == BASACT)
1527                                         basact = NULL;
1528                         }
1529                 }
1530         }
1531         
1532         /* so, do we have something selected? */
1533         if (basact) {
1534                 retval = true;
1535                 
1536                 if (vc.obedit) {
1537                         /* only do select */
1538                         deselectall_except(scene, basact);
1539                         ED_base_object_select(basact, BA_SELECT);
1540                 }
1541                 /* also prevent making it active on mouse selection */
1542                 else if (BASE_SELECTABLE(v3d, basact)) {
1543
1544                         oldbasact = BASACT;
1545                         
1546                         if (extend) {
1547                                 ED_base_object_select(basact, BA_SELECT);
1548                         }
1549                         else if (deselect) {
1550                                 ED_base_object_select(basact, BA_DESELECT);
1551                         }
1552                         else if (toggle) {
1553                                 if (basact->flag & SELECT) {
1554                                         if (basact == oldbasact) {
1555                                                 ED_base_object_select(basact, BA_DESELECT);
1556                                         }
1557                                 }
1558                                 else {
1559                                         ED_base_object_select(basact, BA_SELECT);
1560                                 }
1561                         }
1562                         else {
1563                                 deselectall_except(scene, basact);
1564                                 ED_base_object_select(basact, BA_SELECT);
1565                         }
1566
1567                         if ((oldbasact != basact) && (is_obedit == false)) {
1568                                 ED_base_object_activate(C, basact); /* adds notifier */
1569                         }
1570                 }
1571
1572                 WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
1573         }
1574
1575         return retval;
1576 }
1577
1578 /* ********************  border and circle ************************************** */
1579
1580 typedef struct BoxSelectUserData {
1581         ViewContext *vc;
1582         const rcti *rect;
1583         const rctf *rect_fl;
1584         rctf       _rect_fl;
1585         bool select;
1586
1587         /* runtime */
1588         int pass;
1589         bool is_done;
1590         bool is_changed;
1591 } BoxSelectUserData;
1592
1593 static void view3d_userdata_boxselect_init(BoxSelectUserData *r_data,
1594                                            ViewContext *vc, const rcti *rect, const bool select)
1595 {
1596         r_data->vc = vc;
1597
1598         r_data->rect = rect;
1599         r_data->rect_fl = &r_data->_rect_fl;
1600         BLI_rctf_rcti_copy(&r_data->_rect_fl, rect);
1601
1602         r_data->select = select;
1603
1604         /* runtime */
1605         r_data->pass = 0;
1606         r_data->is_done = false;
1607         r_data->is_changed = false;
1608 }
1609
1610 bool edge_inside_circle(const float cent[2], float radius, const float screen_co_a[2], const float screen_co_b[2])
1611 {
1612         const float radius_squared = radius * radius;
1613         return (dist_squared_to_line_segment_v2(cent, screen_co_a, screen_co_b) < radius_squared);
1614 }
1615
1616 static void do_paintvert_box_select__doSelectVert(void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
1617 {
1618         BoxSelectUserData *data = userData;
1619
1620         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1621                 SET_FLAG_FROM_TEST(mv->flag, data->select, SELECT);
1622         }
1623 }
1624 static int do_paintvert_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1625 {
1626         const bool use_zbuf = (vc->v3d->flag & V3D_ZBUF_SELECT) != 0;
1627         Mesh *me;
1628         MVert *mvert;
1629         struct ImBuf *ibuf;
1630         unsigned int *rt;
1631         int a, index;
1632         char *selar;
1633         const int size[2] = {
1634             BLI_rcti_size_x(rect) + 1,
1635             BLI_rcti_size_y(rect) + 1};
1636
1637         me = vc->obact->data;
1638
1639         if ((me == NULL) || (me->totvert == 0) || (size[0] * size[1] <= 0)) {
1640                 return OPERATOR_CANCELLED;
1641         }
1642
1643         if (extend == false && select)
1644                 paintvert_deselect_all_visible(vc->obact, SEL_DESELECT, false);
1645
1646         if (use_zbuf) {
1647                 selar = MEM_callocN(me->totvert + 1, "selar");
1648                 ED_view3d_backbuf_validate(vc);
1649
1650                 ibuf = IMB_allocImBuf(size[0], size[1], 32, IB_rect);
1651                 rt = ibuf->rect;
1652                 glReadPixels(
1653                         rect->xmin + vc->ar->winrct.xmin,
1654                         rect->ymin + vc->ar->winrct.ymin,
1655                         size[0], size[1], GL_RGBA, GL_UNSIGNED_BYTE,  ibuf->rect);
1656                 if (ENDIAN_ORDER == B_ENDIAN) {
1657                         IMB_convert_rgba_to_abgr(ibuf);
1658                 }
1659                 GPU_select_to_index_array(ibuf->rect, size[0] * size[1]);
1660
1661                 a = size[0] * size[1];
1662                 while (a--) {
1663                         if (*rt) {
1664                                 index = *rt;
1665                                 if (index <= me->totvert) {
1666                                         selar[index] = 1;
1667                                 }
1668                         }
1669                         rt++;
1670                 }
1671
1672                 mvert = me->mvert;
1673                 for (a = 1; a <= me->totvert; a++, mvert++) {
1674                         if (selar[a]) {
1675                                 if ((mvert->flag & ME_HIDE) == 0) {
1676                                         if (select) mvert->flag |=  SELECT;
1677                                         else        mvert->flag &= ~SELECT;
1678                                 }
1679                         }
1680                 }
1681
1682                 IMB_freeImBuf(ibuf);
1683                 MEM_freeN(selar);
1684
1685 #ifdef __APPLE__
1686                 glReadBuffer(GL_BACK);
1687 #endif
1688         }
1689         else {
1690                 BoxSelectUserData data;
1691
1692                 view3d_userdata_boxselect_init(&data, vc, rect, select);
1693
1694                 ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d);
1695
1696                 meshobject_foreachScreenVert(vc, do_paintvert_box_select__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1697         }
1698
1699         if (select == false) {
1700                 BKE_mesh_mselect_validate(me);
1701         }
1702         paintvert_flush_flags(vc->obact);
1703
1704         return OPERATOR_FINISHED;
1705 }
1706
1707 static void do_nurbs_box_select__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
1708 {
1709         BoxSelectUserData *data = userData;
1710         Object *obedit = data->vc->obedit;
1711         Curve *cu = (Curve *)obedit->data;
1712
1713         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1714                 if (bp) {
1715                         bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
1716                 }
1717                 else {
1718                         if (cu->drawflag & CU_HIDE_HANDLES) {
1719                                 /* can only be (beztindex == 0) here since handles are hidden */
1720                                 bezt->f1 = bezt->f2 = bezt->f3 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
1721                         }
1722                         else {
1723                                 if (beztindex == 0) {
1724                                         bezt->f1 = data->select ? (bezt->f1 | SELECT) : (bezt->f1 & ~SELECT);
1725                                 }
1726                                 else if (beztindex == 1) {
1727                                         bezt->f2 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
1728                                 }
1729                                 else {
1730                                         bezt->f3 = data->select ? (bezt->f3 | SELECT) : (bezt->f3 & ~SELECT);
1731                                 }
1732                         }
1733                 }
1734         }
1735 }
1736 static int do_nurbs_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1737 {
1738         BoxSelectUserData data;
1739         
1740         view3d_userdata_boxselect_init(&data, vc, rect, select);
1741
1742         if (extend == false && select) {
1743                 Curve *curve = (Curve *) vc->obedit->data;
1744                 ED_curve_deselect_all(curve->editnurb);
1745         }
1746
1747         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
1748         nurbs_foreachScreenVert(vc, do_nurbs_box_select__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1749         BKE_curve_nurb_vert_active_validate(vc->obedit->data);
1750
1751         return OPERATOR_FINISHED;
1752 }
1753
1754 static void do_lattice_box_select__doSelect(void *userData, BPoint *bp, const float screen_co[2])
1755 {
1756         BoxSelectUserData *data = userData;
1757
1758         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1759                 bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
1760         }
1761 }
1762 static int do_lattice_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1763 {
1764         BoxSelectUserData data;
1765
1766         view3d_userdata_boxselect_init(&data, vc, rect, select);
1767
1768         if (extend == false && select)
1769                 ED_lattice_flags_set(vc->obedit, 0);
1770
1771         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
1772         lattice_foreachScreenVert(vc, do_lattice_box_select__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1773         
1774         return OPERATOR_FINISHED;
1775 }
1776
1777 static void do_mesh_box_select__doSelectVert(void *userData, BMVert *eve, const float screen_co[2], int UNUSED(index))
1778 {
1779         BoxSelectUserData *data = userData;
1780
1781         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1782                 BM_vert_select_set(data->vc->em->bm, eve, data->select);
1783         }
1784 }
1785 static void do_mesh_box_select__doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
1786 {
1787         BoxSelectUserData *data = userData;
1788
1789         if (EDBM_backbuf_check(bm_solidoffs + index)) {
1790                 if (data->pass == 0) {
1791                         if (edge_fully_inside_rect(data->rect_fl, screen_co_a, screen_co_b)) {
1792                                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
1793                                 data->is_done = true;
1794                         }
1795                 }
1796                 else {
1797                         if (edge_inside_rect(data->rect_fl, screen_co_a, screen_co_b)) {
1798                                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
1799                         }
1800                 }
1801         }
1802 }
1803 static void do_mesh_box_select__doSelectFace(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
1804 {
1805         BoxSelectUserData *data = userData;
1806
1807         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1808                 BM_face_select_set(data->vc->em->bm, efa, data->select);
1809         }
1810 }
1811 static int do_mesh_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1812 {
1813         BoxSelectUserData data;
1814         ToolSettings *ts = vc->scene->toolsettings;
1815         int bbsel;
1816         
1817         view3d_userdata_boxselect_init(&data, vc, rect, select);
1818
1819         if (extend == false && select)
1820                 EDBM_flag_disable_all(vc->em, BM_ELEM_SELECT);
1821
1822         /* for non zbuf projections, don't change the GL state */
1823         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
1824
1825         glLoadMatrixf(vc->rv3d->viewmat);
1826         bbsel = EDBM_backbuf_border_init(vc, rect->xmin, rect->ymin, rect->xmax, rect->ymax);
1827
1828         if (ts->selectmode & SCE_SELECT_VERTEX) {
1829                 if (bbsel) {
1830                         edbm_backbuf_check_and_select_verts(vc->em, select);
1831                 }
1832                 else {
1833                         mesh_foreachScreenVert(vc, do_mesh_box_select__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1834                 }
1835         }
1836         if (ts->selectmode & SCE_SELECT_EDGE) {
1837                 /* Does both bbsel and non-bbsel versions (need screen cos for both) */
1838
1839                 data.pass = 0;
1840                 mesh_foreachScreenEdge(vc, do_mesh_box_select__doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
1841
1842                 if (data.is_done == 0) {
1843                         data.pass = 1;
1844                         mesh_foreachScreenEdge(vc, do_mesh_box_select__doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
1845                 }
1846         }
1847         
1848         if (ts->selectmode & SCE_SELECT_FACE) {
1849                 if (bbsel) {
1850                         edbm_backbuf_check_and_select_faces(vc->em, select);
1851                 }
1852                 else {
1853                         mesh_foreachScreenFace(vc, do_mesh_box_select__doSelectFace, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1854                 }
1855         }
1856         
1857         EDBM_backbuf_free();
1858                 
1859         EDBM_selectmode_flush(vc->em);
1860         
1861         return OPERATOR_FINISHED;
1862 }
1863
1864 static int do_meta_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1865 {
1866         MetaBall *mb = (MetaBall *)vc->obedit->data;
1867         MetaElem *ml;
1868         int a;
1869
1870         unsigned int buffer[MAXPICKBUF];
1871         int hits;
1872
1873         hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect, VIEW3D_SELECT_ALL);
1874
1875         if (extend == false && select)
1876                 BKE_mball_deselect_all(mb);
1877         
1878         for (ml = mb->editelems->first; ml; ml = ml->next) {
1879                 for (a = 0; a < hits; a++) {
1880                         if (ml->selcol1 == buffer[(4 * a) + 3]) {
1881                                 ml->flag |= MB_SCALE_RAD;
1882                                 if (select) ml->flag |= SELECT;
1883                                 else ml->flag &= ~SELECT;
1884                                 break;
1885                         }
1886                         if (ml->selcol2 == buffer[(4 * a) + 3]) {
1887                                 ml->flag &= ~MB_SCALE_RAD;
1888                                 if (select) ml->flag |= SELECT;
1889                                 else ml->flag &= ~SELECT;
1890                                 break;
1891                         }
1892                 }
1893         }
1894
1895         return OPERATOR_FINISHED;
1896 }
1897
1898 static int do_armature_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1899 {
1900         bArmature *arm = vc->obedit->data;
1901         EditBone *ebone;
1902         int a;
1903
1904         unsigned int buffer[MAXPICKBUF];
1905         int hits;
1906
1907         hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect, VIEW3D_SELECT_ALL);
1908         
1909         /* clear flag we use to detect point was affected */
1910         for (ebone = arm->edbo->first; ebone; ebone = ebone->next)
1911                 ebone->flag &= ~BONE_DONE;
1912         
1913         if (extend == false && select)
1914                 ED_armature_deselect_all_visible(vc->obedit);
1915
1916         /* first we only check points inside the border */
1917         for (a = 0; a < hits; a++) {
1918                 int index = buffer[(4 * a) + 3];
1919                 if (index != -1) {
1920                         ebone = BLI_findlink(arm->edbo, index & ~(BONESEL_ANY));
1921                         if ((index & 0xFFFF0000) == 0) {
1922                                 continue;
1923                         }
1924                         if ((select == false) || ((ebone->flag & BONE_UNSELECTABLE) == 0)) {
1925                                 if (index & BONESEL_TIP) {
1926                                         ebone->flag |= BONE_DONE;
1927                                         if (select) ebone->flag |= BONE_TIPSEL;
1928                                         else ebone->flag &= ~BONE_TIPSEL;
1929                                 }
1930                                 
1931                                 if (index & BONESEL_ROOT) {
1932                                         ebone->flag |= BONE_DONE;
1933                                         if (select) ebone->flag |= BONE_ROOTSEL;
1934                                         else ebone->flag &= ~BONE_ROOTSEL;
1935                                 }
1936                         }
1937                 }
1938         }
1939         
1940         /* now we have to flush tag from parents... */
1941         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1942                 if (ebone->parent && (ebone->flag & BONE_CONNECTED)) {
1943                         if (ebone->parent->flag & BONE_DONE)
1944                                 ebone->flag |= BONE_DONE;
1945                 }
1946         }
1947         
1948         /* only select/deselect entire bones when no points where in the rect */
1949         for (a = 0; a < hits; a++) {
1950                 int index = buffer[(4 * a) + 3];
1951                 if (index != -1) {
1952                         ebone = BLI_findlink(arm->edbo, index & ~(BONESEL_ANY));
1953                         if (index & BONESEL_BONE) {
1954                                 if ((select == false) || ((ebone->flag & BONE_UNSELECTABLE) == 0)) {
1955                                         if (!(ebone->flag & BONE_DONE)) {
1956                                                 if (select)
1957                                                         ebone->flag |= (BONE_ROOTSEL | BONE_TIPSEL | BONE_SELECTED);
1958                                                 else
1959                                                         ebone->flag &= ~(BONE_ROOTSEL | BONE_TIPSEL | BONE_SELECTED);
1960                                         }
1961                                 }
1962                         }
1963                 }
1964         }
1965         
1966         ED_armature_sync_selection(arm->edbo);
1967         
1968         return hits > 0 ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
1969 }
1970
1971 static int do_object_pose_box_select(bContext *C, ViewContext *vc, rcti *rect, bool select, bool extend)
1972 {
1973         Bone *bone;
1974         Object *ob = vc->obact;
1975         unsigned int *vbuffer = NULL; /* selection buffer       */
1976         unsigned int *col;          /* color in buffer  */
1977         int bone_only;
1978         int bone_selected = 0;
1979         int totobj = MAXPICKBUF; /* XXX solve later */
1980         int hits;
1981         
1982         if ((ob) && (ob->mode & OB_MODE_POSE))
1983                 bone_only = 1;
1984         else
1985                 bone_only = 0;
1986         
1987         if (extend == false && select) {
1988                 if (bone_only) {
1989                         CTX_DATA_BEGIN (C, bPoseChannel *, pchan, visible_pose_bones)
1990                         {
1991                                 if ((select == false) || ((pchan->bone->flag & BONE_UNSELECTABLE) == 0)) {
1992                                         pchan->bone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1993                                 }
1994                         }
1995                         CTX_DATA_END;
1996                 }
1997                 else {
1998                         object_deselect_all_visible(vc->scene, vc->v3d);
1999                 }
2000         }
2001
2002         /* selection buffer now has bones potentially too, so we add MAXPICKBUF */
2003         vbuffer = MEM_mallocN(4 * (totobj + MAXPICKELEMS) * sizeof(unsigned int), "selection buffer");
2004         hits = view3d_opengl_select(vc, vbuffer, 4 * (totobj + MAXPICKELEMS), rect, VIEW3D_SELECT_ALL);
2005         /*
2006          * LOGIC NOTES (theeth):
2007          * The buffer and ListBase have the same relative order, which makes the selection
2008          * very simple. Loop through both data sets at the same time, if the color
2009          * is the same as the object, we have a hit and can move to the next color
2010          * and object pair, if not, just move to the next object,
2011          * keeping the same color until we have a hit.
2012          * 
2013          * The buffer order is defined by OGL standard, hopefully no stupid GFX card
2014          * does it incorrectly.
2015          */
2016
2017         if (hits > 0) { /* no need to loop if there's no hit */
2018                 Base *base;
2019                 col = vbuffer + 3;
2020                 
2021                 for (base = vc->scene->base.first; base && hits; base = base->next) {
2022                         if (BASE_SELECTABLE(vc->v3d, base)) {
2023                                 while (base->selcol == (*col & 0xFFFF)) {   /* we got an object */
2024                                         if (*col & 0xFFFF0000) {                    /* we got a bone */
2025                                                 bone = get_indexed_bone(base->object, *col & ~(BONESEL_ANY));
2026                                                 if (bone) {
2027                                                         if (select) {
2028                                                                 if ((bone->flag & BONE_UNSELECTABLE) == 0) {
2029                                                                         bone->flag |= BONE_SELECTED;
2030                                                                         bone_selected = 1;
2031                                                                 }
2032                                                         }
2033                                                         else {
2034                                                                 bArmature *arm = base->object->data;
2035                                                                 bone->flag &= ~BONE_SELECTED;
2036                                                                 if (arm->act_bone == bone)
2037                                                                         arm->act_bone = NULL;
2038                                                         }
2039                                                 }
2040                                         }
2041                                         else if (!bone_only) {
2042                                                 ED_base_object_select(base, select ? BA_SELECT : BA_DESELECT);
2043                                         }
2044                                         
2045                                         col += 4; /* next color */
2046                                         hits--;
2047                                         if (hits == 0) break;
2048                                 }
2049                         }
2050                         
2051                         if (bone_selected) {
2052                                 if (base->object && (base->object->type == OB_ARMATURE)) {
2053                                         bArmature *arm = base->object->data;
2054                                         
2055                                         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, base->object);
2056                                         
2057                                         if (arm && (arm->flag & ARM_HAS_VIZ_DEPS)) {
2058                                                 /* mask modifier ('armature' mode), etc. */
2059                                                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2060                                         }
2061                                 }
2062                         }
2063                 }
2064                 
2065                 WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, vc->scene);
2066         }
2067         MEM_freeN(vbuffer);
2068
2069         return hits > 0 ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
2070 }
2071
2072 static int view3d_borderselect_exec(bContext *C, wmOperator *op)
2073 {
2074         ViewContext vc;
2075         rcti rect;
2076         bool extend;
2077         bool select;
2078
2079         int ret = OPERATOR_CANCELLED;
2080
2081         view3d_operator_needs_opengl(C);
2082
2083         /* setup view context for argument to callbacks */
2084         ED_view3d_viewcontext_init(C, &vc);
2085         
2086         select = !RNA_boolean_get(op->ptr, "deselect");
2087         extend = RNA_boolean_get(op->ptr, "extend");
2088         WM_operator_properties_border_to_rcti(op, &rect);
2089
2090         if (vc.obedit) {
2091                 switch (vc.obedit->type) {
2092                         case OB_MESH:
2093                                 vc.em = BKE_editmesh_from_object(vc.obedit);
2094                                 ret = do_mesh_box_select(&vc, &rect, select, extend);
2095 //                      if (EM_texFaceCheck())
2096                                 if (ret & OPERATOR_FINISHED) {
2097                                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
2098                                 }
2099                                 break;
2100                         case OB_CURVE:
2101                         case OB_SURF:
2102                                 ret = do_nurbs_box_select(&vc, &rect, select, extend);
2103                                 if (ret & OPERATOR_FINISHED) {
2104                                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
2105                                 }
2106                                 break;
2107                         case OB_MBALL:
2108                                 ret = do_meta_box_select(&vc, &rect, select, extend);
2109                                 if (ret & OPERATOR_FINISHED) {
2110                                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
2111                                 }
2112                                 break;
2113                         case OB_ARMATURE:
2114                                 ret = do_armature_box_select(&vc, &rect, select, extend);
2115                                 if (ret & OPERATOR_FINISHED) {
2116                                         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, vc.obedit);
2117                                 }
2118                                 break;
2119                         case OB_LATTICE:
2120                                 ret = do_lattice_box_select(&vc, &rect, select, extend);
2121                                 if (ret & OPERATOR_FINISHED) {
2122                                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
2123                                 }
2124                                 break;
2125                         default:
2126                                 assert(!"border select on incorrect object type");
2127                                 break;
2128                 }
2129         }
2130         else {  /* no editmode, unified for bones and objects */
2131                 if (vc.obact && vc.obact->mode & OB_MODE_SCULPT) {
2132                         ret = ED_sculpt_mask_box_select(C, &vc, &rect, select, extend);
2133                 }
2134                 else if (vc.obact && BKE_paint_select_face_test(vc.obact)) {
2135                         ret = do_paintface_box_select(&vc, &rect, select, extend);
2136                 }
2137                 else if (vc.obact && BKE_paint_select_vert_test(vc.obact)) {
2138                         ret = do_paintvert_box_select(&vc, &rect, select, extend);
2139                 }
2140                 else if (vc.obact && vc.obact->mode & OB_MODE_PARTICLE_EDIT) {
2141                         ret = PE_border_select(C, &rect, select, extend);
2142                 }
2143                 else { /* object mode with none active */
2144                         ret = do_object_pose_box_select(C, &vc, &rect, select, extend);
2145                 }
2146         }
2147
2148         return ret;
2149
2150
2151
2152 /* *****************Selection Operators******************* */
2153
2154 /* ****** Border Select ****** */
2155 void VIEW3D_OT_select_border(wmOperatorType *ot)
2156 {
2157         /* identifiers */
2158         ot->name = "Border Select";
2159         ot->description = "Select items using border selection";
2160         ot->idname = "VIEW3D_OT_select_border";
2161         
2162         /* api callbacks */
2163         ot->invoke = WM_gesture_border_invoke;
2164         ot->exec = view3d_borderselect_exec;
2165         ot->modal = WM_gesture_border_modal;
2166         ot->poll = view3d_selectable_data;
2167         ot->cancel = WM_gesture_border_cancel;
2168         
2169         /* flags */
2170         ot->flag = OPTYPE_UNDO;
2171         
2172         /* rna */
2173         WM_operator_properties_gesture_border_select(ot);
2174 }
2175
2176
2177 /* mouse selection in weight paint */
2178 /* gets called via generic mouse select operator */
2179 static bool ed_wpaint_vertex_select_pick(
2180         bContext *C, const int mval[2],
2181         bool extend, bool deselect, bool toggle, Object *obact)
2182 {
2183         View3D *v3d = CTX_wm_view3d(C);
2184         const bool use_zbuf = (v3d->flag & V3D_ZBUF_SELECT) != 0;
2185
2186         Mesh *me = obact->data; /* already checked for NULL */
2187         unsigned int index = 0;
2188         MVert *mv;
2189
2190         if (ED_mesh_pick_vert(C, obact, mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, use_zbuf)) {
2191                 mv = &me->mvert[index];
2192                 if (extend) {
2193                         mv->flag |= SELECT;
2194                 }
2195                 else if (deselect) {
2196                         mv->flag &= ~SELECT;
2197                 }
2198                 else if (toggle) {
2199                         mv->flag ^= SELECT;
2200                 }
2201                 else {
2202                         paintvert_deselect_all_visible(obact, SEL_DESELECT, false);
2203                         mv->flag |= SELECT;
2204                 }
2205
2206                 /* update mselect */
2207                 if (mv->flag & SELECT) {
2208                         BKE_mesh_mselect_active_set(me, index, ME_VSEL);
2209                 }
2210                 else {
2211                         BKE_mesh_mselect_validate(me);
2212                 }
2213
2214                 paintvert_flush_flags(obact);
2215                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data);
2216                 return true;
2217         }
2218         return false;
2219 }
2220
2221 /* ****** Mouse Select ****** */
2222
2223
2224 static int view3d_select_exec(bContext *C, wmOperator *op)
2225 {
2226         Object *obedit = CTX_data_edit_object(C);
2227         Object *obact = CTX_data_active_object(C);
2228         bool extend = RNA_boolean_get(op->ptr, "extend");
2229         bool deselect = RNA_boolean_get(op->ptr, "deselect");
2230         bool toggle = RNA_boolean_get(op->ptr, "toggle");
2231         bool center = RNA_boolean_get(op->ptr, "center");
2232         bool enumerate = RNA_boolean_get(op->ptr, "enumerate");
2233         /* only force object select for editmode to support vertex parenting,
2234          * or paint-select to allow pose bone select with vert/face select */
2235         bool object = (RNA_boolean_get(op->ptr, "object") &&
2236                        (obedit ||
2237                         BKE_paint_select_elem_test(obact) ||
2238                         /* so its possible to select bones in weightpaint mode (LMB select) */
2239                         (obact && (obact->mode & OB_MODE_WEIGHT_PAINT) && BKE_object_pose_armature_get(obact))));
2240
2241         bool retval = false;
2242         int location[2];
2243
2244         RNA_int_get_array(op->ptr, "location", location);
2245
2246         view3d_operator_needs_opengl(C);
2247
2248         if (object) {
2249                 obedit = NULL;
2250                 obact = NULL;
2251
2252                 /* ack, this is incorrect but to do this correctly we would need an
2253                  * alternative editmode/objectmode keymap, this copies the functionality
2254                  * from 2.4x where Ctrl+Select in editmode does object select only */
2255                 center = false;
2256         }
2257
2258         if (obedit && object == false) {
2259                 if (obedit->type == OB_MESH)
2260                         retval = EDBM_select_pick(C, location, extend, deselect, toggle);
2261                 else if (obedit->type == OB_ARMATURE)
2262                         retval = ED_armature_select_pick(C, location, extend, deselect, toggle);
2263                 else if (obedit->type == OB_LATTICE)
2264                         retval = ED_lattice_select_pick(C, location, extend, deselect, toggle);
2265                 else if (ELEM(obedit->type, OB_CURVE, OB_SURF))
2266                         retval = ED_curve_editnurb_select_pick(C, location, extend, deselect, toggle);
2267                 else if (obedit->type == OB_MBALL)
2268                         retval = ED_mball_select_pick(C, location, extend, deselect, toggle);
2269                 else if (obedit->type == OB_FONT)
2270                         retval = ED_curve_editfont_select_pick(C, location, extend, deselect, toggle);
2271                         
2272         }
2273         else if (obact && obact->mode & OB_MODE_PARTICLE_EDIT)
2274                 return PE_mouse_particles(C, location, extend, deselect, toggle);
2275         else if (obact && BKE_paint_select_face_test(obact))
2276                 retval = paintface_mouse_select(C, obact, location, extend, deselect, toggle);
2277         else if (BKE_paint_select_vert_test(obact))
2278                 retval = ed_wpaint_vertex_select_pick(C, location, extend, deselect, toggle, obact);
2279         else
2280                 retval = ed_object_select_pick(C, location, extend, deselect, toggle, center, enumerate, object);
2281
2282         /* passthrough allows tweaks
2283          * FINISHED to signal one operator worked
2284          * */
2285         if (retval)
2286                 return OPERATOR_PASS_THROUGH | OPERATOR_FINISHED;
2287         else
2288                 return OPERATOR_PASS_THROUGH;  /* nothing selected, just passthrough */
2289 }
2290
2291 static int view3d_select_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2292 {
2293         RNA_int_set_array(op->ptr, "location", event->mval);
2294
2295         return view3d_select_exec(C, op);
2296 }
2297
2298 void VIEW3D_OT_select(wmOperatorType *ot)
2299 {
2300         PropertyRNA *prop;
2301
2302         /* identifiers */
2303         ot->name = "Activate/Select";
2304         ot->description = "Activate/select item(s)";
2305         ot->idname = "VIEW3D_OT_select";
2306         
2307         /* api callbacks */
2308         ot->invoke = view3d_select_invoke;
2309         ot->exec = view3d_select_exec;
2310         ot->poll = ED_operator_view3d_active;
2311         
2312         /* flags */
2313         ot->flag = OPTYPE_UNDO;
2314         
2315         /* properties */
2316         WM_operator_properties_mouse_select(ot);
2317
2318         RNA_def_boolean(ot->srna, "center", 0, "Center", "Use the object center when selecting, in editmode used to extend object selection");
2319         RNA_def_boolean(ot->srna, "enumerate", 0, "Enumerate", "List objects under the mouse (object mode only)");
2320         RNA_def_boolean(ot->srna, "object", 0, "Object", "Use object selection (editmode only)");
2321
2322         prop = RNA_def_int_vector(ot->srna, "location", 2, NULL, INT_MIN, INT_MAX, "Location", "Mouse location", INT_MIN, INT_MAX);
2323         RNA_def_property_flag(prop, PROP_HIDDEN);
2324 }
2325
2326
2327 /* -------------------- circle select --------------------------------------------- */
2328
2329 typedef struct CircleSelectUserData {
2330         ViewContext *vc;
2331         bool select;
2332         int   mval[2];
2333         float mval_fl[2];
2334         float radius;
2335         float radius_squared;
2336
2337         /* runtime */
2338         bool is_changed;
2339 } CircleSelectUserData;
2340
2341 static void view3d_userdata_circleselect_init(CircleSelectUserData *r_data,
2342                                               ViewContext *vc, const bool select, const int mval[2], const float rad)
2343 {
2344         r_data->vc = vc;
2345         r_data->select = select;
2346         copy_v2_v2_int(r_data->mval, mval);
2347         r_data->mval_fl[0] = mval[0];
2348         r_data->mval_fl[1] = mval[1];
2349
2350         r_data->radius = rad;
2351         r_data->radius_squared = rad * rad;
2352
2353         /* runtime */
2354         r_data->is_changed = false;
2355 }
2356
2357 static void mesh_circle_doSelectVert(void *userData, BMVert *eve, const float screen_co[2], int UNUSED(index))
2358 {
2359         CircleSelectUserData *data = userData;
2360
2361         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2362                 BM_vert_select_set(data->vc->em->bm, eve, data->select);
2363         }
2364 }
2365 static void mesh_circle_doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int UNUSED(index))
2366 {
2367         CircleSelectUserData *data = userData;
2368
2369         if (edge_inside_circle(data->mval_fl, data->radius, screen_co_a, screen_co_b)) {
2370                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
2371         }
2372 }
2373 static void mesh_circle_doSelectFace(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
2374 {
2375         CircleSelectUserData *data = userData;
2376
2377         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2378                 BM_face_select_set(data->vc->em->bm, efa, data->select);
2379         }
2380 }
2381
2382 static void mesh_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2383 {
2384         ToolSettings *ts = vc->scene->toolsettings;
2385         int bbsel;
2386         CircleSelectUserData data;
2387         
2388         bbsel = EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
2389         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
2390
2391         vc->em = BKE_editmesh_from_object(vc->obedit);
2392
2393         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2394
2395         if (ts->selectmode & SCE_SELECT_VERTEX) {
2396                 if (bbsel) {
2397                         edbm_backbuf_check_and_select_verts(vc->em, select);
2398                 }
2399                 else {
2400                         mesh_foreachScreenVert(vc, mesh_circle_doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2401                 }
2402         }
2403
2404         if (ts->selectmode & SCE_SELECT_EDGE) {
2405                 if (bbsel) {
2406                         edbm_backbuf_check_and_select_edges(vc->em, select);
2407                 }
2408                 else {
2409                         mesh_foreachScreenEdge(vc, mesh_circle_doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
2410                 }
2411         }
2412         
2413         if (ts->selectmode & SCE_SELECT_FACE) {
2414                 if (bbsel) {
2415                         edbm_backbuf_check_and_select_faces(vc->em, select);
2416                 }
2417                 else {
2418                         mesh_foreachScreenFace(vc, mesh_circle_doSelectFace, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2419                 }
2420         }
2421
2422         EDBM_backbuf_free();
2423         EDBM_selectmode_flush(vc->em);
2424 }
2425
2426 static void paint_facesel_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2427 {
2428         Object *ob = vc->obact;
2429         Mesh *me = ob->data;
2430         bool bbsel;
2431
2432         bm_vertoffs = me->totpoly + 1; /* max index array */
2433
2434         bbsel = EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
2435         if (bbsel) {
2436                 edbm_backbuf_check_and_select_tfaces(me, select);
2437                 EDBM_backbuf_free();
2438                 paintface_flush_flags(ob, SELECT);
2439         }
2440 }
2441
2442 static void paint_vertsel_circle_select_doSelectVert(void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
2443 {
2444         CircleSelectUserData *data = userData;
2445
2446         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2447                 SET_FLAG_FROM_TEST(mv->flag, data->select, SELECT);
2448         }
2449 }
2450 static void paint_vertsel_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2451 {
2452         const bool use_zbuf = (vc->v3d->flag & V3D_ZBUF_SELECT) != 0;
2453         Object *ob = vc->obact;
2454         Mesh *me = ob->data;
2455         bool bbsel;
2456         /* CircleSelectUserData data = {NULL}; */ /* UNUSED */
2457
2458         if (use_zbuf) {
2459                 bm_vertoffs = me->totvert + 1; /* max index array */
2460
2461                 bbsel = EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
2462                 if (bbsel) {
2463                         edbm_backbuf_check_and_select_verts_obmode(me, select);
2464                         EDBM_backbuf_free();
2465                 }
2466         }
2467         else {
2468                 CircleSelectUserData data;
2469
2470                 ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d); /* for foreach's screen/vert projection */
2471
2472                 view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2473                 meshobject_foreachScreenVert(vc, paint_vertsel_circle_select_doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2474         }
2475
2476         if (select != LEFTMOUSE) {
2477                 BKE_mesh_mselect_validate(me);
2478         }
2479         paintvert_flush_flags(ob);
2480 }
2481
2482
2483 static void nurbscurve_circle_doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
2484 {
2485         CircleSelectUserData *data = userData;
2486         Object *obedit = data->vc->obedit;
2487         Curve *cu = (Curve *)obedit->data;
2488
2489         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2490                 if (bp) {
2491                         bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
2492                 }
2493                 else {
2494                         if (cu->drawflag & CU_HIDE_HANDLES) {
2495                                 /* can only be (beztindex == 0) here since handles are hidden */
2496                                 bezt->f1 = bezt->f2 = bezt->f3 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
2497                         }
2498                         else {
2499                                 if (beztindex == 0) {
2500                                         bezt->f1 = data->select ? (bezt->f1 | SELECT) : (bezt->f1 & ~SELECT);
2501                                 }
2502                                 else if (beztindex == 1) {
2503                                         bezt->f2 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
2504                                 }
2505                                 else {
2506                                         bezt->f3 = data->select ? (bezt->f3 | SELECT) : (bezt->f3 & ~SELECT);
2507                                 }
2508                         }
2509                 }
2510         }
2511 }
2512 static void nurbscurve_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2513 {
2514         CircleSelectUserData data;
2515
2516         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2517
2518         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
2519         nurbs_foreachScreenVert(vc, nurbscurve_circle_doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2520         BKE_curve_nurb_vert_active_validate(vc->obedit->data);
2521 }
2522
2523
2524 static void latticecurve_circle_doSelect(void *userData, BPoint *bp, const float screen_co[2])
2525 {
2526         CircleSelectUserData *data = userData;
2527
2528         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2529                 bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
2530         }
2531 }
2532 static void lattice_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2533 {
2534         CircleSelectUserData data;
2535
2536         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2537
2538         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
2539         lattice_foreachScreenVert(vc, latticecurve_circle_doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2540 }
2541
2542
2543 /* NOTE: pose-bone case is copied from editbone case... */
2544 static bool pchan_circle_doSelectJoint(void *userData, bPoseChannel *pchan, const float screen_co[2])
2545 {
2546         CircleSelectUserData *data = userData;
2547
2548         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2549                 if (data->select)
2550                         pchan->bone->flag |= BONE_SELECTED;
2551                 else
2552                         pchan->bone->flag &= ~BONE_SELECTED;
2553                 return 1;
2554         }
2555         return 0;
2556 }
2557 static void do_circle_select_pose__doSelectBone(void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
2558 {
2559         CircleSelectUserData *data = userData;
2560         bArmature *arm = data->vc->obact->data;
2561
2562         if (PBONE_SELECTABLE(arm, pchan->bone)) {
2563                 bool is_point_done = false;
2564                 int points_proj_tot = 0;
2565
2566                 /* project head location to screenspace */
2567                 if (screen_co_a[0] != IS_CLIPPED) {
2568                         points_proj_tot++;
2569                         if (pchan_circle_doSelectJoint(data, pchan, screen_co_a)) {
2570                                 is_point_done = true;
2571                         }
2572                 }
2573
2574                 /* project tail location to screenspace */
2575                 if (screen_co_b[0] != IS_CLIPPED) {
2576                         points_proj_tot++;
2577                         if (pchan_circle_doSelectJoint(data, pchan, screen_co_b)) {
2578                                 is_point_done = true;
2579                         }
2580                 }
2581
2582                 /* check if the head and/or tail is in the circle
2583                  * - the call to check also does the selection already
2584                  */
2585
2586                 /* only if the endpoints didn't get selected, deal with the middle of the bone too
2587                  * It works nicer to only do this if the head or tail are not in the circle,
2588                  * otherwise there is no way to circle select joints alone */
2589                 if ((is_point_done == false) && (points_proj_tot == 2) &&
2590                     edge_inside_circle(data->mval_fl, data->radius, screen_co_a, screen_co_b))
2591                 {
2592                         if (data->select) pchan->bone->flag |= BONE_SELECTED;
2593                         else              pchan->bone->flag &= ~BONE_SELECTED;
2594                         data->is_changed = true;
2595                 }
2596
2597                 data->is_changed |= is_point_done;
2598         }
2599 }
2600 static void pose_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2601 {
2602         CircleSelectUserData data;
2603         
2604         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2605
2606         ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d); /* for foreach's screen/vert projection */
2607         
2608         pose_foreachScreenBone(vc, do_circle_select_pose__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2609
2610         if (data.is_changed) {
2611                 bArmature *arm = vc->obact->data;
2612
2613                 WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obact);
2614
2615                 if (arm->flag & ARM_HAS_VIZ_DEPS) {
2616                         /* mask modifier ('armature' mode), etc. */
2617                         DAG_id_tag_update(&vc->obact->id, OB_RECALC_DATA);
2618                 }
2619         }
2620 }
2621
2622 static bool armature_circle_doSelectJoint(void *userData, EditBone *ebone, const float screen_co[2], bool head)
2623 {
2624         CircleSelectUserData *data = userData;
2625
2626         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2627                 if (head) {
2628                         if (data->select)
2629                                 ebone->flag |= BONE_ROOTSEL;
2630                         else 
2631                                 ebone->flag &= ~BONE_ROOTSEL;
2632                 }
2633                 else {
2634                         if (data->select)
2635                                 ebone->flag |= BONE_TIPSEL;
2636                         else 
2637                                 ebone->flag &= ~BONE_TIPSEL;
2638                 }
2639                 return 1;
2640         }
2641         return 0;
2642 }
2643 static void do_circle_select_armature__doSelectBone(void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
2644 {
2645         CircleSelectUserData *data = userData;
2646         bArmature *arm = data->vc->obedit->data;
2647
2648         if (data->select ? EBONE_SELECTABLE(arm, ebone) : EBONE_VISIBLE(arm, ebone)) {
2649                 bool is_point_done = false;
2650                 int points_proj_tot = 0;
2651
2652                 /* project head location to screenspace */
2653                 if (screen_co_a[0] != IS_CLIPPED) {
2654                         points_proj_tot++;
2655                         if (armature_circle_doSelectJoint(data, ebone, screen_co_a, true)) {
2656                                 is_point_done = true;
2657                         }
2658                 }
2659
2660                 /* project tail location to screenspace */
2661                 if (screen_co_b[0] != IS_CLIPPED) {
2662                         points_proj_tot++;
2663                         if (armature_circle_doSelectJoint(data, ebone, screen_co_b, false)) {
2664                                 is_point_done = true;
2665                         }
2666                 }
2667
2668                 /* check if the head and/or tail is in the circle
2669                  * - the call to check also does the selection already
2670                  */
2671
2672                 /* only if the endpoints didn't get selected, deal with the middle of the bone too
2673                  * It works nicer to only do this if the head or tail are not in the circle,
2674                  * otherwise there is no way to circle select joints alone */
2675                 if ((is_point_done == false) && (points_proj_tot == 2) &&
2676                     edge_inside_circle(data->mval_fl, data->radius, screen_co_a, screen_co_b))
2677                 {
2678                         if (data->select) ebone->flag |=  (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
2679                         else              ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
2680                         data->is_changed = true;
2681                 }
2682
2683                 data->is_changed |= is_point_done;
2684         }
2685 }
2686 static void armature_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2687 {
2688         CircleSelectUserData data;
2689         bArmature *arm = vc->obedit->data;
2690
2691         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2692
2693         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
2694
2695         armature_foreachScreenBone(vc, do_circle_select_armature__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2696
2697         if (data.is_changed) {
2698                 ED_armature_sync_selection(arm->edbo);
2699                 ED_armature_validate_active(arm);
2700                 WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obedit);
2701         }
2702 }
2703
2704 static void do_circle_select_mball__doSelectElem(void *userData, struct MetaElem *ml, const float screen_co[2])
2705 {
2706         CircleSelectUserData *data = userData;
2707
2708         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2709                 if (data->select) ml->flag |=  SELECT;
2710                 else              ml->flag &= ~SELECT;
2711                 data->is_changed = true;
2712         }
2713 }
2714 static void mball_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2715 {
2716         CircleSelectUserData data;
2717
2718         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2719
2720         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
2721
2722         mball_foreachScreenElem(vc, do_circle_select_mball__doSelectElem, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2723 }
2724
2725 /** Callbacks for circle selection in Editmode */
2726
2727 static void obedit_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2728 {
2729         switch (vc->obedit->type) {
2730                 case OB_MESH:
2731                         mesh_circle_select(vc, select, mval, rad);
2732                         break;
2733                 case OB_CURVE:
2734                 case OB_SURF:
2735                         nurbscurve_circle_select(vc, select, mval, rad);
2736                         break;
2737                 case OB_LATTICE:
2738                         lattice_circle_select(vc, select, mval, rad);
2739                         break;
2740                 case OB_ARMATURE:
2741                         armature_circle_select(vc, select, mval, rad);
2742                         break;
2743                 case OB_MBALL:
2744                         mball_circle_select(vc, select, mval, rad);
2745                         break;
2746                 default:
2747                         return;
2748         }
2749 }
2750
2751 static bool object_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2752 {
2753         Scene *scene = vc->scene;
2754         const float radius_squared = rad * rad;
2755         const float mval_fl[2] = {mval[0], mval[1]};
2756         bool changed = false;
2757         const int select_flag = select ? SELECT : 0;
2758
2759
2760         Base *base;
2761         for (base = FIRSTBASE; base; base = base->next) {
2762                 if (BASE_SELECTABLE(vc->v3d, base) && ((base->flag & SELECT) != select_flag)) {
2763                         float screen_co[2];
2764                         if (ED_view3d_project_float_global(vc->ar, base->object->obmat[3], screen_co,
2765                                                            V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
2766                         {
2767                                 if (len_squared_v2v2(mval_fl, screen_co) <= radius_squared) {
2768                                         ED_base_object_select(base, select ? BA_SELECT : BA_DESELECT);
2769                                         changed = true;
2770                                 }
2771                         }
2772                 }
2773         }
2774
2775         return changed;
2776 }
2777
2778 /* not a real operator, only for circle test */
2779 static int view3d_circle_select_exec(bContext *C, wmOperator *op)
2780 {
2781         ViewContext vc;
2782         ED_view3d_viewcontext_init(C, &vc);
2783         Object *obact = vc.obact;
2784         Object *obedit = vc.obedit;
2785         const int radius = RNA_int_get(op->ptr, "radius");
2786         const bool select = !RNA_boolean_get(op->ptr, "deselect");
2787         const int mval[2] = {RNA_int_get(op->ptr, "x"),
2788                              RNA_int_get(op->ptr, "y")};
2789
2790         if (obedit || BKE_paint_select_elem_test(obact) ||
2791             (obact && (obact->mode & (OB_MODE_PARTICLE_EDIT | OB_MODE_POSE))) )
2792         {
2793                 view3d_operator_needs_opengl(C);
2794
2795                 if (CTX_data_edit_object(C)) {
2796                         obedit_circle_select(&vc, select, mval, (float)radius);
2797                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data);
2798                 }
2799                 else if (BKE_paint_select_face_test(obact)) {
2800                         paint_facesel_circle_select(&vc, select, mval, (float)radius);
2801                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data);
2802                 }
2803                 else if (BKE_paint_select_vert_test(obact)) {
2804                         paint_vertsel_circle_select(&vc, select, mval, (float)radius);
2805                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data);
2806                 }
2807                 else if (obact->mode & OB_MODE_POSE) {
2808                         pose_circle_select(&vc, select, mval, (float)radius);
2809                 }
2810                 else {
2811                         return PE_circle_select(C, select, mval, (float)radius);
2812                 }
2813         }
2814         else if (obact && obact->mode & OB_MODE_SCULPT) {
2815                 return OPERATOR_CANCELLED;
2816         }
2817         else {
2818                 if (object_circle_select(&vc, select, mval, (float)radius)) {
2819                         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, vc.scene);
2820                 }
2821         }
2822
2823         return OPERATOR_FINISHED;
2824 }
2825
2826 void VIEW3D_OT_select_circle(wmOperatorType *ot)
2827 {
2828         ot->name = "Circle Select";
2829         ot->description = "Select items using circle selection";
2830         ot->idname = "VIEW3D_OT_select_circle";
2831         
2832         ot->invoke = WM_gesture_circle_invoke;
2833         ot->modal = WM_gesture_circle_modal;
2834         ot->exec = view3d_circle_select_exec;
2835         ot->poll = view3d_selectable_data;
2836         ot->cancel = WM_gesture_circle_cancel;
2837         
2838         /* flags */
2839         ot->flag = OPTYPE_UNDO;
2840
2841         /* properties */
2842         WM_operator_properties_gesture_circle_select(ot);
2843 }