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