Merge commit 'origin/master (9395646c2c44cdf568ca950700d71fe966f2d80f)' into blender2.8
[blender.git] / source / blender / editors / space_view3d / view3d_draw.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_draw.c
28  *  \ingroup spview3d
29  */
30
31 #include <math.h>
32
33 #include "BIF_gl.h"
34 #include "BIF_glutil.h"
35
36 #include "BKE_camera.h"
37 #include "BKE_context.h"
38 #include "BKE_global.h"
39 #include "BKE_key.h"
40 #include "BKE_scene.h"
41 #include "BKE_object.h"
42 #include "BKE_paint.h"
43 #include "BKE_unit.h"
44
45 #include "BLF_api.h"
46
47 #include "BLI_listbase.h"
48 #include "BLI_math.h"
49 #include "BLI_rect.h"
50 #include "BLI_string.h"
51 #include "BLI_threads.h"
52 #include "BLI_jitter.h"
53
54 #include "BLT_translation.h"
55
56 #include "DNA_armature_types.h"
57 #include "DNA_brush_types.h"
58 #include "DNA_camera_types.h"
59 #include "DNA_key_types.h"
60 #include "DNA_mesh_types.h"
61 #include "DNA_object_types.h"
62 #include "DNA_view3d_types.h"
63 #include "DNA_windowmanager_types.h"
64
65 #include "DRW_engine.h"
66
67 #include "ED_keyframing.h"
68 #include "ED_armature.h"
69 #include "ED_keyframing.h"
70 #include "ED_gpencil.h"
71 #include "ED_screen.h"
72 #include "ED_transform.h"
73 #include "ED_gpencil.h"
74
75 #include "DEG_depsgraph_query.h"
76
77 #include "GPU_draw.h"
78 #include "GPU_matrix.h"
79 #include "GPU_immediate.h"
80 #include "GPU_immediate_util.h"
81 #include "GPU_material.h"
82 #include "GPU_viewport.h"
83 #include "GPU_compositing.h"
84
85 #include "MEM_guardedalloc.h"
86
87 #include "UI_interface.h"
88 #include "UI_resources.h"
89
90 #include "RE_engine.h"
91
92 #include "WM_api.h"
93 #include "WM_types.h"
94
95 #include "IMB_imbuf.h"
96 #include "IMB_imbuf_types.h"
97
98 #include "view3d_intern.h"  /* own include */
99
100 /* prototypes */
101 static void draw_all_objects(const bContext *C, ARegion *ar, const bool only_depth, const bool use_depth);
102
103 typedef struct DrawData {
104         rcti border_rect;
105         bool render_border;
106         bool clip_border;
107         bool is_render;
108         GPUViewport *viewport;
109 } DrawData;
110
111 static void view3d_draw_data_init(const bContext *C, ARegion *ar, RegionView3D *rv3d, DrawData *draw_data)
112 {
113         Scene *scene = CTX_data_scene(C);
114         View3D *v3d = CTX_wm_view3d(C);
115
116         draw_data->is_render = (v3d->drawtype == OB_RENDER);
117
118         draw_data->render_border = ED_view3d_calc_render_border(scene, v3d, ar, &draw_data->border_rect);
119         draw_data->clip_border = (draw_data->render_border && !BLI_rcti_compare(&ar->drawrct, &draw_data->border_rect));
120
121         draw_data->viewport = rv3d->viewport;
122 }
123
124 /* ******************** general functions ***************** */
125
126 static bool use_depth_doit(Scene *scene, View3D *v3d)
127 {
128         if (v3d->drawtype > OB_WIRE)
129                 return true;
130
131         /* special case (depth for wire color) */
132         if (v3d->drawtype <= OB_WIRE) {
133                 if (scene->obedit && scene->obedit->type == OB_MESH) {
134                         Mesh *me = scene->obedit->data;
135                         if (me->drawflag & ME_DRAWEIGHT) {
136                                 return true;
137                         }
138                 }
139         }
140         return false;
141 }
142
143 static bool use_depth(const bContext *C)
144 {
145         View3D *v3d = CTX_wm_view3d(C);
146         Scene *scene = CTX_data_scene(C);
147         return use_depth_doit(scene, v3d);
148 }
149
150 /**
151  * \note keep this synced with #ED_view3d_mats_rv3d_backup/#ED_view3d_mats_rv3d_restore
152  */
153 void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
154 {
155         RegionView3D *rv3d = ar->regiondata;
156
157
158         /* setup window matrices */
159         if (winmat)
160                 copy_m4_m4(rv3d->winmat, winmat);
161         else
162                 view3d_winmatrix_set(ar, v3d, NULL);
163
164         /* setup view matrix */
165         if (viewmat)
166                 copy_m4_m4(rv3d->viewmat, viewmat);
167         else
168                 view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
169
170         /* update utility matrices */
171         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
172         invert_m4_m4(rv3d->persinv, rv3d->persmat);
173         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
174
175         /* calculate GLSL view dependent values */
176
177         /* store window coordinates scaling/offset */
178         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
179                 rctf cameraborder;
180                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &cameraborder, false);
181                 rv3d->viewcamtexcofac[0] = (float)ar->winx / BLI_rctf_size_x(&cameraborder);
182                 rv3d->viewcamtexcofac[1] = (float)ar->winy / BLI_rctf_size_y(&cameraborder);
183
184                 rv3d->viewcamtexcofac[2] = -rv3d->viewcamtexcofac[0] * cameraborder.xmin / (float)ar->winx;
185                 rv3d->viewcamtexcofac[3] = -rv3d->viewcamtexcofac[1] * cameraborder.ymin / (float)ar->winy;
186         }
187         else {
188                 rv3d->viewcamtexcofac[0] = rv3d->viewcamtexcofac[1] = 1.0f;
189                 rv3d->viewcamtexcofac[2] = rv3d->viewcamtexcofac[3] = 0.0f;
190         }
191
192         /* calculate pixelsize factor once, is used for lamps and obcenters */
193         {
194                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
195                  * because of float point precision problems at large values [#23908] */
196                 float v1[3], v2[3];
197                 float len_px, len_sc;
198
199                 v1[0] = rv3d->persmat[0][0];
200                 v1[1] = rv3d->persmat[1][0];
201                 v1[2] = rv3d->persmat[2][0];
202
203                 v2[0] = rv3d->persmat[0][1];
204                 v2[1] = rv3d->persmat[1][1];
205                 v2[2] = rv3d->persmat[2][1];
206
207                 len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
208                 len_sc = (float)MAX2(ar->winx, ar->winy);
209
210                 rv3d->pixsize = len_px / len_sc;
211         }
212 }
213
214 static void view3d_main_region_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
215 {
216         RegionView3D *rv3d = ar->regiondata;
217
218         ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat);
219
220         /* set for opengl */
221         gpuLoadProjectionMatrix(rv3d->winmat);
222         gpuLoadMatrix(rv3d->viewmat);
223 }
224
225 static bool view3d_stereo3d_active(const bContext *C, Scene *scene, View3D *v3d, RegionView3D *rv3d)
226 {
227         wmWindow *win = CTX_wm_window(C);
228
229         if ((scene->r.scemode & R_MULTIVIEW) == 0)
230                 return false;
231
232         if (WM_stereo3d_enabled(win, true) == false)
233                 return false;
234
235         if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB)
236                 return false;
237
238         if (scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) {
239                 if (v3d->stereo3d_camera == STEREO_MONO_ID)
240                         return false;
241
242                 return BKE_scene_multiview_is_stereo3d(&scene->r);
243         }
244
245         return true;
246 }
247
248 /* setup the view and win matrices for the multiview cameras
249  *
250  * unlike view3d_stereo3d_setup_offscreen, when view3d_stereo3d_setup is called
251  * we have no winmatrix (i.e., projection matrix) defined at that time.
252  * Since the camera and the camera shift are needed for the winmat calculation
253  * we do a small hack to replace it temporarily so we don't need to change the
254  * view3d)main_region_setup_view() code to account for that.
255  */
256 static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar)
257 {
258         bool is_left;
259         const char *names[2] = { STEREO_LEFT_NAME, STEREO_RIGHT_NAME };
260         const char *viewname;
261
262         /* show only left or right camera */
263         if (v3d->stereo3d_camera != STEREO_3D_ID)
264                 v3d->multiview_eye = v3d->stereo3d_camera;
265
266         is_left = v3d->multiview_eye == STEREO_LEFT_ID;
267         viewname = names[is_left ? STEREO_LEFT_ID : STEREO_RIGHT_ID];
268
269         /* update the viewport matrices with the new camera */
270         if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
271                 Camera *data;
272                 float viewmat[4][4];
273                 float shiftx;
274
275                 data = (Camera *)v3d->camera->data;
276                 shiftx = data->shiftx;
277
278                 BLI_lock_thread(LOCK_VIEW3D);
279                 data->shiftx = BKE_camera_multiview_shift_x(&scene->r, v3d->camera, viewname);
280
281                 BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
282                 view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
283
284                 data->shiftx = shiftx;
285                 BLI_unlock_thread(LOCK_VIEW3D);
286         }
287         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
288                 float viewmat[4][4];
289                 Object *view_ob = v3d->camera;
290                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
291
292                 BLI_lock_thread(LOCK_VIEW3D);
293                 v3d->camera = camera;
294
295                 BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
296                 view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
297
298                 v3d->camera = view_ob;
299                 BLI_unlock_thread(LOCK_VIEW3D);
300         }
301 }
302
303 /* ******************** debug ***************** */
304
305 #define VIEW3D_DRAW_DEBUG 1
306 /* TODO: expand scope of this flag so UI reflects the underlying code */
307
308 #if VIEW3D_DRAW_DEBUG
309
310 static void view3d_draw_debug_store_depth(ARegion *UNUSED(ar), DrawData *draw_data)
311 {
312         GPUViewport *viewport = draw_data->viewport;
313         GLint viewport_size[4];
314         glGetIntegerv(GL_VIEWPORT, viewport_size);
315
316         const int x = viewport_size[0];
317         const int y = viewport_size[1];
318         const int w = viewport_size[2];
319         const int h = viewport_size[3];
320
321         if (GPU_viewport_debug_depth_is_valid(viewport)) {
322                 if ((GPU_viewport_debug_depth_width(viewport) != w) ||
323                     (GPU_viewport_debug_depth_height(viewport) != h))
324                 {
325                         GPU_viewport_debug_depth_free(viewport);
326                 }
327         }
328
329         if (!GPU_viewport_debug_depth_is_valid(viewport)) {
330                 char error[256];
331                 if (!GPU_viewport_debug_depth_create(viewport, w, h, error)) {
332                         fprintf(stderr, "Failed to create depth buffer for debug: %s\n", error);
333                         return;
334                 }
335         }
336
337         GPU_viewport_debug_depth_store(viewport, x, y);
338 }
339
340 static void view3d_draw_debug_post_solid(const bContext *C, ARegion *ar, DrawData *draw_data)
341 {
342         View3D *v3d = CTX_wm_view3d(C);
343
344         if ((v3d->tmp_compat_flag & V3D_DEBUG_SHOW_SCENE_DEPTH) != 0) {
345                 view3d_draw_debug_store_depth(ar, draw_data);
346         }
347 }
348
349 static void view3d_draw_debug(const bContext *C, ARegion *ar, DrawData *draw_data)
350 {
351         View3D *v3d = CTX_wm_view3d(C);
352
353         if ((v3d->tmp_compat_flag & V3D_DEBUG_SHOW_COMBINED_DEPTH) != 0) {
354                 /* store */
355                 view3d_draw_debug_store_depth(ar, draw_data);
356         }
357
358         if (((v3d->tmp_compat_flag & V3D_DEBUG_SHOW_SCENE_DEPTH) != 0) ||
359             ((v3d->tmp_compat_flag & V3D_DEBUG_SHOW_COMBINED_DEPTH) != 0))
360         {
361                 /* draw */
362                 if (GPU_viewport_debug_depth_is_valid(draw_data->viewport)) {
363                         GPU_viewport_debug_depth_draw(draw_data->viewport, v3d->debug.znear, v3d->debug.zfar);
364                 }
365         }
366         else {
367                 /* cleanup */
368                 GPU_viewport_debug_depth_free(draw_data->viewport);
369         }
370 }
371
372 #endif /* VIEW3D_DRAW_DEBUG */
373
374 /* ******************** view border ***************** */
375
376 static void view3d_camera_border(
377         const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
378         rctf *r_viewborder, const bool no_shift, const bool no_zoom)
379 {
380         CameraParams params;
381         rctf rect_view, rect_camera;
382
383         /* get viewport viewplane */
384         BKE_camera_params_init(&params);
385         BKE_camera_params_from_view3d(&params, v3d, rv3d);
386         if (no_zoom)
387                 params.zoom = 1.0f;
388         BKE_camera_params_compute_viewplane(&params, ar->winx, ar->winy, 1.0f, 1.0f);
389         rect_view = params.viewplane;
390
391         /* get camera viewplane */
392         BKE_camera_params_init(&params);
393         /* fallback for non camera objects */
394         params.clipsta = v3d->near;
395         params.clipend = v3d->far;
396         BKE_camera_params_from_object(&params, v3d->camera);
397         if (no_shift) {
398                 params.shiftx = 0.0f;
399                 params.shifty = 0.0f;
400         }
401         BKE_camera_params_compute_viewplane(&params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
402         rect_camera = params.viewplane;
403
404         /* get camera border within viewport */
405         r_viewborder->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
406         r_viewborder->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
407         r_viewborder->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
408         r_viewborder->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
409 }
410
411 void ED_view3d_calc_camera_border_size(
412         const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
413         float r_size[2])
414 {
415         rctf viewborder;
416
417         view3d_camera_border(scene, ar, v3d, rv3d, &viewborder, true, true);
418         r_size[0] = BLI_rctf_size_x(&viewborder);
419         r_size[1] = BLI_rctf_size_y(&viewborder);
420 }
421
422 void ED_view3d_calc_camera_border(
423         const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
424         rctf *r_viewborder, const bool no_shift)
425 {
426         view3d_camera_border(scene, ar, v3d, rv3d, r_viewborder, no_shift, false);
427 }
428
429 static void drawviewborder_grid3(uint shdr_pos, float x1, float x2, float y1, float y2, float fac)
430 {
431         float x3, y3, x4, y4;
432
433         x3 = x1 + fac * (x2 - x1);
434         y3 = y1 + fac * (y2 - y1);
435         x4 = x1 + (1.0f - fac) * (x2 - x1);
436         y4 = y1 + (1.0f - fac) * (y2 - y1);
437
438         immBegin(PRIM_LINES, 8);
439
440         immVertex2f(shdr_pos, x1, y3);
441         immVertex2f(shdr_pos, x2, y3);
442
443         immVertex2f(shdr_pos, x1, y4);
444         immVertex2f(shdr_pos, x2, y4);
445
446         immVertex2f(shdr_pos, x3, y1);
447         immVertex2f(shdr_pos, x3, y2);
448
449         immVertex2f(shdr_pos, x4, y1);
450         immVertex2f(shdr_pos, x4, y2);
451
452         immEnd();
453 }
454
455 /* harmonious triangle */
456 static void drawviewborder_triangle(
457         uint shdr_pos, float x1, float x2, float y1, float y2, const char golden, const char dir)
458 {
459         float ofs;
460         float w = x2 - x1;
461         float h = y2 - y1;
462
463         immBegin(PRIM_LINES, 6);
464
465         if (w > h) {
466                 if (golden) {
467                         ofs = w * (1.0f - (1.0f / 1.61803399f));
468                 }
469                 else {
470                         ofs = h * (h / w);
471                 }
472                 if (dir == 'B') SWAP(float, y1, y2);
473
474                 immVertex2f(shdr_pos, x1, y1);
475                 immVertex2f(shdr_pos, x2, y2);
476
477                 immVertex2f(shdr_pos, x2, y1);
478                 immVertex2f(shdr_pos, x1 + (w - ofs), y2);
479
480                 immVertex2f(shdr_pos, x1, y2);
481                 immVertex2f(shdr_pos, x1 + ofs, y1);
482         }
483         else {
484                 if (golden) {
485                         ofs = h * (1.0f - (1.0f / 1.61803399f));
486                 }
487                 else {
488                         ofs = w * (w / h);
489                 }
490                 if (dir == 'B') SWAP(float, x1, x2);
491
492                 immVertex2f(shdr_pos, x1, y1);
493                 immVertex2f(shdr_pos, x2, y2);
494
495                 immVertex2f(shdr_pos, x2, y1);
496                 immVertex2f(shdr_pos, x1, y1 + ofs);
497
498                 immVertex2f(shdr_pos, x1, y2);
499                 immVertex2f(shdr_pos, x2, y1 + (h - ofs));
500         }
501
502         immEnd();
503 }
504
505 static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
506 {
507         float x1, x2, y1, y2;
508         float x1i, x2i, y1i, y2i;
509
510         rctf viewborder;
511         Camera *ca = NULL;
512         RegionView3D *rv3d = ar->regiondata;
513
514         if (v3d->camera == NULL)
515                 return;
516         if (v3d->camera->type == OB_CAMERA)
517                 ca = v3d->camera->data;
518
519         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
520         /* the offsets */
521         x1 = viewborder.xmin;
522         y1 = viewborder.ymin;
523         x2 = viewborder.xmax;
524         y2 = viewborder.ymax;
525
526         glLineWidth(1.0f);
527
528         /* apply offsets so the real 3D camera shows through */
529
530         /* note: quite un-scientific but without this bit extra
531          * 0.0001 on the lower left the 2D border sometimes
532          * obscures the 3D camera border */
533         /* note: with VIEW3D_CAMERA_BORDER_HACK defined this error isn't noticeable
534          * but keep it here in case we need to remove the workaround */
535         x1i = (int)(x1 - 1.0001f);
536         y1i = (int)(y1 - 1.0001f);
537         x2i = (int)(x2 + (1.0f - 0.0001f));
538         y2i = (int)(y2 + (1.0f - 0.0001f));
539
540         uint shdr_pos = VertexFormat_add_attrib(immVertexFormat(), "pos", COMP_F32, 2, KEEP_FLOAT);
541
542         /* First, solid lines. */
543         {
544                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
545
546                 /* passepartout, specified in camera edit buttons */
547                 if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
548                         const float winx = (ar->winx + 1);
549                         const float winy = (ar->winy + 1);
550
551                         float alpha = 1.0f;
552
553                         if (ca->passepartalpha != 1.0f) {
554                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
555                                 glEnable(GL_BLEND);
556                                 alpha = ca->passepartalpha;
557                         }
558
559                         immUniformColor4f(0.0f, 0.0f, 0.0f, alpha);
560
561                         if (x1i > 0.0f)
562                                 immRectf(shdr_pos, 0.0f, winy, x1i, 0.0f);
563                         if (x2i < winx)
564                                 immRectf(shdr_pos, x2i, winy, winx, 0.0f);
565                         if (y2i < winy)
566                                 immRectf(shdr_pos, x1i, winy, x2i, y2i);
567                         if (y2i > 0.0f)
568                                 immRectf(shdr_pos, x1i, y1i, x2i, 0.0f);
569
570                         glDisable(GL_BLEND);
571                 }
572
573                 immUniformThemeColor(TH_BACK);
574                 imm_draw_line_box(shdr_pos, x1i, y1i, x2i, y2i);
575
576 #ifdef VIEW3D_CAMERA_BORDER_HACK
577                 if (view3d_camera_border_hack_test == true) {
578                         immUniformColor3ubv(view3d_camera_border_hack_col);
579                         imm_draw_line_box(shdr_pos, x1i + 1, y1i + 1, x2i - 1, y2i - 1);
580                         view3d_camera_border_hack_test = false;
581                 }
582 #endif
583
584                 immUnbindProgram();
585         }
586
587         /* And now, the dashed lines! */
588         {
589                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_COLOR);
590
591                 float viewport_size[4];
592                 glGetFloatv(GL_VIEWPORT, viewport_size);
593                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
594
595                 immUniform1i("num_colors", 0);  /* "simple" mode */
596                 immUniform1f("dash_width", 6.0f);
597                 immUniform1f("dash_factor", 0.5f);
598
599                 /* outer line not to confuse with object selection */
600                 if (v3d->flag2 & V3D_LOCK_CAMERA) {
601                         immUniformThemeColor(TH_REDALERT);
602                         imm_draw_line_box(shdr_pos, x1i - 1, y1i - 1, x2i + 1, y2i + 1);
603                 }
604
605                 immUniformThemeColor(TH_VIEW_OVERLAY);
606                 imm_draw_line_box(shdr_pos, x1i, y1i, x2i, y2i);
607
608                 /* border */
609                 if (scene->r.mode & R_BORDER) {
610                         float x3, y3, x4, y4;
611
612                         x3 = floorf(x1 + (scene->r.border.xmin * (x2 - x1))) - 1;
613                         y3 = floorf(y1 + (scene->r.border.ymin * (y2 - y1))) - 1;
614                         x4 = floorf(x1 + (scene->r.border.xmax * (x2 - x1))) + (U.pixelsize - 1);
615                         y4 = floorf(y1 + (scene->r.border.ymax * (y2 - y1))) + (U.pixelsize - 1);
616
617                         immUniformColor3f(1.0f, 0.25f, 0.25f);
618                         imm_draw_line_box(shdr_pos, x3, y3, x4, y4);
619                 }
620
621                 /* safety border */
622                 if (ca) {
623                         immUniformThemeColorBlend(TH_VIEW_OVERLAY, TH_BACK, 0.25f);
624
625                         if (ca->dtx & CAM_DTX_CENTER) {
626                                 float x3, y3;
627
628                                 x3 = x1 + 0.5f * (x2 - x1);
629                                 y3 = y1 + 0.5f * (y2 - y1);
630
631                                 immBegin(PRIM_LINES, 4);
632
633                                 immVertex2f(shdr_pos, x1, y3);
634                                 immVertex2f(shdr_pos, x2, y3);
635
636                                 immVertex2f(shdr_pos, x3, y1);
637                                 immVertex2f(shdr_pos, x3, y2);
638
639                                 immEnd();
640                         }
641
642                         if (ca->dtx & CAM_DTX_CENTER_DIAG) {
643                                 immBegin(PRIM_LINES, 4);
644
645                                 immVertex2f(shdr_pos, x1, y1);
646                                 immVertex2f(shdr_pos, x2, y2);
647
648                                 immVertex2f(shdr_pos, x1, y2);
649                                 immVertex2f(shdr_pos, x2, y1);
650
651                                 immEnd();
652                         }
653
654                         if (ca->dtx & CAM_DTX_THIRDS) {
655                                 drawviewborder_grid3(shdr_pos, x1, x2, y1, y2, 1.0f / 3.0f);
656                         }
657
658                         if (ca->dtx & CAM_DTX_GOLDEN) {
659                                 drawviewborder_grid3(shdr_pos, x1, x2, y1, y2, 1.0f - (1.0f / 1.61803399f));
660                         }
661
662                         if (ca->dtx & CAM_DTX_GOLDEN_TRI_A) {
663                                 drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 0, 'A');
664                         }
665
666                         if (ca->dtx & CAM_DTX_GOLDEN_TRI_B) {
667                                 drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 0, 'B');
668                         }
669
670                         if (ca->dtx & CAM_DTX_HARMONY_TRI_A) {
671                                 drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 1, 'A');
672                         }
673
674                         if (ca->dtx & CAM_DTX_HARMONY_TRI_B) {
675                                 drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 1, 'B');
676                         }
677
678                         if (ca->flag & CAM_SHOW_SAFE_MARGINS) {
679                                 UI_draw_safe_areas(shdr_pos, x1, x2, y1, y2,
680                                                    scene->safe_areas.title, scene->safe_areas.action);
681
682                                 if (ca->flag & CAM_SHOW_SAFE_CENTER) {
683                                         UI_draw_safe_areas(shdr_pos, x1, x2, y1, y2,
684                                                            scene->safe_areas.title_center, scene->safe_areas.action_center);
685                                 }
686                         }
687                 }
688
689                 if (ca->flag & CAM_SHOWSENSOR) {
690                         /* determine sensor fit, and get sensor x/y, for auto fit we
691                          * assume and square sensor and only use sensor_x */
692                         float sizex = scene->r.xsch * scene->r.xasp;
693                         float sizey = scene->r.ysch * scene->r.yasp;
694                         int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
695                         float sensor_x = ca->sensor_x;
696                         float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
697
698                         /* determine sensor plane */
699                         rctf rect;
700
701                         if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
702                                 float sensor_scale = (x2i - x1i) / sensor_x;
703                                 float sensor_height = sensor_scale * sensor_y;
704
705                                 rect.xmin = x1i;
706                                 rect.xmax = x2i;
707                                 rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
708                                 rect.ymax = rect.ymin + sensor_height;
709                         }
710                         else {
711                                 float sensor_scale = (y2i - y1i) / sensor_y;
712                                 float sensor_width = sensor_scale * sensor_x;
713
714                                 rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
715                                 rect.xmax = rect.xmin + sensor_width;
716                                 rect.ymin = y1i;
717                                 rect.ymax = y2i;
718                         }
719
720                         /* draw */
721                         immUniformThemeColorShade(TH_VIEW_OVERLAY, 100);
722
723                         /* TODO Was using UI_draw_roundbox_4fv(false, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f, color).
724                          * We'll probably need a new imm_draw_line_roundbox_dashed dor that - though in practice the
725                          * 2.0f round corner effect was nearly not visible anyway... */
726                         imm_draw_line_box(shdr_pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
727                 }
728
729                 immUnbindProgram();
730         }
731
732         /* camera name - draw in highlighted text color */
733         if (ca && (ca->flag & CAM_SHOWNAME)) {
734                 UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
735                 BLF_draw_default(x1i, y1i - (0.7f * U.widget_unit), 0.0f,
736                                  v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
737         }
738 }
739
740 static void drawrenderborder(ARegion *ar, View3D *v3d)
741 {
742         /* use the same program for everything */
743         uint shdr_pos = VertexFormat_add_attrib(immVertexFormat(), "pos", COMP_F32, 2, KEEP_FLOAT);
744
745         glLineWidth(1.0f);
746
747         immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_COLOR);
748
749         float viewport_size[4];
750         glGetFloatv(GL_VIEWPORT, viewport_size);
751         immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
752
753         immUniform1i("num_colors", 0);  /* "simple" mode */
754         immUniform4f("color", 1.0f, 0.25f, 0.25f, 1.0f);
755         immUniform1f("dash_width", 6.0f);
756         immUniform1f("dash_factor", 0.5f);
757
758         imm_draw_line_box(shdr_pos,
759                           v3d->render_border.xmin * ar->winx, v3d->render_border.ymin * ar->winy,
760                           v3d->render_border.xmax * ar->winx, v3d->render_border.ymax * ar->winy);
761
762         immUnbindProgram();
763 }
764
765 void ED_view3d_draw_depth(
766         struct Depsgraph *graph,
767         ARegion *ar, View3D *v3d, bool alphaoverride)
768 {
769         Scene *scene = DAG_get_scene(graph);
770         RegionView3D *rv3d = ar->regiondata;
771
772         short zbuf = v3d->zbuf;
773         short flag = v3d->flag;
774         float glalphaclip = U.glalphaclip;
775         int obcenter_dia = U.obcenter_dia;
776         /* temp set drawtype to solid */
777         /* Setting these temporarily is not nice */
778         v3d->flag &= ~V3D_SELECT_OUTLINE;
779         U.glalphaclip = alphaoverride ? 0.5f : glalphaclip; /* not that nice but means we wont zoom into billboards */
780         U.obcenter_dia = 0;
781
782         view3d_winmatrix_set(ar, v3d, NULL);
783         view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
784
785         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
786         invert_m4_m4(rv3d->persinv, rv3d->persmat);
787         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
788
789         glClear(GL_DEPTH_BUFFER_BIT);
790
791         gpuLoadMatrix(rv3d->viewmat);
792
793         if (rv3d->rflag & RV3D_CLIPPING) {
794                 ED_view3d_clipping_set(rv3d);
795         }
796         /* get surface depth without bias */
797         rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
798
799         v3d->zbuf = true;
800         glEnable(GL_DEPTH_TEST);
801
802 #ifdef WITH_OPENGL_LEGACY
803         if (IS_VIEWPORT_LEGACY(vc->v3d)) {
804                 /* temp, calls into view3d_draw_legacy.c */
805                 ED_view3d_draw_depth_loop(scene, ar, v3d);
806         }
807         else
808 #endif /* WITH_OPENGL_LEGACY */
809         {
810                 DRW_draw_depth_loop(graph, ar, v3d);
811         }
812
813         if (rv3d->rflag & RV3D_CLIPPING) {
814                 ED_view3d_clipping_disable();
815         }
816         rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
817
818         v3d->zbuf = zbuf;
819         if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
820
821         U.glalphaclip = glalphaclip;
822         v3d->flag = flag;
823         U.obcenter_dia = obcenter_dia;
824 }
825
826 /* ******************** offline engine ***************** */
827
828 static bool view3d_draw_render_draw(const bContext *C, Scene *scene,
829     ARegion *ar, View3D *UNUSED(v3d),
830     bool clip_border, const rcti *border_rect)
831 {
832         RegionView3D *rv3d = ar->regiondata;
833         RenderEngineType *type;
834         GLint scissor[4];
835
836         /* create render engine */
837         if (!rv3d->render_engine) {
838                 RenderEngine *engine;
839
840                 type = RE_engines_find(scene->r.engine);
841
842                 if (!(type->view_update && type->render_to_view))
843                         return false;
844
845                 engine = RE_engine_create_ex(type, true);
846
847                 engine->tile_x = scene->r.tilex;
848                 engine->tile_y = scene->r.tiley;
849
850                 type->view_update(engine, C);
851
852                 rv3d->render_engine = engine;
853         }
854
855         /* rendered draw */
856         gpuPushMatrix();
857         float original_proj[4][4];
858         gpuGetProjectionMatrix(original_proj);
859         ED_region_pixelspace(ar);
860
861         if (clip_border) {
862                 /* for border draw, we only need to clear a subset of the 3d view */
863                 if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
864                         glGetIntegerv(GL_SCISSOR_BOX, scissor);
865                         glScissor(border_rect->xmin, border_rect->ymin,
866                                 BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
867                 }
868                 else {
869                         return false;
870                 }
871         }
872
873         /* don't change depth buffer */
874         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
875         glClear(GL_COLOR_BUFFER_BIT); /* is this necessary? -- merwin */
876
877         /* render result draw */
878         type = rv3d->render_engine->type;
879         type->render_to_view(rv3d->render_engine, C);
880
881         if (clip_border) {
882                 /* restore scissor as it was before */
883                 glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
884         }
885
886         gpuLoadProjectionMatrix(original_proj);
887         gpuPopMatrix();
888
889         return true;
890 }
891
892 /* ******************** background plates ***************** */
893
894 static void view3d_draw_background_gradient(void)
895 {
896         /* TODO: finish 2D API & draw background with that */
897
898         VertexFormat *format = immVertexFormat();
899         unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
900         unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
901         unsigned char col_hi[3], col_lo[3];
902
903         immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR);
904
905         UI_GetThemeColor3ubv(TH_LOW_GRAD, col_lo);
906         UI_GetThemeColor3ubv(TH_HIGH_GRAD, col_hi);
907
908         immBegin(PRIM_TRIANGLE_FAN, 4);
909         immAttrib3ubv(color, col_lo);
910         immVertex2f(pos, -1.0f, -1.0f);
911         immVertex2f(pos, 1.0f, -1.0f);
912
913         immAttrib3ubv(color, col_hi);
914         immVertex2f(pos, 1.0f, 1.0f);
915         immVertex2f(pos, -1.0f, 1.0f);
916         immEnd();
917
918         immUnbindProgram();
919 }
920
921 static void view3d_draw_background_none(void)
922 {
923         UI_ThemeClearColorAlpha(TH_HIGH_GRAD, 1.0f);
924         glClear(GL_COLOR_BUFFER_BIT);
925 }
926
927 static void view3d_draw_background_world(Scene *scene, View3D *v3d, RegionView3D *rv3d)
928 {
929         if (scene->world) {
930                 GPUMaterial *gpumat = GPU_material_world(scene, scene->world);
931
932                 /* calculate full shader for background */
933                 GPU_material_bind(gpumat, 1, 1, 1.0f, false, rv3d->viewmat, rv3d->viewinv, rv3d->viewcamtexcofac, (v3d->scenelock != 0));
934
935                 if (GPU_material_bound(gpumat)) {
936                         /* TODO viewport (dfelinto): GPU_material_bind relies on immediate mode,
937                          * we can't get rid of the following code without a bigger refactor
938                          * or we dropping this functionality. */
939
940                         glBegin(GL_TRIANGLE_STRIP);
941                         glVertex2f(-1.0f, -1.0f);
942                         glVertex2f(1.0f, -1.0f);
943                         glVertex2f(-1.0f, 1.0f);
944                         glVertex2f(1.0f, 1.0f);
945                         glEnd();
946
947                         GPU_material_unbind(gpumat);
948                         return;
949                 }
950         }
951
952         /* if any of the above fails */
953         view3d_draw_background_none();
954 }
955
956 /* ******************** solid plates ***************** */
957
958 /**
959  * Clear the buffer and draw the proper shader
960  */
961 static void view3d_draw_background(const bContext *C)
962 {
963         Scene *scene = CTX_data_scene(C);
964         View3D *v3d = CTX_wm_view3d(C);
965         RegionView3D *rv3d = CTX_wm_region_view3d(C);
966
967         /* Background functions do not read or write depth, but they do clear or completely
968          * overwrite color buffer.
969          */
970
971         switch (v3d->debug.background) {
972                 case V3D_DEBUG_BACKGROUND_WORLD:
973                         view3d_draw_background_world(scene, v3d, rv3d);
974                         break;
975                 case V3D_DEBUG_BACKGROUND_GRADIENT:
976                         view3d_draw_background_gradient();
977                         break;
978                 case V3D_DEBUG_BACKGROUND_NONE:
979                 default:
980                         view3d_draw_background_none();
981         }
982 }
983
984 /**
985  *
986  */
987 static void view3d_draw_render_solid_surfaces(const bContext *C, ARegion *ar, const bool UNUSED(run_screen_shaders))
988 {
989         /* TODO viewport */
990         draw_all_objects(C, ar, false, use_depth(C));
991 }
992
993 /**
994  *
995  */
996 static void view3d_draw_render_transparent_surfaces(const bContext *UNUSED(C))
997 {
998         /* TODO viewport */
999 }
1000
1001 /**
1002  *
1003  */
1004 static void view3d_draw_post_draw(const bContext *UNUSED(C))
1005 {
1006         /* TODO viewport */
1007 }
1008
1009 /* ******************** geometry overlay ***************** */
1010
1011 /**
1012  * Front/back wire frames
1013  */
1014 static void view3d_draw_wire_plates(const bContext *UNUSED(C))
1015 {
1016         /* TODO viewport */
1017 }
1018
1019 /**
1020  * Special treatment for selected objects
1021  */
1022 static void view3d_draw_outline_plates(const bContext *UNUSED(C))
1023 {
1024         /* TODO viewport */
1025 }
1026
1027 /* ******************** other elements ***************** */
1028
1029
1030 #define DEBUG_GRID 0
1031
1032 static void gridline_range(double x0, double dx, double max, int *r_first, int *r_count)
1033 {
1034         /* determine range of gridlines that appear in this Area -- similar calc but separate ranges for x & y
1035          * x0 is gridline 0, the axis in screen space
1036          * Area covers [0 .. max) pixels */
1037
1038         int first = (int)ceil(-x0 / dx);
1039         int last = (int)floor((max - x0) / dx);
1040
1041         if (first <= last) {
1042                 *r_first = first;
1043                 *r_count = last - first + 1;
1044         }
1045         else {
1046                 *r_first = 0;
1047                 *r_count = 0;
1048         }
1049
1050 #if DEBUG_GRID
1051         printf("   first %d * dx = %f\n", first, x0 + first * dx);
1052         printf("   last %d * dx = %f\n", last, x0 + last * dx);
1053         printf("   count = %d\n", *count_out);
1054 #endif
1055 }
1056
1057 static int gridline_count(ARegion *ar, double x0, double y0, double dx)
1058 {
1059         /* x0 & y0 establish the "phase" of the grid within this 2D region
1060          * dx is the frequency, shared by x & y directions
1061          * pass in dx of smallest (highest precision) grid we want to draw */
1062
1063 #if DEBUG_GRID
1064         printf("  %s(%f, %f, dx:%f)\n", __FUNCTION__, x0, y0, dx);
1065 #endif
1066
1067         int first, x_ct, y_ct;
1068
1069         gridline_range(x0, dx, ar->winx, &first, &x_ct);
1070         gridline_range(y0, dx, ar->winy, &first, &y_ct);
1071
1072         int total_ct = x_ct + y_ct;
1073
1074 #if DEBUG_GRID
1075         printf("   %d + %d = %d gridlines\n", x_ct, y_ct, total_ct);
1076 #endif
1077
1078         return total_ct;
1079 }
1080
1081 static bool drawgrid_draw(ARegion *ar, double x0, double y0, double dx, int skip_mod, unsigned pos, unsigned col, GLubyte col_value[3])
1082 {
1083         /* skip every skip_mod lines relative to each axis; they will be overlaid by another drawgrid_draw
1084          * always skip exact x0 & y0 axes; they will be drawn later in color
1085          *
1086          * set grid color once, just before the first line is drawn
1087          * it's harmless to set same color for every line, or every vertex
1088          * but if no lines are drawn, color must not be set! */
1089
1090 #if DEBUG_GRID
1091         printf("  %s(%f, %f, dx:%f, skip_mod:%d)\n", __FUNCTION__, x0, y0, dx, skip_mod);
1092 #endif
1093
1094         const float x_max = (float)ar->winx;
1095         const float y_max = (float)ar->winy;
1096
1097         int first, ct;
1098         int x_ct = 0, y_ct = 0; /* count of lines actually drawn */
1099         int lines_skipped_for_next_unit = 0;
1100
1101         /* draw vertical lines */
1102         gridline_range(x0, dx, x_max, &first, &ct);
1103
1104         for (int i = first; i < first + ct; ++i) {
1105                 if (i == 0)
1106                         continue;
1107                 else if (skip_mod && (i % skip_mod) == 0) {
1108                         ++lines_skipped_for_next_unit;
1109                         continue;
1110                 }
1111
1112                 if (x_ct == 0)
1113                         immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
1114
1115                 float x = (float)(x0 + i * dx);
1116                 immVertex2f(pos, x, 0.0f);
1117                 immVertex2f(pos, x, y_max);
1118                 ++x_ct;
1119         }
1120
1121         /* draw horizontal lines */
1122         gridline_range(y0, dx, y_max, &first, &ct);
1123
1124         for (int i = first; i < first + ct; ++i) {
1125                 if (i == 0)
1126                         continue;
1127                 else if (skip_mod && (i % skip_mod) == 0) {
1128                         ++lines_skipped_for_next_unit;
1129                         continue;
1130                 }
1131
1132                 if (x_ct + y_ct == 0)
1133                         immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
1134
1135                 float y = (float)(y0 + i * dx);
1136                 immVertex2f(pos, 0.0f, y);
1137                 immVertex2f(pos, x_max, y);
1138                 ++y_ct;
1139         }
1140
1141 #if DEBUG_GRID
1142         int total_ct = x_ct + y_ct;
1143         printf("    %d + %d = %d gridlines drawn, %d skipped for next unit\n", x_ct, y_ct, total_ct, lines_skipped_for_next_unit);
1144 #endif
1145
1146         return lines_skipped_for_next_unit > 0;
1147 }
1148
1149 #define GRID_MIN_PX_D 6.0
1150 #define GRID_MIN_PX_F 6.0f
1151
1152 static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
1153 {
1154         RegionView3D *rv3d = ar->regiondata;
1155
1156 #if DEBUG_GRID
1157         printf("%s width %d, height %d\n", __FUNCTION__, ar->winx, ar->winy);
1158 #endif
1159
1160         double fx = rv3d->persmat[3][0];
1161         double fy = rv3d->persmat[3][1];
1162         double fw = rv3d->persmat[3][3];
1163
1164         const double wx = 0.5 * ar->winx;  /* use double precision to avoid rounding errors */
1165         const double wy = 0.5 * ar->winy;
1166
1167         double x = wx * fx / fw;
1168         double y = wy * fy / fw;
1169
1170         double vec4[4] = { v3d->grid, v3d->grid, 0.0, 1.0 };
1171         mul_m4_v4d(rv3d->persmat, vec4);
1172         fx = vec4[0];
1173         fy = vec4[1];
1174         fw = vec4[3];
1175
1176         double dx = fabs(x - wx * fx / fw);
1177         if (dx == 0) dx = fabs(y - wy * fy / fw);
1178
1179         x += wx;
1180         y += wy;
1181
1182         /* now x, y, and dx have their final values
1183          * (x,y) is the world origin (0,0,0) mapped to Area-relative screen space
1184          * dx is the distance in pixels between grid lines -- same for horiz or vert grid lines */
1185
1186         glLineWidth(1.0f);
1187
1188 #if 0 /* TODO: write to UI/widget depth buffer, not scene depth */
1189         glDepthMask(GL_FALSE);  /* disable write in zbuffer */
1190 #endif
1191
1192         VertexFormat *format = immVertexFormat();
1193         unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1194         unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
1195
1196         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1197
1198         unsigned char col[3], col2[3];
1199         UI_GetThemeColor3ubv(TH_GRID, col);
1200
1201         if (unit->system) {
1202                 const void *usys;
1203                 int len;
1204
1205                 bUnit_GetSystem(unit->system, B_UNIT_LENGTH, &usys, &len);
1206
1207                 bool first = true;
1208
1209                 if (usys) {
1210                         int i = len;
1211                         while (i--) {
1212                                 double scalar = bUnit_GetScaler(usys, i);
1213
1214                                 double dx_scalar = dx * scalar / (double)unit->scale_length;
1215                                 if (dx_scalar < (GRID_MIN_PX_D * 2.0)) {
1216                                         /* very very small grid items are less useful when dealing with units */
1217                                         continue;
1218                                 }
1219
1220                                 if (first) {
1221                                         first = false;
1222
1223                                         /* Store the smallest drawn grid size units name so users know how big each grid cell is */
1224                                         *grid_unit = bUnit_GetNameDisplay(usys, i);
1225                                         rv3d->gridview = (float)((scalar * (double)v3d->grid) / (double)unit->scale_length);
1226
1227                                         int gridline_ct = gridline_count(ar, x, y, dx_scalar);
1228                                         if (gridline_ct == 0)
1229                                                 goto drawgrid_cleanup; /* nothing to draw */
1230
1231                                         immBegin(PRIM_LINES, gridline_ct * 2);
1232                                 }
1233
1234                                 float blend_fac = 1.0f - ((GRID_MIN_PX_F * 2.0f) / (float)dx_scalar);
1235                                 /* tweak to have the fade a bit nicer */
1236                                 blend_fac = (blend_fac * blend_fac) * 2.0f;
1237                                 CLAMP(blend_fac, 0.3f, 1.0f);
1238
1239                                 UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, blend_fac, col2);
1240
1241                                 const int skip_mod = (i == 0) ? 0 : (int)round(bUnit_GetScaler(usys, i - 1) / scalar);
1242 #if DEBUG_GRID
1243                                 printf("%s %f, ", bUnit_GetNameDisplay(usys, i), scalar);
1244                                 if (i > 0)
1245                                         printf("next unit is %d times larger\n", skip_mod);
1246                                 else
1247                                         printf("largest unit\n");
1248 #endif
1249                                 if (!drawgrid_draw(ar, x, y, dx_scalar, skip_mod, pos, color, col2))
1250                                         break;
1251                         }
1252                 }
1253         }
1254         else {
1255                 const double sublines = v3d->gridsubdiv;
1256                 const float  sublines_fl = v3d->gridsubdiv;
1257
1258                 int grids_to_draw = 2; /* first the faint fine grid, then the bold coarse grid */
1259
1260                 if (dx < GRID_MIN_PX_D) {
1261                         rv3d->gridview *= sublines_fl;
1262                         dx *= sublines;
1263                         if (dx < GRID_MIN_PX_D) {
1264                                 rv3d->gridview *= sublines_fl;
1265                                 dx *= sublines;
1266                                 if (dx < GRID_MIN_PX_D) {
1267                                         rv3d->gridview *= sublines_fl;
1268                                         dx *= sublines;
1269                                         grids_to_draw = (dx < GRID_MIN_PX_D) ? 0 : 1;
1270                                 }
1271                         }
1272                 }
1273                 else {
1274                         if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
1275                                 rv3d->gridview /= sublines_fl;
1276                                 dx /= sublines;
1277                                 if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
1278                                         rv3d->gridview /= sublines_fl;
1279                                         dx /= sublines;
1280                                         if (dx > (GRID_MIN_PX_D * 10.0)) {
1281                                                 grids_to_draw = 1;
1282                                         }
1283                                 }
1284                         }
1285                 }
1286
1287                 int gridline_ct = gridline_count(ar, x, y, dx);
1288                 if (gridline_ct == 0)
1289                         goto drawgrid_cleanup; /* nothing to draw */
1290
1291                 immBegin(PRIM_LINES, gridline_ct * 2);
1292
1293                 if (grids_to_draw == 2) {
1294                         UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0), col2);
1295                         if (drawgrid_draw(ar, x, y, dx, v3d->gridsubdiv, pos, color, col2))
1296                                 drawgrid_draw(ar, x, y, dx * sublines, 0, pos, color, col);
1297                 }
1298                 else if (grids_to_draw == 1) {
1299                         drawgrid_draw(ar, x, y, dx, 0, pos, color, col);
1300                 }
1301         }
1302
1303         /* draw visible axes */
1304         /* horizontal line */
1305         if (0 <= y && y < ar->winy) {
1306                 UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT) ? 'Y' : 'X');
1307                 immAttrib3ub(color, col2[0], col2[1], col2[2]);
1308                 immVertex2f(pos, 0.0f, y);
1309                 immVertex2f(pos, (float)ar->winx, y);
1310         }
1311
1312         /* vertical line */
1313         if (0 <= x && x < ar->winx) {
1314                 UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM) ? 'Y' : 'Z');
1315                 immAttrib3ub(color, col2[0], col2[1], col2[2]);
1316                 immVertex2f(pos, x, 0.0f);
1317                 immVertex2f(pos, x, (float)ar->winy);
1318         }
1319
1320         immEnd();
1321
1322 drawgrid_cleanup:
1323         immUnbindProgram();
1324
1325 #if 0 /* depth write is left enabled above */
1326         glDepthMask(GL_TRUE);  /* enable write in zbuffer */
1327 #endif
1328 }
1329
1330 #undef DEBUG_GRID
1331 #undef GRID_MIN_PX_D
1332 #undef GRID_MIN_PX_F
1333
1334 static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
1335 {
1336         /* draw only if there is something to draw */
1337         if (v3d->gridflag & (V3D_SHOW_FLOOR | V3D_SHOW_X | V3D_SHOW_Y | V3D_SHOW_Z)) {
1338                 /* draw how many lines?
1339                  * trunc(v3d->gridlines / 2) * 4
1340                  * + 2 for xy axes (possibly with special colors)
1341                  * + 1 for z axis (the only line not in xy plane)
1342                  * even v3d->gridlines are honored, odd rounded down */
1343                 const int gridlines = v3d->gridlines / 2;
1344                 const float grid_scale = ED_view3d_grid_scale(scene, v3d, grid_unit);
1345                 const float grid = gridlines * grid_scale;
1346
1347                 const bool show_floor = (v3d->gridflag & V3D_SHOW_FLOOR) && gridlines >= 1;
1348
1349                 bool show_axis_x = v3d->gridflag & V3D_SHOW_X;
1350                 bool show_axis_y = v3d->gridflag & V3D_SHOW_Y;
1351                 bool show_axis_z = v3d->gridflag & V3D_SHOW_Z;
1352
1353                 unsigned char col_grid[3], col_axis[3];
1354
1355                 glLineWidth(1.0f);
1356
1357                 UI_GetThemeColor3ubv(TH_GRID, col_grid);
1358
1359                 if (!write_depth)
1360                         glDepthMask(GL_FALSE);
1361
1362                 if (show_floor) {
1363                         const unsigned vertex_ct = 2 * (gridlines * 4 + 2);
1364                         const int sublines = v3d->gridsubdiv;
1365
1366                         unsigned char col_bg[3], col_grid_emphasise[3], col_grid_light[3];
1367
1368                         VertexFormat *format = immVertexFormat();
1369                         unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1370                         unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
1371
1372                         immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
1373
1374                         immBegin(PRIM_LINES, vertex_ct);
1375
1376                         /* draw normal grid lines */
1377                         UI_GetColorPtrShade3ubv(col_grid, col_grid_light, 10);
1378
1379                         for (int a = 1; a <= gridlines; a++) {
1380                                 /* skip emphasised divider lines */
1381                                 if (a % sublines != 0) {
1382                                         const float line = a * grid_scale;
1383
1384                                         immAttrib3ubv(color, col_grid_light);
1385
1386                                         immVertex2f(pos, -grid, -line);
1387                                         immVertex2f(pos, +grid, -line);
1388                                         immVertex2f(pos, -grid, +line);
1389                                         immVertex2f(pos, +grid, +line);
1390
1391                                         immVertex2f(pos, -line, -grid);
1392                                         immVertex2f(pos, -line, +grid);
1393                                         immVertex2f(pos, +line, -grid);
1394                                         immVertex2f(pos, +line, +grid);
1395                                 }
1396                         }
1397
1398                         /* draw emphasised grid lines */
1399                         UI_GetThemeColor3ubv(TH_BACK, col_bg);
1400                         /* emphasise division lines lighter instead of darker, if background is darker than grid */
1401                         UI_GetColorPtrShade3ubv(col_grid, col_grid_emphasise,
1402                                 (col_grid[0] + col_grid[1] + col_grid[2] + 30 >
1403                                 col_bg[0] + col_bg[1] + col_bg[2]) ? 20 : -10);
1404
1405                         if (sublines <= gridlines) {
1406                                 immAttrib3ubv(color, col_grid_emphasise);
1407
1408                                 for (int a = sublines; a <= gridlines; a += sublines) {
1409                                         const float line = a * grid_scale;
1410
1411                                         immVertex2f(pos, -grid, -line);
1412                                         immVertex2f(pos, +grid, -line);
1413                                         immVertex2f(pos, -grid, +line);
1414                                         immVertex2f(pos, +grid, +line);
1415
1416                                         immVertex2f(pos, -line, -grid);
1417                                         immVertex2f(pos, -line, +grid);
1418                                         immVertex2f(pos, +line, -grid);
1419                                         immVertex2f(pos, +line, +grid);
1420                                 }
1421                         }
1422
1423                         /* draw X axis */
1424                         if (show_axis_x) {
1425                                 show_axis_x = false; /* drawing now, won't need to draw later */
1426                                 UI_make_axis_color(col_grid, col_axis, 'X');
1427                                 immAttrib3ubv(color, col_axis);
1428                         }
1429                         else
1430                                 immAttrib3ubv(color, col_grid_emphasise);
1431
1432                         immVertex2f(pos, -grid, 0.0f);
1433                         immVertex2f(pos, +grid, 0.0f);
1434
1435                         /* draw Y axis */
1436                         if (show_axis_y) {
1437                                 show_axis_y = false; /* drawing now, won't need to draw later */
1438                                 UI_make_axis_color(col_grid, col_axis, 'Y');
1439                                 immAttrib3ubv(color, col_axis);
1440                         }
1441                         else
1442                                 immAttrib3ubv(color, col_grid_emphasise);
1443
1444                         immVertex2f(pos, 0.0f, -grid);
1445                         immVertex2f(pos, 0.0f, +grid);
1446
1447                         immEnd();
1448                         immUnbindProgram();
1449
1450                         /* done with XY plane */
1451                 }
1452
1453                 if (show_axis_x || show_axis_y || show_axis_z) {
1454                         /* draw axis lines -- sometimes grid floor is off, other times we still need to draw the Z axis */
1455
1456                         VertexFormat *format = immVertexFormat();
1457                         unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 3, KEEP_FLOAT);
1458                         unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
1459
1460                         immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
1461                         immBegin(PRIM_LINES, (show_axis_x + show_axis_y + show_axis_z) * 2);
1462
1463                         if (show_axis_x) {
1464                                 UI_make_axis_color(col_grid, col_axis, 'X');
1465                                 immAttrib3ubv(color, col_axis);
1466                                 immVertex3f(pos, -grid, 0.0f, 0.0f);
1467                                 immVertex3f(pos, +grid, 0.0f, 0.0f);
1468                         }
1469
1470                         if (show_axis_y) {
1471                                 UI_make_axis_color(col_grid, col_axis, 'Y');
1472                                 immAttrib3ubv(color, col_axis);
1473                                 immVertex3f(pos, 0.0f, -grid, 0.0f);
1474                                 immVertex3f(pos, 0.0f, +grid, 0.0f);
1475                         }
1476
1477                         if (show_axis_z) {
1478                                 UI_make_axis_color(col_grid, col_axis, 'Z');
1479                                 immAttrib3ubv(color, col_axis);
1480                                 immVertex3f(pos, 0.0f, 0.0f, -grid);
1481                                 immVertex3f(pos, 0.0f, 0.0f, +grid);
1482                         }
1483
1484                         immEnd();
1485                         immUnbindProgram();
1486                 }
1487
1488                 if (!write_depth)
1489                         glDepthMask(GL_TRUE);
1490         }
1491 }
1492
1493 /** could move this elsewhere, but tied into #ED_view3d_grid_scale */
1494 float ED_scene_grid_scale(Scene *scene, const char **grid_unit)
1495 {
1496         /* apply units */
1497         if (scene->unit.system) {
1498                 const void *usys;
1499                 int len;
1500
1501                 bUnit_GetSystem(scene->unit.system, B_UNIT_LENGTH, &usys, &len);
1502
1503                 if (usys) {
1504                         int i = bUnit_GetBaseUnit(usys);
1505                         if (grid_unit)
1506                                 *grid_unit = bUnit_GetNameDisplay(usys, i);
1507                         return (float)bUnit_GetScaler(usys, i) / scene->unit.scale_length;
1508                 }
1509         }
1510
1511         return 1.0f;
1512 }
1513
1514 float ED_view3d_grid_scale(Scene *scene, View3D *v3d, const char **grid_unit)
1515 {
1516         return v3d->grid * ED_scene_grid_scale(scene, grid_unit);
1517 }
1518
1519
1520 static void view3d_draw_grid(const bContext *C, ARegion *ar)
1521 {
1522         /* TODO viewport
1523          * Missing is the flags to check whether to draw it
1524          * for now now we are using the flags in v3d itself.
1525          *
1526          * Also for now always assume depth is there, so we
1527          * draw on top of it.
1528          */
1529         /**
1530          * Calculate pixel-size factor once, is used for lamps and object centers.
1531          * Used by #ED_view3d_pixel_size and typically not accessed directly.
1532          *
1533          * \note #BKE_camera_params_compute_viewplane' also calculates a pixel-size value,
1534          * passed to #RE_SetPixelSize, in ortho mode this is compatible with this value,
1535          * but in perspective mode its offset by the near-clip.
1536          *
1537          * 'RegionView3D.pixsize' is used for viewport drawing, not rendering.
1538          */
1539         Scene *scene = CTX_data_scene(C);
1540         View3D *v3d = CTX_wm_view3d(C);
1541         RegionView3D *rv3d = ar->regiondata;
1542
1543         const bool draw_floor = (rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO);
1544         const char *grid_unit = NULL;
1545
1546         /* ortho grid goes first, does not write to depth buffer and doesn't need depth test so it will override
1547          * objects if done last
1548          * needs to be done always, gridview is adjusted in drawgrid() now, but only for ortho views.
1549          */
1550         rv3d->gridview = ED_view3d_grid_scale(scene, v3d, &grid_unit);
1551
1552         glEnable(GL_DEPTH_TEST);
1553         glDepthMask(GL_FALSE); /* read & test depth, but don't alter it. TODO: separate UI depth buffer */
1554
1555         if (!draw_floor) {
1556                 ED_region_pixelspace(ar);
1557                 *(&grid_unit) = NULL;  /* drawgrid need this to detect/affect smallest valid unit... */
1558                 drawgrid(&scene->unit, ar, v3d, &grid_unit);
1559
1560                 gpuLoadProjectionMatrix(rv3d->winmat);
1561                 gpuLoadMatrix(rv3d->viewmat);
1562         }
1563         else {
1564                 drawfloor(scene, v3d, &grid_unit, false);
1565         }
1566
1567         glDisable(GL_DEPTH_TEST);
1568 }
1569
1570 static bool is_cursor_visible(Scene *scene, SceneLayer *sl)
1571 {
1572         Object *ob = OBACT_NEW;
1573
1574         /* don't draw cursor in paint modes, but with a few exceptions */
1575         if (ob && ob->mode & OB_MODE_ALL_PAINT) {
1576                 /* exception: object is in weight paint and has deforming armature in pose mode */
1577                 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
1578                         if (BKE_object_pose_armature_get(ob) != NULL) {
1579                                 return true;
1580                         }
1581                 }
1582                 /* exception: object in texture paint mode, clone brush, use_clone_layer disabled */
1583                 else if (ob->mode & OB_MODE_TEXTURE_PAINT) {
1584                         const Paint *p = BKE_paint_get_active(scene, sl);
1585
1586                         if (p && p->brush && p->brush->imagepaint_tool == PAINT_TOOL_CLONE) {
1587                                 if ((scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_LAYER_CLONE) == 0) {
1588                                         return true;
1589                                 }
1590                         }
1591                 }
1592
1593                 /* no exception met? then don't draw cursor! */
1594                 return false;
1595         }
1596
1597         return true;
1598 }
1599
1600 static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
1601 {
1602         int co[2];
1603
1604         /* we don't want the clipping for cursor */
1605         if (ED_view3d_project_int_global(ar, ED_view3d_cursor3d_get(scene, v3d), co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1606                 const float f5 = 0.25f * U.widget_unit;
1607                 const float f10 = 0.5f * U.widget_unit;
1608                 const float f20 = U.widget_unit;
1609                 
1610                 glLineWidth(1.0f);
1611
1612                 VertexFormat *format = immVertexFormat();
1613                 unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1614                 unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
1615
1616                 immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1617
1618                 const int segments = 16;
1619
1620                 immBegin(PRIM_LINE_LOOP, segments);
1621
1622                 for (int i = 0; i < segments; ++i) {
1623                         float angle = 2 * M_PI * ((float)i / (float)segments);
1624                         float x = co[0] + f10 * cosf(angle);
1625                         float y = co[1] + f10 * sinf(angle);
1626
1627                         if (i % 2 == 0)
1628                                 immAttrib3ub(color, 255, 0, 0);
1629                         else
1630                                 immAttrib3ub(color, 255, 255, 255);
1631
1632                         immVertex2f(pos, x, y);
1633                 }
1634                 immEnd();
1635
1636                 immUnbindProgram();
1637
1638                 VertexFormat_clear(format);
1639                 pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1640
1641                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1642
1643                 unsigned char crosshair_color[3];
1644                 UI_GetThemeColor3ubv(TH_VIEW_OVERLAY, crosshair_color);
1645                 immUniformColor3ubv(crosshair_color);
1646
1647                 immBegin(PRIM_LINES, 8);
1648                 immVertex2f(pos, co[0] - f20, co[1]);
1649                 immVertex2f(pos, co[0] - f5, co[1]);
1650                 immVertex2f(pos, co[0] + f5, co[1]);
1651                 immVertex2f(pos, co[0] + f20, co[1]);
1652                 immVertex2f(pos, co[0], co[1] - f20);
1653                 immVertex2f(pos, co[0], co[1] - f5);
1654                 immVertex2f(pos, co[0], co[1] + f5);
1655                 immVertex2f(pos, co[0], co[1] + f20);
1656                 immEnd();
1657
1658                 immUnbindProgram();
1659         }
1660 }
1661
1662 static void draw_view_axis(RegionView3D *rv3d, rcti *rect)
1663 {
1664         const float k = U.rvisize * U.pixelsize;  /* axis size */
1665         const int bright = - 20 * (10 - U.rvibright);  /* axis alpha offset (rvibright has range 0-10) */
1666
1667         const float startx = rect->xmin + k + 1.0f;  /* axis center in screen coordinates, x=y */
1668         const float starty = rect->ymin + k + 1.0f;
1669
1670         float axis_pos[3][2];
1671         unsigned char axis_col[3][4];
1672
1673         int axis_order[3] = {0, 1, 2};
1674         axis_sort_v3(rv3d->viewinv[2], axis_order);
1675
1676         for (int axis_i = 0; axis_i < 3; axis_i++) {
1677                 int i = axis_order[axis_i];
1678
1679                 /* get position of each axis tip on screen */
1680                 float vec[3] = { 0.0f };
1681                 vec[i] = 1.0f;
1682                 mul_qt_v3(rv3d->viewquat, vec);
1683                 axis_pos[i][0] = startx + vec[0] * k;
1684                 axis_pos[i][1] = starty + vec[1] * k;
1685
1686                 /* get color of each axis */
1687                 UI_GetThemeColorShade3ubv(TH_AXIS_X + i, bright, axis_col[i]); /* rgb */
1688                 axis_col[i][3] = 255 * hypotf(vec[0], vec[1]); /* alpha */
1689         }
1690
1691         /* draw axis lines */
1692         glLineWidth(2.0f);
1693         glEnable(GL_LINE_SMOOTH);
1694         glEnable(GL_BLEND);
1695         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1696
1697         VertexFormat *format = immVertexFormat();
1698         unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
1699         unsigned int col = VertexFormat_add_attrib(format, "color", COMP_U8, 4, NORMALIZE_INT_TO_FLOAT);
1700
1701         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1702         immBegin(PRIM_LINES, 6);
1703
1704         for (int axis_i = 0; axis_i < 3; axis_i++) {
1705                 int i = axis_order[axis_i];
1706
1707                 immAttrib4ubv(col, axis_col[i]);
1708                 immVertex2f(pos, startx, starty);
1709                 immVertex2fv(pos, axis_pos[i]);
1710         }
1711
1712         immEnd();
1713         immUnbindProgram();
1714         glDisable(GL_LINE_SMOOTH);
1715
1716         /* draw axis names */
1717         for (int axis_i = 0; axis_i < 3; axis_i++) {
1718                 int i = axis_order[axis_i];
1719
1720                 const char axis_text[2] = {'x' + i, '\0'};
1721                 BLF_color4ubv(BLF_default(), axis_col[i]);
1722                 BLF_draw_default_ascii(axis_pos[i][0] + 2, axis_pos[i][1] + 2, 0.0f, axis_text, 1);
1723         }
1724 }
1725
1726 #ifdef WITH_INPUT_NDOF
1727 /* draw center and axis of rotation for ongoing 3D mouse navigation */
1728 static void draw_rotation_guide(RegionView3D *rv3d)
1729 {
1730         float o[3];    /* center of rotation */
1731         float end[3];  /* endpoints for drawing */
1732
1733         GLubyte color[4] = {0, 108, 255, 255};  /* bright blue so it matches device LEDs */
1734
1735         negate_v3_v3(o, rv3d->ofs);
1736
1737         glEnable(GL_BLEND);
1738         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1739         glDepthMask(GL_FALSE);  /* don't overwrite zbuf */
1740
1741         VertexFormat *format = immVertexFormat();
1742         unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 3, KEEP_FLOAT);
1743         unsigned int col = VertexFormat_add_attrib(format, "color", COMP_U8, 4, NORMALIZE_INT_TO_FLOAT);
1744
1745         immBindBuiltinProgram(GPU_SHADER_3D_SMOOTH_COLOR);
1746
1747         if (rv3d->rot_angle != 0.0f) {
1748                 /* -- draw rotation axis -- */
1749                 float scaled_axis[3];
1750                 const float scale = rv3d->dist;
1751                 mul_v3_v3fl(scaled_axis, rv3d->rot_axis, scale);
1752
1753
1754                 immBegin(PRIM_LINE_STRIP, 3);
1755                 color[3] = 0; /* more transparent toward the ends */
1756                 immAttrib4ubv(col, color);
1757                 add_v3_v3v3(end, o, scaled_axis);
1758                 immVertex3fv(pos, end);
1759
1760 #if 0
1761                 color[3] = 0.2f + fabsf(rv3d->rot_angle);  /* modulate opacity with angle */
1762                 /* ^^ neat idea, but angle is frame-rate dependent, so it's usually close to 0.2 */
1763 #endif
1764
1765                 color[3] = 127; /* more opaque toward the center */
1766                 immAttrib4ubv(col, color);
1767                 immVertex3fv(pos, o);
1768
1769                 color[3] = 0;
1770                 immAttrib4ubv(col, color);
1771                 sub_v3_v3v3(end, o, scaled_axis);
1772                 immVertex3fv(pos, end);
1773                 immEnd();
1774                 
1775                 /* -- draw ring around rotation center -- */
1776                 {
1777 #define     ROT_AXIS_DETAIL 13
1778
1779                         const float s = 0.05f * scale;
1780                         const float step = 2.0f * (float)(M_PI / ROT_AXIS_DETAIL);
1781
1782                         float q[4];  /* rotate ring so it's perpendicular to axis */
1783                         const int upright = fabsf(rv3d->rot_axis[2]) >= 0.95f;
1784                         if (!upright) {
1785                                 const float up[3] = {0.0f, 0.0f, 1.0f};
1786                                 float vis_angle, vis_axis[3];
1787
1788                                 cross_v3_v3v3(vis_axis, up, rv3d->rot_axis);
1789                                 vis_angle = acosf(dot_v3v3(up, rv3d->rot_axis));
1790                                 axis_angle_to_quat(q, vis_axis, vis_angle);
1791                         }
1792
1793                         immBegin(PRIM_LINE_LOOP, ROT_AXIS_DETAIL);
1794                         color[3] = 63; /* somewhat faint */
1795                         immAttrib4ubv(col, color);
1796                         float angle = 0.0f;
1797                         for (int i = 0; i < ROT_AXIS_DETAIL; ++i, angle += step) {
1798                                 float p[3] = {s * cosf(angle), s * sinf(angle), 0.0f};
1799
1800                                 if (!upright) {
1801                                         mul_qt_v3(q, p);
1802                                 }
1803
1804                                 add_v3_v3(p, o);
1805                                 immVertex3fv(pos, p);
1806                         }
1807                         immEnd();
1808
1809 #undef      ROT_AXIS_DETAIL
1810                 }
1811
1812                 color[3] = 255;  /* solid dot */
1813         }
1814         else
1815                 color[3] = 127;  /* see-through dot */
1816
1817         immUnbindProgram();
1818
1819         /* -- draw rotation center -- */
1820         immBindBuiltinProgram(GPU_SHADER_3D_POINT_FIXED_SIZE_VARYING_COLOR);
1821         glPointSize(5.0f);
1822         immBegin(PRIM_POINTS, 1);
1823         immAttrib4ubv(col, color);
1824         immVertex3fv(pos, o);
1825         immEnd();
1826         immUnbindProgram();
1827
1828 #if 0
1829         /* find screen coordinates for rotation center, then draw pretty icon */
1830         mul_m4_v3(rv3d->persinv, rot_center);
1831         UI_icon_draw(rot_center[0], rot_center[1], ICON_NDOF_TURN);
1832         /* ^^ just playing around, does not work */
1833 #endif
1834
1835         glDisable(GL_BLEND);
1836         glDepthMask(GL_TRUE);
1837 }
1838 #endif /* WITH_INPUT_NDOF */
1839
1840 /* ******************** non-meshes ***************** */
1841
1842 static void view3d_draw_non_mesh(
1843 Scene *scene, SceneLayer *sl, Object *ob, Base *base, View3D *v3d,
1844 RegionView3D *rv3d, const bool is_boundingbox, const unsigned char color[4])
1845 {
1846         gpuPushMatrix(); /* necessary? --merwin */
1847
1848         /* multiply view with object matrix.
1849          * local viewmat and persmat, to calculate projections */
1850         ED_view3d_init_mats_rv3d_gl(ob, rv3d);
1851
1852         switch (ob->type) {
1853                 case OB_MESH:
1854                 case OB_FONT:
1855                 case OB_CURVE:
1856                 case OB_SURF:
1857                 case OB_MBALL:
1858                         if (is_boundingbox) {
1859                                 draw_bounding_volume(ob, ob->boundtype, color);
1860                         }
1861                         break;
1862                 case OB_EMPTY:
1863                         drawaxes(rv3d->viewmatob, ob->empty_drawsize, ob->empty_drawtype, color);
1864                         break;
1865                 case OB_LAMP:
1866                         drawlamp(v3d, rv3d, base, OB_SOLID, DRAW_CONSTCOLOR, color, ob == OBACT_NEW);
1867                         break;
1868                 case OB_CAMERA:
1869                         drawcamera(scene, v3d, rv3d, base, DRAW_CONSTCOLOR, color);
1870                         break;
1871                 case OB_SPEAKER:
1872                         drawspeaker(color);
1873                         break;
1874                 case OB_LATTICE:
1875                         /* TODO */
1876                         break;
1877                 case OB_ARMATURE:
1878                         /* TODO */
1879                         break;
1880                 default:
1881                 /* TODO Viewport: handle the other cases*/
1882                         break;
1883         }
1884
1885         if (ob->rigidbody_object) {
1886                 draw_rigidbody_shape(ob, color);
1887         }
1888
1889         ED_view3d_clear_mats_rv3d(rv3d); /* no effect in release builds */
1890
1891         gpuPopMatrix(); /* see above */
1892 }
1893
1894 /* ******************** info ***************** */
1895
1896 /**
1897 * Render and camera border
1898 */
1899 static void view3d_draw_border(const bContext *C, ARegion *ar)
1900 {
1901         Scene *scene = CTX_data_scene(C);
1902         RegionView3D *rv3d = ar->regiondata;
1903         View3D *v3d = CTX_wm_view3d(C);
1904
1905         if (rv3d->persp == RV3D_CAMOB) {
1906                 drawviewborder(scene, ar, v3d);
1907         }
1908         else if (v3d->flag2 & V3D_RENDER_BORDER) {
1909                 drawrenderborder(ar, v3d);
1910         }
1911 }
1912
1913 /**
1914 * Grease Pencil
1915 */
1916 static void view3d_draw_grease_pencil(const bContext *UNUSED(C))
1917 {
1918         /* TODO viewport */
1919 }
1920
1921
1922 /**
1923 * Viewport Name
1924 */
1925 static const char *view3d_get_name(View3D *v3d, RegionView3D *rv3d)
1926 {
1927         const char *name = NULL;
1928
1929         switch (rv3d->view) {
1930                 case RV3D_VIEW_FRONT:
1931                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Front Ortho");
1932                         else name = IFACE_("Front Persp");
1933                         break;
1934                 case RV3D_VIEW_BACK:
1935                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Back Ortho");
1936                         else name = IFACE_("Back Persp");
1937                         break;
1938                 case RV3D_VIEW_TOP:
1939                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Top Ortho");
1940                         else name = IFACE_("Top Persp");
1941                         break;
1942                 case RV3D_VIEW_BOTTOM:
1943                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Bottom Ortho");
1944                         else name = IFACE_("Bottom Persp");
1945                         break;
1946                 case RV3D_VIEW_RIGHT:
1947                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Right Ortho");
1948                         else name = IFACE_("Right Persp");
1949                         break;
1950                 case RV3D_VIEW_LEFT:
1951                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Left Ortho");
1952                         else name = IFACE_("Left Persp");
1953                         break;
1954
1955                 default:
1956                         if (rv3d->persp == RV3D_CAMOB) {
1957                                 if ((v3d->camera) && (v3d->camera->type == OB_CAMERA)) {
1958                                         Camera *cam;
1959                                         cam = v3d->camera->data;
1960                                         if (cam->type == CAM_PERSP) {
1961                                                 name = IFACE_("Camera Persp");
1962                                         }
1963                                         else if (cam->type == CAM_ORTHO) {
1964                                                 name = IFACE_("Camera Ortho");
1965                                         }
1966                                         else {
1967                                                 BLI_assert(cam->type == CAM_PANO);
1968                                                 name = IFACE_("Camera Pano");
1969                                         }
1970                                 }
1971                                 else {
1972                                         name = IFACE_("Object as Camera");
1973                                 }
1974                         }
1975                         else {
1976                                 name = (rv3d->persp == RV3D_ORTHO) ? IFACE_("User Ortho") : IFACE_("User Persp");
1977                         }
1978         }
1979
1980         return name;
1981 }
1982
1983 static void draw_viewport_name(ARegion *ar, View3D *v3d, rcti *rect)
1984 {
1985         RegionView3D *rv3d = ar->regiondata;
1986         const char *name = view3d_get_name(v3d, rv3d);
1987         /* increase size for unicode languages (Chinese in utf-8...) */
1988 #ifdef WITH_INTERNATIONAL
1989         char tmpstr[96];
1990 #else
1991         char tmpstr[32];
1992 #endif
1993
1994         if (v3d->localvd) {
1995                 BLI_snprintf(tmpstr, sizeof(tmpstr), IFACE_("%s (Local)"), name);
1996                 name = tmpstr;
1997         }
1998
1999         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
2000 #ifdef WITH_INTERNATIONAL
2001         BLF_draw_default(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
2002 #else
2003         BLF_draw_default_ascii(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
2004 #endif
2005 }
2006
2007 /**
2008  * draw info beside axes in bottom left-corner:
2009  * framenum, object name, bone name (if available), marker name (if available)
2010  */
2011
2012 static void draw_selected_name(Scene *scene, Object *ob, rcti *rect)
2013 {
2014         const int cfra = CFRA;
2015         const char *msg_pin = " (Pinned)";
2016         const char *msg_sep = " : ";
2017
2018         const int font_id = BLF_default();
2019
2020         char info[300];
2021         char *s = info;
2022         short offset = 1.5f * UI_UNIT_X + rect->xmin;
2023
2024         s += sprintf(s, "(%d)", cfra);
2025
2026         /*
2027          * info can contain:
2028          * - a frame (7 + 2)
2029          * - 3 object names (MAX_NAME)
2030          * - 2 BREAD_CRUMB_SEPARATORs (6)
2031          * - a SHAPE_KEY_PINNED marker and a trailing '\0' (9+1) - translated, so give some room!
2032          * - a marker name (MAX_NAME + 3)
2033          */
2034
2035         /* get name of marker on current frame (if available) */
2036         const char *markern = BKE_scene_find_marker_name(scene, cfra);
2037
2038         /* check if there is an object */
2039         if (ob) {
2040                 *s++ = ' ';
2041                 s += BLI_strcpy_rlen(s, ob->id.name + 2);
2042
2043                 /* name(s) to display depends on type of object */
2044                 if (ob->type == OB_ARMATURE) {
2045                         bArmature *arm = ob->data;
2046
2047                         /* show name of active bone too (if possible) */
2048                         if (arm->edbo) {
2049                                 if (arm->act_edbone) {
2050                                         s += BLI_strcpy_rlen(s, msg_sep);
2051                                         s += BLI_strcpy_rlen(s, arm->act_edbone->name);
2052                                 }
2053                         }
2054                         else if (ob->mode & OB_MODE_POSE) {
2055                                 if (arm->act_bone) {
2056
2057                                         if (arm->act_bone->layer & arm->layer) {
2058                                                 s += BLI_strcpy_rlen(s, msg_sep);
2059                                                 s += BLI_strcpy_rlen(s, arm->act_bone->name);
2060                                         }
2061                                 }
2062                         }
2063                 }
2064                 else if (ELEM(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
2065                         /* try to display active bone and active shapekey too (if they exist) */
2066
2067                         if (ob->type == OB_MESH && ob->mode & OB_MODE_WEIGHT_PAINT) {
2068                                 Object *armobj = BKE_object_pose_armature_get(ob);
2069                                 if (armobj  && armobj->mode & OB_MODE_POSE) {
2070                                         bArmature *arm = armobj->data;
2071                                         if (arm->act_bone) {
2072                                                 if (arm->act_bone->layer & arm->layer) {
2073                                                         s += BLI_strcpy_rlen(s, msg_sep);
2074                                                         s += BLI_strcpy_rlen(s, arm->act_bone->name);
2075                                                 }
2076                                         }
2077                                 }
2078                         }
2079
2080                         Key *key = BKE_key_from_object(ob);
2081                         if (key) {
2082                                 KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1);
2083                                 if (kb) {
2084                                         s += BLI_strcpy_rlen(s, msg_sep);
2085                                         s += BLI_strcpy_rlen(s, kb->name);
2086                                         if (ob->shapeflag & OB_SHAPE_LOCK) {
2087                                                 s += BLI_strcpy_rlen(s, IFACE_(msg_pin));
2088                                         }
2089                                 }
2090                         }
2091                 }
2092
2093                 /* color depends on whether there is a keyframe */
2094                 if (id_frame_has_keyframe((ID *)ob, /* BKE_scene_frame_get(scene) */ (float)cfra, ANIMFILTER_KEYS_LOCAL))
2095                         UI_FontThemeColor(font_id, TH_TIME_KEYFRAME);
2096                 else if (ED_gpencil_has_keyframe_v3d(scene, ob, cfra))
2097                         UI_FontThemeColor(font_id, TH_TIME_GP_KEYFRAME);
2098                 else
2099                         UI_FontThemeColor(font_id, TH_TEXT_HI);
2100         }
2101         else {
2102                 /* no object */
2103                 if (ED_gpencil_has_keyframe_v3d(scene, NULL, cfra))
2104                         UI_FontThemeColor(font_id, TH_TIME_GP_KEYFRAME);
2105                 else
2106                         UI_FontThemeColor(font_id, TH_TEXT_HI);
2107         }
2108
2109         if (markern) {
2110                 s += sprintf(s, " <%s>", markern);
2111         }
2112
2113         if (U.uiflag & USER_SHOW_ROTVIEWICON)
2114                 offset = U.widget_unit + (U.rvisize * 2) + rect->xmin;
2115
2116         BLF_draw_default(offset, 0.5f * U.widget_unit, 0.0f, info, sizeof(info));
2117 }
2118
2119 /* ******************** view loop ***************** */
2120
2121 /**
2122  * Set the correct matrices
2123  */
2124 static void view3d_draw_setup_view(const bContext *C, ARegion *ar)
2125 {
2126         Scene *scene = CTX_data_scene(C);
2127         View3D *v3d = CTX_wm_view3d(C);
2128         RegionView3D *rv3d = ar->regiondata;
2129
2130         /* setup the view matrix */
2131         if (view3d_stereo3d_active(C, scene, v3d, rv3d))
2132                 view3d_stereo3d_setup(scene, v3d, ar);
2133         else
2134                 view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
2135 }
2136
2137 static void draw_all_objects(const bContext *C, ARegion *ar, const bool only_depth, const bool use_depth)
2138 {
2139         Scene *scene = CTX_data_scene(C);
2140         SceneLayer *sl = CTX_data_scene_layer(C);
2141         View3D *v3d = CTX_wm_view3d(C);
2142
2143         if (only_depth)
2144                 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
2145
2146         if (only_depth || use_depth) {
2147                 glEnable(GL_DEPTH_TEST);
2148                 glDepthFunc(GL_LESS);
2149                 glDepthMask(GL_TRUE);
2150                 v3d->zbuf = true;
2151         }
2152
2153         for (Base *base = sl->object_bases.first; base; base = base->next) {
2154                 if ((base->flag & BASE_VISIBLED) != 0) {
2155                         /* dupli drawing */
2156                         if (base->object->transflag & OB_DUPLI)
2157                                 draw_dupli_objects(scene, sl, ar, v3d, base);
2158
2159                         draw_object(scene, sl, ar, v3d, base, 0);
2160                 }
2161         }
2162
2163         if (only_depth)
2164                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2165
2166         if (only_depth || use_depth) {
2167                 glDisable(GL_DEPTH_TEST);
2168                 v3d->zbuf = false;
2169         }
2170 }
2171
2172 /**
2173  * Draw only the scene depth buffer
2174  */
2175 static void draw_depth_buffer(const bContext *C, ARegion *ar)
2176 {
2177         draw_all_objects(C, ar, true, true);
2178 }
2179
2180 /**
2181  * Required if the shaders need it or external engines
2182  * (e.g., Cycles requires depth buffer handled separately).
2183  */
2184 static void view3d_draw_prerender_buffers(const bContext *C, ARegion *ar, DrawData *draw_data)
2185 {
2186         View3D *v3d = CTX_wm_view3d(C);
2187
2188         /* TODO viewport */
2189         if (draw_data->is_render && ((!draw_data->clip_border) || (v3d->drawtype <= OB_WIRE))) {
2190                 draw_depth_buffer(C, ar);
2191         }
2192 }
2193
2194 /**
2195  * Draw all the plates that will fill the RGBD buffer
2196  */
2197 static void view3d_draw_solid_plates(const bContext *C, ARegion *ar, DrawData *draw_data)
2198 {
2199         /* realtime plates */
2200         if ((!draw_data->is_render) || draw_data->clip_border) {
2201                 view3d_draw_render_solid_surfaces(C, ar, true);
2202                 view3d_draw_render_transparent_surfaces(C);
2203                 view3d_draw_post_draw(C);
2204         }
2205
2206         /* offline plates */
2207         if (draw_data->is_render) {
2208                 Scene *scene = CTX_data_scene(C);
2209                 View3D *v3d = CTX_wm_view3d(C);
2210
2211                 /* TODO: move this outside of solid plates, after solid & before other 3D elements */
2212                 view3d_draw_render_draw(C, scene, ar, v3d, draw_data->clip_border, &draw_data->border_rect);
2213         }
2214
2215 #if VIEW3D_DRAW_DEBUG
2216         view3d_draw_debug_post_solid(C, ar, draw_data);
2217 #endif
2218 }
2219
2220 /**
2221  * Wires, outline, ...
2222  */
2223 static void view3d_draw_geometry_overlay(const bContext *C)
2224 {
2225         view3d_draw_wire_plates(C);
2226         view3d_draw_outline_plates(C);
2227 }
2228
2229 /* drawing cameras, lamps, ... */
2230 static void view3d_draw_non_meshes(const bContext *C, ARegion *ar)
2231 {
2232         /* TODO viewport
2233          * for now we draw them all, in the near future
2234          * we filter them based on the plates/layers
2235          */
2236         Scene *scene = CTX_data_scene(C);
2237         SceneLayer *sl = CTX_data_scene_layer(C);
2238         View3D *v3d = CTX_wm_view3d(C);
2239         RegionView3D *rv3d = ar->regiondata;
2240
2241         bool is_boundingbox = ((v3d->drawtype == OB_BOUNDBOX) ||
2242                                 ((v3d->drawtype == OB_RENDER) && (v3d->prev_drawtype == OB_BOUNDBOX)));
2243
2244         glEnable(GL_DEPTH_TEST);
2245         /* TODO Viewport
2246          * we are already temporarily writing to zbuffer in draw_object()
2247          * for now let's avoid writing again to zbuffer to prevent glitches
2248          */
2249
2250         for (Base *base = sl->object_bases.first; base; base = base->next) {
2251                 if ((base->flag & BASE_VISIBLED) != 0) {
2252                         Object *ob = base->object;
2253
2254                         unsigned char ob_wire_col[4];
2255                         draw_object_wire_color(scene, sl, base, ob_wire_col);
2256                         view3d_draw_non_mesh(scene, sl, ob, base, v3d, rv3d, is_boundingbox, ob_wire_col);
2257                 }
2258         }
2259
2260         glDisable(GL_DEPTH_TEST);
2261 }
2262
2263 /**
2264 * Parent lines, grid, ...
2265 */
2266 static void view3d_draw_other_elements(const bContext *C, ARegion *ar)
2267 {
2268         view3d_draw_grid(C, ar);
2269
2270 #ifdef WITH_INPUT_NDOF
2271         RegionView3D *rv3d = ar->regiondata;
2272
2273         if ((U.ndof_flag & NDOF_SHOW_GUIDE) && ((rv3d->viewlock & RV3D_LOCKED) == 0) && (rv3d->persp != RV3D_CAMOB))
2274                 /* TODO: draw something else (but not this) during fly mode */
2275                 draw_rotation_guide(rv3d);
2276 #endif
2277 }
2278
2279 /**
2280  * Paint brushes, armatures, ...
2281  */
2282 static void view3d_draw_tool_ui(const bContext *UNUSED(C))
2283 {
2284         /* TODO viewport */
2285 }
2286
2287 /**
2288  * Blueprint images
2289  */
2290 static void view3d_draw_reference_images(const bContext *UNUSED(C))
2291 {
2292         /* TODO viewport */
2293 }
2294
2295 /**
2296 * 3D manipulators
2297  */
2298 static void view3d_draw_manipulators(const bContext *C, const ARegion *ar)
2299 {
2300         View3D *v3d = CTX_wm_view3d(C);
2301         v3d->zbuf = false;
2302
2303         /* TODO, only draws 3D manipulators right now, need to see how 2D drawing will work in new viewport */
2304
2305         /* draw depth culled manipulators - manipulators need to be updated *after* view matrix was set up */
2306         /* TODO depth culling manipulators is not yet supported, just drawing _3D here, should
2307          * later become _IN_SCENE (and draw _3D separate) */
2308         WM_manipulatormap_draw(ar->manipulator_map, C, WM_MANIPULATORMAP_DRAWSTEP_3D);
2309 }
2310
2311 /**
2312 * Information drawn on top of the solid plates and composed data
2313 */
2314 void view3d_draw_region_info(const bContext *C, ARegion *ar, const int offset)
2315 {
2316         RegionView3D *rv3d = ar->regiondata;
2317         View3D *v3d = CTX_wm_view3d(C);
2318         Scene *scene = CTX_data_scene(C);
2319         wmWindowManager *wm = CTX_wm_manager(C);
2320
2321         /* correct projection matrix */
2322         ED_region_pixelspace(ar);
2323
2324         /* local coordinate visible rect inside region, to accomodate overlapping ui */
2325         rcti rect;
2326         ED_region_visible_rect(ar, &rect);
2327
2328         /* Leave room for previously drawn info. */
2329         rect.ymax -= offset;
2330
2331         view3d_draw_border(C, ar);
2332         view3d_draw_grease_pencil(C);
2333
2334         if (U.uiflag & USER_SHOW_ROTVIEWICON) {
2335                 draw_view_axis(rv3d, &rect);
2336         }
2337
2338         if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_no_scrub(wm)) {
2339                 ED_scene_draw_fps(scene, &rect);
2340         }
2341         else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
2342                 draw_viewport_name(ar, v3d, &rect);
2343         }
2344
2345         if (U.uiflag & USER_DRAWVIEWINFO) {
2346                 SceneLayer *sl = CTX_data_scene_layer(C);
2347                 Object *ob = OBACT_NEW;
2348                 draw_selected_name(scene, ob, &rect);
2349         }
2350 #if 0 /* TODO */
2351         if (grid_unit) { /* draw below the viewport name */
2352                 char numstr[32] = "";
2353
2354                 UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
2355                 if (v3d->grid != 1.0f) {
2356                         BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
2357                 }
2358
2359                 BLF_draw_default_ascii(rect.xmin + U.widget_unit,
2360                                        rect.ymax - (USER_SHOW_VIEWPORTNAME ? 2 * U.widget_unit : U.widget_unit), 0.0f,
2361                                        numstr[0] ? numstr : grid_unit, sizeof(numstr));
2362         }
2363 #endif
2364 }
2365
2366 /**
2367  * This could run once per view, or even in parallel
2368  * for each of them. What is a "view"?
2369  * - a viewport with the camera elsewhere
2370  * - left/right stereo
2371  * - panorama / fisheye individual cubemap faces
2372  */
2373 static void view3d_draw_view(const bContext *C, ARegion *ar, DrawData *draw_data)
2374 {
2375         /* TODO - Technically this should be drawn to a few FBO, so we can handle
2376          * compositing better, but for now this will get the ball rolling (dfelinto) */
2377
2378         glDepthMask(GL_TRUE); /* should be set by default */
2379         glClear(GL_DEPTH_BUFFER_BIT);
2380 //      glDisable(GL_DEPTH_TEST); /* should be set by default */
2381
2382         view3d_draw_background(C); /* clears/overwrites entire color buffer */
2383
2384         view3d_draw_setup_view(C, ar);
2385
2386         glEnable(GL_DEPTH_TEST);
2387         glDepthFunc(GL_LEQUAL);
2388         view3d_draw_prerender_buffers(C, ar, draw_data); /* depth pre-pass */
2389
2390 //      glDepthFunc(GL_EQUAL); /* TODO: do this after separating surfaces from wires */
2391 //      glDepthMask(GL_FALSE); /* same TODO as above */
2392         view3d_draw_solid_plates(C, ar, draw_data);
2393
2394 //      glDepthFunc(GL_LEQUAL); /* same TODO as above */
2395 //      glDepthMask(GL_TRUE); /* same TODO as above */
2396
2397         view3d_draw_geometry_overlay(C);
2398         view3d_draw_non_meshes(C, ar);
2399         view3d_draw_other_elements(C, ar);
2400         view3d_draw_tool_ui(C);
2401         view3d_draw_reference_images(C);
2402         view3d_draw_manipulators(C, ar);
2403
2404         glDisable(GL_DEPTH_TEST);
2405
2406         view3d_draw_region_info(C, ar, 0);
2407
2408 #if VIEW3D_DRAW_DEBUG
2409         view3d_draw_debug(C, ar, draw_data);
2410 #endif
2411 }
2412
2413 static void view3d_draw_view_new(const bContext *C, ARegion *ar, DrawData *UNUSED(draw_data))
2414 {
2415         view3d_draw_setup_view(C, ar);
2416
2417         /* Only 100% compliant on new spec goes bellow */
2418         DRW_draw_view(C);
2419 }
2420
2421 void view3d_main_region_draw(const bContext *C, ARegion *ar)
2422 {
2423         Scene *scene = CTX_data_scene(C);
2424         View3D *v3d = CTX_wm_view3d(C);
2425         RegionView3D *rv3d = ar->regiondata;
2426         /* TODO layers - In the future we should get RE from Layers */
2427         RenderEngineType *type = RE_engines_find(scene->r.engine);
2428
2429         if (IS_VIEWPORT_LEGACY(v3d) && ((type->flag & RE_USE_LEGACY_PIPELINE) != 0)) {
2430                 view3d_main_region_draw_legacy(C, ar);
2431                 return;
2432         }
2433
2434         if (!rv3d->viewport)
2435                 rv3d->viewport = GPU_viewport_create();
2436
2437         /* TODO viewport - there is so much to be done, in fact a lot will need to happen in the space_view3d.c
2438          * before we even call the drawing routine, but let's move on for now (dfelinto)
2439          * but this is a provisory way to start seeing things in the viewport */
2440         DrawData draw_data;
2441         view3d_draw_data_init(C, ar, rv3d, &draw_data);
2442
2443         GPU_viewport_bind(rv3d->viewport, &ar->winrct);
2444
2445         if ((type->flag & RE_USE_LEGACY_PIPELINE) == 0) {
2446                 view3d_draw_view_new(C, ar, &draw_data);
2447         }
2448         else {
2449                 view3d_draw_view(C, ar, &draw_data);
2450         }
2451
2452         GPU_viewport_unbind(rv3d->viewport);
2453
2454         v3d->flag |= V3D_INVALID_BACKBUF;
2455 }
2456
2457
2458 /* -------------------------------------------------------------------- */
2459
2460 /** \name Offscreen Drawing
2461  * \{ */
2462
2463 static void view3d_stereo3d_setup_offscreen(
2464         Scene *scene, View3D *v3d, ARegion *ar,
2465         float winmat[4][4], const char *viewname)
2466 {
2467         /* update the viewport matrices with the new camera */
2468         if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
2469                 float viewmat[4][4];
2470                 const bool is_left = STREQ(viewname, STEREO_LEFT_NAME);
2471
2472                 BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
2473                 view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
2474         }
2475         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
2476                 float viewmat[4][4];
2477                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
2478
2479                 BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
2480                 view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
2481         }
2482 }
2483
2484 void ED_view3d_draw_offscreen_init(Scene *scene, SceneLayer *sl, View3D *v3d)
2485 {
2486         RenderEngineType *type = RE_engines_find(scene->r.engine);
2487         if (IS_VIEWPORT_LEGACY(v3d) && ((type->flag & RE_USE_LEGACY_PIPELINE) != 0)) {
2488                 /* shadow buffers, before we setup matrices */
2489                 if (draw_glsl_material(scene, sl, NULL, v3d, v3d->drawtype)) {
2490                         VP_deprecated_gpu_update_lamps_shadows_world(scene, v3d);
2491                 }
2492         }
2493 }
2494
2495 /*
2496  * Function to clear the view
2497  */
2498 static void view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar)
2499 {
2500         glClear(GL_DEPTH_BUFFER_BIT);
2501
2502         if (scene->world && (v3d->flag3 & V3D_SHOW_WORLD)) {
2503                 VP_view3d_draw_background_world(scene, v3d, ar->regiondata);
2504         }
2505         else {
2506                 VP_view3d_draw_background_none();
2507         }
2508 }
2509
2510 /* ED_view3d_draw_offscreen_init should be called before this to initialize
2511  * stuff like shadow buffers
2512  */
2513 void ED_view3d_draw_offscreen(
2514         Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy,
2515         float viewmat[4][4], float winmat[4][4],
2516         bool do_bgpic, bool do_sky, bool is_persp, const char *viewname,
2517         GPUFX *fx, GPUFXSettings *fx_settings,
2518         GPUOffScreen *ofs)
2519 {
2520         bool do_compositing = false;
2521         RegionView3D *rv3d = ar->regiondata;
2522
2523         /* set temporary new size */
2524         int bwinx = ar->winx;
2525         int bwiny = ar->winy;
2526         rcti brect = ar->winrct;
2527
2528         ar->winx = winx;
2529         ar->winy = winy;
2530         ar->winrct.xmin = 0;
2531         ar->winrct.ymin = 0;
2532         ar->winrct.xmax = winx;
2533         ar->winrct.ymax = winy;
2534
2535         struct bThemeState theme_state;
2536         UI_Theme_Store(&theme_state);
2537         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
2538
2539         /* set flags */
2540         G.f |= G_RENDER_OGL;
2541
2542         if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
2543                 /* free images which can have changed on frame-change
2544                  * warning! can be slow so only free animated images - campbell */
2545                 GPU_free_images_anim();
2546         }
2547
2548         gpuPushProjectionMatrix();
2549         gpuLoadIdentity();
2550         gpuPushMatrix();
2551         gpuLoadIdentity();
2552
2553         /* clear opengl buffers */
2554         if (do_sky) {
2555                 view3d_main_region_clear(scene, v3d, ar);
2556         }
2557         else {
2558                 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
2559                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2560         }
2561
2562         if ((viewname != NULL && viewname[0] != '\0') && (viewmat == NULL) && rv3d->persp == RV3D_CAMOB && v3d->camera)
2563                 view3d_stereo3d_setup_offscreen(scene, v3d, ar, winmat, viewname);
2564         else
2565                 view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
2566
2567         /* main drawing call */
2568         RenderEngineType *type = RE_engines_find(scene->r.engine);
2569         if (IS_VIEWPORT_LEGACY(v3d) && ((type->flag & RE_USE_LEGACY_PIPELINE) != 0)) {
2570
2571                 /* framebuffer fx needed, we need to draw offscreen first */
2572                 if (v3d->fx_settings.fx_flag && fx) {
2573                         GPUSSAOSettings *ssao = NULL;
2574
2575                         if (v3d->drawtype < OB_SOLID) {
2576                                 ssao = v3d->fx_settings.ssao;
2577                                 v3d->fx_settings.ssao = NULL;
2578                         }
2579
2580                         do_compositing = GPU_fx_compositor_initialize_passes(fx, &ar->winrct, NULL, fx_settings);
2581
2582                         if (ssao)
2583                                 v3d->fx_settings.ssao = ssao;
2584                 }
2585
2586                 VP_deprecated_view3d_draw_objects(NULL, scene, v3d, ar, NULL, do_bgpic, true, do_compositing ? fx : NULL);
2587
2588                 /* post process */
2589                 if (do_compositing) {
2590                         if (!winmat)
2591                                 is_persp = rv3d->is_persp;
2592                         GPU_fx_do_composite_pass(fx, winmat, is_persp, scene, ofs);
2593                 }
2594
2595                 if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
2596                         /* draw grease-pencil stuff */
2597                         ED_region_pixelspace(ar);
2598
2599                         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2600                                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2601                                 ED_gpencil_draw_view3d(NULL, scene, v3d, ar, false);
2602                         }
2603
2604                         /* freeing the images again here could be done after the operator runs, leaving for now */
2605                         GPU_free_images_anim();
2606                 }
2607         }
2608         else {
2609                 /* XXX, should take depsgraph as arg */
2610                 DRW_draw_render_loop_offscreen(scene->depsgraph, ar, v3d, ofs);
2611         }
2612
2613         /* restore size */
2614         ar->winx = bwinx;
2615         ar->winy = bwiny;
2616         ar->winrct = brect;
2617
2618         gpuPopProjectionMatrix();
2619         gpuPopMatrix();
2620
2621         UI_Theme_Restore(&theme_state);
2622
2623         G.f &= ~G_RENDER_OGL;
2624 }
2625
2626 /**
2627  * Utility func for ED_view3d_draw_offscreen
2628  *
2629  * \param ofs: Optional off-screen buffer, can be NULL.
2630  * (avoids re-creating when doing multiple GL renders).
2631  */
2632 ImBuf *ED_view3d_draw_offscreen_imbuf(
2633         Scene *scene, SceneLayer *sl, View3D *v3d, ARegion *ar, int sizex, int sizey,
2634         unsigned int flag, bool draw_background,
2635         int alpha_mode, int samples, bool full_samples, const char *viewname,
2636         /* output vars */
2637         GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
2638 {
2639         RegionView3D *rv3d = ar->regiondata;
2640         const bool draw_sky = (alpha_mode == R_ADDSKY);
2641
2642         /* view state */
2643         GPUFXSettings fx_settings = v3d->fx_settings;
2644         bool is_ortho = false;
2645         float winmat[4][4];
2646
2647         if (ofs && ((GPU_offscreen_width(ofs) != sizex) || (GPU_offscreen_height(ofs) != sizey))) {
2648                 /* sizes differ, can't reuse */
2649                 ofs = NULL;
2650         }
2651
2652         const bool own_ofs = (ofs == NULL);
2653
2654         if (own_ofs) {
2655                 /* bind */
2656                 ofs = GPU_offscreen_create(sizex, sizey, full_samples ? 0 : samples, err_out);
2657                 if (ofs == NULL) {
2658                         return NULL;
2659                 }
2660         }
2661
2662         ED_view3d_draw_offscreen_init(scene, sl, v3d);
2663
2664         GPU_offscreen_bind(ofs, true);
2665
2666         /* read in pixels & stamp */
2667         ImBuf *ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
2668
2669         /* render 3d view */
2670         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
2671                 CameraParams params;
2672                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
2673
2674                 BKE_camera_params_init(&params);
2675                 /* fallback for non camera objects */
2676                 params.clipsta = v3d->near;
2677                 params.clipend = v3d->far;
2678                 BKE_camera_params_from_object(&params, camera);
2679                 BKE_camera_multiview_params(&scene->r, &params, camera, viewname);
2680                 BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
2681                 BKE_camera_params_compute_matrix(&params);
2682
2683                 BKE_camera_to_gpu_dof(camera, &fx_settings);
2684
2685                 is_ortho = params.is_ortho;
2686                 copy_m4_m4(winmat, params.winmat);
2687         }
2688         else {
2689                 rctf viewplane;
2690                 float clipsta, clipend;
2691
2692                 is_ortho = ED_view3d_viewplane_get(v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend, NULL);
2693                 if (is_ortho) {
2694                         orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend);
2695                 }
2696                 else {
2697                         perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
2698                 }
2699         }
2700
2701         if ((samples && full_samples) == 0) {
2702                 /* Single-pass render, common case */
2703                 ED_view3d_draw_offscreen(
2704                         scene, v3d, ar, sizex, sizey, NULL, winmat,
2705                         draw_background, draw_sky, !is_ortho, viewname,
2706                         fx, &fx_settings, ofs);
2707
2708                 if (ibuf->rect_float) {
2709                         GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
2710                 }
2711                 else if (ibuf->rect) {
2712                         GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
2713                 }
2714         }
2715         else {
2716                 /* Multi-pass render, use accumulation buffer & jitter for 'full' oversampling.
2717                  * Use because OpenGL may use a lower quality MSAA, and only over-sample edges. */
2718                 static float jit_ofs[32][2];
2719                 float winmat_jitter[4][4];
2720                 /* use imbuf as temp storage, before writing into it from accumulation buffer */
2721                 unsigned char *rect_temp = ibuf->rect ? (void *)ibuf->rect : (void *)ibuf->rect_float;
2722                 unsigned int *accum_buffer = MEM_mallocN(sizex * sizey * sizeof(int[4]), "accum1");
2723
2724                 BLI_jitter_init(jit_ofs, samples);
2725
2726                 /* first sample buffer, also initializes 'rv3d->persmat' */
2727                 ED_view3d_draw_offscreen(
2728                         scene, v3d, ar, sizex, sizey, NULL, winmat,
2729                         draw_background, draw_sky, !is_ortho, viewname,
2730                         fx, &fx_settings, ofs);
2731                 GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, rect_temp);
2732
2733                 unsigned i = sizex * sizey * 4;
2734                 while (i--) {
2735                         accum_buffer[i] = rect_temp[i];
2736                 }
2737
2738                 /* skip the first sample */
2739                 for (int j = 1; j < samples; j++) {
2740                         copy_m4_m4(winmat_jitter, winmat);
2741                         window_translate_m4(
2742                                 winmat_jitter, rv3d->persmat,
2743                                 (jit_ofs[j][0] * 2.0f) / sizex,
2744                                 (jit_ofs[j][1] * 2.0f) / sizey);
2745
2746                         ED_view3d_draw_offscreen(
2747                                 scene, v3d, ar, sizex, sizey, NULL, winmat_jitter,
2748                                 draw_background, draw_sky, !is_ortho, viewname,
2749                                 fx, &fx_settings, ofs);
2750                         GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, rect_temp);
2751
2752                         i = sizex * sizey * 4;
2753                         while (i--) {
2754                                 accum_buffer[i] += rect_temp[i];
2755                         }
2756                 }
2757
2758                 if (ibuf->rect_float) {
2759                         float *rect_float = ibuf->rect_float;
2760                         i = sizex * sizey * 4;
2761                         while (i--) {
2762                                 rect_float[i] = (float)(accum_buffer[i] / samples) * (1.0f / 255.0f);
2763                         }
2764                 }
2765                 else {
2766                         unsigned char *rect_ub = (unsigned char *)ibuf->rect;
2767                         i = sizex * sizey * 4;
2768                         while (i--) {
2769                                 rect_ub[i] = accum_buffer[i] / samples;
2770                         }
2771                 }
2772
2773                 MEM_freeN(accum_buffer);
2774         }
2775
2776         /* unbind */
2777         GPU_offscreen_unbind(ofs, true);
2778
2779         if (own_ofs) {
2780                 GPU_offscreen_free(ofs);
2781         }
2782
2783         if (ibuf->rect_float && ibuf->rect)
2784                 IMB_rect_from_float(ibuf);
2785
2786         return ibuf;
2787 }
2788
2789 /**
2790  * Creates own fake 3d views (wrapping #ED_view3d_draw_offscreen_imbuf)
2791  *
2792  * \param ofs: Optional off-screen buffer can be NULL.
2793  * (avoids re-creating when doing multiple GL renders).
2794  *
2795  * \note used by the sequencer
2796  */
2797 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(
2798         Scene *scene, SceneLayer *sl, Object *camera, int width, int height,
2799         unsigned int flag, int drawtype, bool use_solid_tex, bool use_gpencil, bool draw_background,
2800         int alpha_mode, int samples, bool full_samples, const char *viewname,
2801         GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
2802 {
2803         View3D v3d = {NULL};
2804         ARegion ar = {NULL};
2805         RegionView3D rv3d = {{{0}}};
2806
2807         /* connect data */
2808         v3d.regionbase.first = v3d.regionbase.last = &ar;
2809         ar.regiondata = &rv3d;
2810         ar.regiontype = RGN_TYPE_WINDOW;
2811
2812         v3d.camera = camera;
2813         v3d.lay = scene->lay;
2814         v3d.drawtype = drawtype;
2815         v3d.flag2 = V3D_RENDER_OVERRIDE;
2816
2817         if (use_gpencil)
2818                 v3d.flag2 |= V3D_SHOW_GPENCIL;
2819
2820         if (use_solid_tex)
2821                 v3d.flag2 |= V3D_SOLID_TEX;
2822
2823         if (draw_background)
2824                 v3d.flag3 |= V3D_SHOW_WORLD;
2825
2826         rv3d.persp = RV3D_CAMOB;
2827
2828         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2829         normalize_m4(rv3d.viewinv);
2830         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2831
2832         {
2833                 CameraParams params;
2834                 Object *view_camera = BKE_camera_multiview_render(scene, v3d.camera, viewname);
2835
2836                 BKE_camera_params_init(&params);
2837                 BKE_camera_params_from_object(&params, view_camera);
2838                 BKE_camera_multiview_params(&scene->r, &params, view_camera, viewname);
2839                 BKE_camera_params_compute_viewplane(&params, width, height, scene->r.xasp, scene->r.yasp);
2840                 BKE_camera_params_compute_matrix(&params);
2841
2842                 copy_m4_m4(rv3d.winmat, params.winmat);
2843                 v3d.near = params.clipsta;
2844                 v3d.far = params.clipend;
2845                 v3d.lens = params.lens;
2846         }
2847
2848         mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2849         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2850
2851         return ED_view3d_draw_offscreen_imbuf(
2852                 scene, sl, &v3d, &ar, width, height, flag,
2853                 draw_background, alpha_mode, samples, full_samples, viewname,
2854                 fx, ofs, err_out);
2855 }
2856
2857 /** \} */
2858
2859
2860 /* -------------------------------------------------------------------- */
2861
2862 /** \name Legacy Interface
2863  *
2864  * This will be removed once the viewport gets replaced
2865  * meanwhile it should keep the old viewport working.
2866  *
2867  * \{ */
2868
2869 void VP_legacy_drawcursor(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d)
2870 {
2871         if (is_cursor_visible(scene, sl)) {
2872                 drawcursor(scene, ar, v3d);
2873         }
2874 }
2875
2876 void VP_legacy_draw_view_axis(RegionView3D *rv3d, rcti *rect)
2877 {
2878         draw_view_axis(rv3d, rect);
2879 }
2880
2881 void VP_legacy_draw_viewport_name(ARegion *ar, View3D *v3d, rcti *rect)
2882 {
2883         draw_viewport_name(ar, v3d, rect);
2884 }
2885
2886 void VP_legacy_draw_selected_name(Scene *scene, Object *ob, rcti *rect)
2887 {
2888         draw_selected_name(scene, ob, rect);
2889 }
2890
2891 void VP_legacy_drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
2892 {
2893         drawgrid(unit, ar, v3d, grid_unit);
2894 }
2895
2896 void VP_legacy_drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
2897 {
2898         drawfloor(scene, v3d, grid_unit, write_depth);
2899 }
2900
2901 void VP_legacy_view3d_main_region_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
2902 {
2903         view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
2904 }
2905
2906 bool VP_legacy_view3d_stereo3d_active(const bContext *C, Scene *scene, View3D *v3d, RegionView3D *rv3d)
2907 {
2908         return view3d_stereo3d_active(C, scene, v3d, rv3d);
2909 }
2910
2911 void VP_legacy_view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar)
2912 {
2913         view3d_stereo3d_setup(scene, v3d, ar);
2914 }
2915
2916 bool VP_legacy_use_depth(Scene *scene, View3D *v3d)
2917 {
2918         return use_depth_doit(scene, v3d);
2919 }
2920
2921 void VP_drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
2922 {
2923         drawviewborder(scene, ar, v3d);
2924 }
2925
2926 void VP_drawrenderborder(ARegion *ar, View3D *v3d)
2927 {
2928         drawrenderborder(ar, v3d);
2929 }
2930
2931 void VP_view3d_draw_background_none(void)
2932 {
2933         if (UI_GetThemeValue(TH_SHOW_BACK_GRAD)) {
2934                 view3d_draw_background_gradient();
2935         }
2936         else {
2937                 view3d_draw_background_none();
2938         }
2939 }
2940
2941 void VP_view3d_draw_background_world(Scene *scene, View3D *v3d, RegionView3D *rv3d)
2942 {
2943         view3d_draw_background_world(scene, v3d, rv3d);
2944 }
2945
2946 void VP_view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar)
2947 {
2948         view3d_main_region_clear(scene, v3d, ar);
2949 }
2950
2951 /** \} */