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