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