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