Merge remote-tracking branch 'origin/master' into blender2.8
authorDalai Felinto <dfelinto@gmail.com>
Wed, 10 May 2017 13:25:26 +0000 (15:25 +0200)
committerDalai Felinto <dfelinto@gmail.com>
Wed, 10 May 2017 13:40:08 +0000 (15:40 +0200)
Note: Depth placement was working already for BI, and althugh this
commit breaks it for it, it makes it work for the draw manager engines.

1  2 
source/blender/editors/include/ED_view3d.h
source/blender/editors/space_view3d/view3d_draw.c
source/blender/editors/space_view3d/view3d_draw_legacy.c

index 24a1b06d940d4d5dd9e10c0f6beb1654dab31f82,bd0dd72bf7001b4fa4a9ce116b035d092c0a7269..ecd2cd9a2676d12caaf31b6fb9295e5a289960ff
@@@ -361,9 -356,12 +361,12 @@@ void ED_view3d_draw_offscreen
          float winmat[4][4], bool do_bgpic, bool do_sky, bool is_persp, const char *viewname,
          struct GPUFX *fx, struct GPUFXSettings *fx_settings,
          struct GPUOffScreen *ofs);
+ void ED_view3d_draw_setup_view(
+         struct wmWindow *win, struct Scene *scene, struct ARegion *ar, struct View3D *v3d,
+         float viewmat[4][4], float winmat[4][4]);
  
  struct ImBuf *ED_view3d_draw_offscreen_imbuf(
 -        struct Scene *scene, struct View3D *v3d, struct ARegion *ar, int sizex, int sizey,
 +        struct Scene *scene, struct SceneLayer *sl, struct View3D *v3d, struct ARegion *ar, int sizex, int sizey,
          unsigned int flag, bool draw_background,
          int alpha_mode, int samples, bool full_samples, const char *viewname,
          struct GPUFX *fx, struct GPUOffScreen *ofs, char err_out[256]);
index b54681dfde40bd0d5cf636a7dfdbe346ce6ad2e7,cd2a6fe0feb27b092cdad2f65e4732f8ed284768..fad3f73fcd7bb0f8c768d4bacce947f05e7a24e5
  #include "view3d_intern.h"  /* own include */
  
  /* prototypes */
 -static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar);
 -static void view3d_stereo3d_setup_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
 -                                            float winmat[4][4], const char *viewname);
 -
 -/* handy utility for drawing shapes in the viewport for arbitrary code.
 - * could add lines and points too */
 -// #define DEBUG_DRAW
 -#ifdef DEBUG_DRAW
 -static void bl_debug_draw(void);
 -/* add these locally when using these functions for testing */
 -extern void bl_debug_draw_quad_clear(void);
 -extern void bl_debug_draw_quad_add(const float v0[3], const float v1[3], const float v2[3], const float v3[3]);
 -extern void bl_debug_draw_edge_add(const float v0[3], const float v1[3]);
 -extern void bl_debug_color_set(const unsigned int col);
 -#endif
 +static void draw_all_objects(const bContext *C, ARegion *ar, const bool only_depth, const bool use_depth);
+ static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d);
  
 -void circf(float x, float y, float rad)
 -{
 -      GLUquadricObj *qobj = gluNewQuadric(); 
 -      
 -      gluQuadricDrawStyle(qobj, GLU_FILL); 
 -      
 -      glPushMatrix(); 
 -      
 -      glTranslatef(x, y, 0.0);
 -      
 -      gluDisk(qobj, 0.0,  rad, 32, 1);
 -      
 -      glPopMatrix(); 
 -      
 -      gluDeleteQuadric(qobj);
 -}
 +typedef struct DrawData {
 +      rcti border_rect;
 +      bool render_border;
 +      bool clip_border;
 +      bool is_render;
 +      GPUViewport *viewport;
 +} DrawData;
  
 -void circ(float x, float y, float rad)
 +static void view3d_draw_data_init(const bContext *C, ARegion *ar, RegionView3D *rv3d, DrawData *draw_data)
  {
 -      GLUquadricObj *qobj = gluNewQuadric(); 
 -      
 -      gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
 -      
 -      glPushMatrix(); 
 -      
 -      glTranslatef(x, y, 0.0);
 -      
 -      gluDisk(qobj, 0.0,  rad, 32, 1);
 -      
 -      glPopMatrix(); 
 -      
 -      gluDeleteQuadric(qobj);
 -}
 -
 +      Scene *scene = CTX_data_scene(C);
 +      View3D *v3d = CTX_wm_view3d(C);
  
 -/* ********* custom clipping *********** */
 +      draw_data->is_render = (v3d->drawtype == OB_RENDER);
  
 -static void view3d_draw_clipping(RegionView3D *rv3d)
 -{
 -      BoundBox *bb = rv3d->clipbb;
 -
 -      if (bb) {
 -              const unsigned int clipping_index[6][4] = {
 -                      {0, 1, 2, 3},
 -                      {0, 4, 5, 1},
 -                      {4, 7, 6, 5},
 -                      {7, 3, 2, 6},
 -                      {1, 5, 6, 2},
 -                      {7, 4, 0, 3}
 -              };
 -
 -              /* fill in zero alpha for rendering & re-projection [#31530] */
 -              unsigned char col[4];
 -              UI_GetThemeColor4ubv(TH_V3D_CLIPPING_BORDER, col);
 -              glColor4ubv(col);
 -
 -              glEnable(GL_BLEND);
 -              glEnableClientState(GL_VERTEX_ARRAY);
 -              glVertexPointer(3, GL_FLOAT, 0, bb->vec);
 -              glDrawElements(GL_QUADS, sizeof(clipping_index) / sizeof(unsigned int), GL_UNSIGNED_INT, clipping_index);
 -              glDisableClientState(GL_VERTEX_ARRAY);
 -              glDisable(GL_BLEND);
 -      }
 -}
 +      draw_data->render_border = ED_view3d_calc_render_border(scene, v3d, ar, &draw_data->border_rect);
 +      draw_data->clip_border = (draw_data->render_border && !BLI_rcti_compare(&ar->drawrct, &draw_data->border_rect));
  
 -void ED_view3d_clipping_set(RegionView3D *rv3d)
 -{
 -      double plane[4];
 -      const unsigned int tot = (rv3d->viewlock & RV3D_BOXCLIP) ? 4 : 6;
 -      unsigned int a;
 -
 -      for (a = 0; a < tot; a++) {
 -              copy_v4db_v4fl(plane, rv3d->clip[a]);
 -              glClipPlane(GL_CLIP_PLANE0 + a, plane);
 -              glEnable(GL_CLIP_PLANE0 + a);
 -      }
 +      draw_data->viewport = rv3d->viewport;
  }
  
 -/* use these to temp disable/enable clipping when 'rv3d->rflag & RV3D_CLIPPING' is set */
 -void ED_view3d_clipping_disable(void)
 -{
 -      unsigned int a;
 +/* ******************** general functions ***************** */
  
 -      for (a = 0; a < 6; a++) {
 -              glDisable(GL_CLIP_PLANE0 + a);
 -      }
 -}
 -void ED_view3d_clipping_enable(void)
 +static bool use_depth_doit(Scene *scene, View3D *v3d)
  {
 -      unsigned int a;
 +      if (v3d->drawtype > OB_WIRE)
 +              return true;
  
 -      for (a = 0; a < 6; a++) {
 -              glEnable(GL_CLIP_PLANE0 + a);
 +      /* special case (depth for wire color) */
 +      if (v3d->drawtype <= OB_WIRE) {
 +              if (scene->obedit && scene->obedit->type == OB_MESH) {
 +                      Mesh *me = scene->obedit->data;
 +                      if (me->drawflag & ME_DRAWEIGHT) {
 +                              return true;
 +                      }
 +              }
        }
 +      return false;
  }
  
 -static bool view3d_clipping_test(const float co[3], const float clip[6][4])
 +static bool use_depth(const bContext *C)
  {
 -      if (plane_point_side_v3(clip[0], co) > 0.0f)
 -              if (plane_point_side_v3(clip[1], co) > 0.0f)
 -                      if (plane_point_side_v3(clip[2], co) > 0.0f)
 -                              if (plane_point_side_v3(clip[3], co) > 0.0f)
 -                                      return false;
 -
 -      return true;
 +      View3D *v3d = CTX_wm_view3d(C);
 +      Scene *scene = CTX_data_scene(C);
 +      return use_depth_doit(scene, v3d);
  }
  
 -/* for 'local' ED_view3d_clipping_local must run first
 - * then all comparisons can be done in localspace */
 -bool ED_view3d_clipping_test(const RegionView3D *rv3d, const float co[3], const bool is_local)
 +/**
 + * \note keep this synced with #ED_view3d_mats_rv3d_backup/#ED_view3d_mats_rv3d_restore
 + */
 +void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
  {
 -      return view3d_clipping_test(co, is_local ? rv3d->clip_local : rv3d->clip);
 -}
 +      RegionView3D *rv3d = ar->regiondata;
  
 -/* ********* end custom clipping *********** */
  
 +      /* setup window matrices */
 +      if (winmat)
 +              copy_m4_m4(rv3d->winmat, winmat);
 +      else
 +              view3d_winmatrix_set(ar, v3d, NULL);
  
 -static void drawgrid_draw(ARegion *ar, double wx, double wy, double x, double y, double dx)
 -{     
 -      double verts[2][2];
 +      /* setup view matrix */
 +      if (viewmat)
 +              copy_m4_m4(rv3d->viewmat, viewmat);
 +      else
 +              view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
  
 -      x += (wx);
 -      y += (wy);
 +      /* update utility matrices */
 +      mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
 +      invert_m4_m4(rv3d->persinv, rv3d->persmat);
 +      invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
  
 -      /* set fixed 'Y' */
 -      verts[0][1] = 0.0f;
 -      verts[1][1] = (double)ar->winy;
 +      /* calculate GLSL view dependent values */
  
 -      /* iter over 'X' */
 -      verts[0][0] = verts[1][0] = x - dx * floor(x / dx);
 -      glEnableClientState(GL_VERTEX_ARRAY);
 -      glVertexPointer(2, GL_DOUBLE, 0, verts);
 +      /* store window coordinates scaling/offset */
 +      if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
 +              rctf cameraborder;
 +              ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &cameraborder, false);
 +              rv3d->viewcamtexcofac[0] = (float)ar->winx / BLI_rctf_size_x(&cameraborder);
 +              rv3d->viewcamtexcofac[1] = (float)ar->winy / BLI_rctf_size_y(&cameraborder);
  
 -      while (verts[0][0] < ar->winx) {
 -              glDrawArrays(GL_LINES, 0, 2);
 -              verts[0][0] = verts[1][0] = verts[0][0] + dx;
 +              rv3d->viewcamtexcofac[2] = -rv3d->viewcamtexcofac[0] * cameraborder.xmin / (float)ar->winx;
 +              rv3d->viewcamtexcofac[3] = -rv3d->viewcamtexcofac[1] * cameraborder.ymin / (float)ar->winy;
 +      }
 +      else {
 +              rv3d->viewcamtexcofac[0] = rv3d->viewcamtexcofac[1] = 1.0f;
 +              rv3d->viewcamtexcofac[2] = rv3d->viewcamtexcofac[3] = 0.0f;
        }
  
 -      /* set fixed 'X' */
 -      verts[0][0] = 0.0f;
 -      verts[1][0] = (double)ar->winx;
 +      /* calculate pixelsize factor once, is used for lamps and obcenters */
 +      {
 +              /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
 +               * because of float point precision problems at large values [#23908] */
 +              float v1[3], v2[3];
 +              float len_px, len_sc;
  
 -      /* iter over 'Y' */
 -      verts[0][1] = verts[1][1] = y - dx * floor(y / dx);
 -      while (verts[0][1] < ar->winy) {
 -              glDrawArrays(GL_LINES, 0, 2);
 -              verts[0][1] = verts[1][1] = verts[0][1] + dx;
 -      }
 +              v1[0] = rv3d->persmat[0][0];
 +              v1[1] = rv3d->persmat[1][0];
 +              v1[2] = rv3d->persmat[2][0];
  
 -      glDisableClientState(GL_VERTEX_ARRAY);
 -}
 +              v2[0] = rv3d->persmat[0][1];
 +              v2[1] = rv3d->persmat[1][1];
 +              v2[2] = rv3d->persmat[2][1];
  
 -#define GRID_MIN_PX_D   6.0
 -#define GRID_MIN_PX_F 6.0f
 +              len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
 +              len_sc = (float)MAX2(ar->winx, ar->winy);
  
 -static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
 +              rv3d->pixsize = len_px / len_sc;
 +      }
 +}
 +
 +static void view3d_main_region_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
  {
 -      /* extern short bgpicmode; */
        RegionView3D *rv3d = ar->regiondata;
 -      double wx, wy, x, y, fw, fx, fy, dx;
 -      double vec4[4];
 -      unsigned char col[3], col2[3];
  
 -      fx = rv3d->persmat[3][0];
 -      fy = rv3d->persmat[3][1];
 -      fw = rv3d->persmat[3][3];
 +      ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat);
  
 -      wx = (ar->winx / 2.0); /* because of rounding errors, grid at wrong location */
 -      wy = (ar->winy / 2.0);
 +      /* set for opengl */
 +      gpuLoadProjectionMatrix(rv3d->winmat);
 +      gpuLoadMatrix(rv3d->viewmat);
 +}
  
- static bool view3d_stereo3d_active(const bContext *C, Scene *scene, View3D *v3d, RegionView3D *rv3d)
 -      x = (wx) * fx / fw;
 -      y = (wy) * fy / fw;
++static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d)
 +{
-       wmWindow *win = CTX_wm_window(C);
-       if ((scene->r.scemode & R_MULTIVIEW) == 0)
-               return false;
-       if (WM_stereo3d_enabled(win, true) == false)
++      if ((scene->r.scemode & R_MULTIVIEW) == 0) {
 +              return false;
++      }
  
-       if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB)
 -      vec4[0] = vec4[1] = v3d->grid;
++      if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB) {
 +              return false;
++      }
  
-       if (scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) {
-               if (v3d->stereo3d_camera == STEREO_MONO_ID)
 -      vec4[2] = 0.0;
 -      vec4[3] = 1.0;
 -      mul_m4_v4d(rv3d->persmat, vec4);
 -      fx = vec4[0];
 -      fy = vec4[1];
 -      fw = vec4[3];
++      switch (v3d->stereo3d_camera) {
++              case STEREO_MONO_ID:
 +                      return false;
-               return BKE_scene_multiview_is_stereo3d(&scene->r);
++                      break;
++              case STEREO_3D_ID:
++                      /* win will be NULL when calling this from the selection or draw loop. */
++                      if ((win == NULL) || (WM_stereo3d_enabled(win, true) == false)) {
++                              return false;
++                      }
++                      if (((scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) != 0) &&
++                          !BKE_scene_multiview_is_stereo3d(&scene->r))
++                      {
++                              return false;
++                      }
++                      break;
++              /* We always need the stereo calculation for left and right cameras. */
++              case STEREO_LEFT_ID:
++              case STEREO_RIGHT_ID:
++              default:
++                      break;
 +      }
 +      return true;
 +}
  
 -      dx = fabs(x - (wx) * fx / fw);
 -      if (dx == 0) dx = fabs(y - (wy) * fy / fw);
 -      
 -      glLineWidth(1.0f);
 -      glDepthMask(GL_FALSE);     /* disable write in zbuffer */
 +/* setup the view and win matrices for the multiview cameras
 + *
 + * unlike view3d_stereo3d_setup_offscreen, when view3d_stereo3d_setup is called
 + * we have no winmatrix (i.e., projection matrix) defined at that time.
 + * Since the camera and the camera shift are needed for the winmat calculation
 + * we do a small hack to replace it temporarily so we don't need to change the
 + * view3d)main_region_setup_view() code to account for that.
 + */
 +static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar)
 +{
 +      bool is_left;
 +      const char *names[2] = { STEREO_LEFT_NAME, STEREO_RIGHT_NAME };
 +      const char *viewname;
  
 -      /* check zoom out */
 -      UI_ThemeColor(TH_GRID);
 -      
 -      if (unit->system) {
 -              /* Use GRID_MIN_PX * 2 for units because very very small grid
 -               * items are less useful when dealing with units */
 -              const void *usys;
 -              int len, i;
 -              double dx_scalar;
 -              float blend_fac;
 +      /* show only left or right camera */
 +      if (v3d->stereo3d_camera != STEREO_3D_ID)
 +              v3d->multiview_eye = v3d->stereo3d_camera;
  
 -              bUnit_GetSystem(unit->system, B_UNIT_LENGTH, &usys, &len);
 +      is_left = v3d->multiview_eye == STEREO_LEFT_ID;
 +      viewname = names[is_left ? STEREO_LEFT_ID : STEREO_RIGHT_ID];
  
 -              if (usys) {
 -                      i = len;
 -                      while (i--) {
 -                              double scalar = bUnit_GetScaler(usys, i);
 +      /* update the viewport matrices with the new camera */
 +      if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
 +              Camera *data;
 +              float viewmat[4][4];
 +              float shiftx;
  
 -                              dx_scalar = dx * scalar / (double)unit->scale_length;
 -                              if (dx_scalar < (GRID_MIN_PX_D * 2.0))
 -                                      continue;
 +              data = (Camera *)v3d->camera->data;
 +              shiftx = data->shiftx;
  
 -                              /* Store the smallest drawn grid size units name so users know how big each grid cell is */
 -                              if (*grid_unit == NULL) {
 -                                      *grid_unit = bUnit_GetNameDisplay(usys, i);
 -                                      rv3d->gridview = (float)((scalar * (double)v3d->grid) / (double)unit->scale_length);
 -                              }
 -                              blend_fac = 1.0f - ((GRID_MIN_PX_F * 2.0f) / (float)dx_scalar);
 +              BLI_lock_thread(LOCK_VIEW3D);
 +              data->shiftx = BKE_camera_multiview_shift_x(&scene->r, v3d->camera, viewname);
  
 -                              /* tweak to have the fade a bit nicer */
 -                              blend_fac = (blend_fac * blend_fac) * 2.0f;
 -                              CLAMP(blend_fac, 0.3f, 1.0f);
 +              BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
 +              view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
 +
 +              data->shiftx = shiftx;
 +              BLI_unlock_thread(LOCK_VIEW3D);
 +      }
 +      else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
 +              float viewmat[4][4];
 +              Object *view_ob = v3d->camera;
 +              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
  
 +              BLI_lock_thread(LOCK_VIEW3D);
 +              v3d->camera = camera;
  
 -                              UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, blend_fac);
 +              BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
 +              view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
  
 -                              drawgrid_draw(ar, wx, wy, x, y, dx_scalar);
 -                      }
 -              }
 +              v3d->camera = view_ob;
 +              BLI_unlock_thread(LOCK_VIEW3D);
 +      }
 +}
 +
++/**
++ * Set the correct matrices
++ */
++void ED_view3d_draw_setup_view(wmWindow *win, Scene *scene, ARegion *ar, View3D *v3d, float viewmat[4][4], float winmat[4][4])
++{
++      RegionView3D *rv3d = ar->regiondata;
++
++      /* Setup the view matrix. */
++      if (view3d_stereo3d_active(win, scene, v3d, rv3d)) {
++              view3d_stereo3d_setup(scene, v3d, ar);
+       }
+       else {
 -              const double sublines    = v3d->gridsubdiv;
 -              const float  sublines_fl = v3d->gridsubdiv;
++              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
++      }
++}
 -              if (dx < GRID_MIN_PX_D) {
 -                      rv3d->gridview *= sublines_fl;
 -                      dx *= sublines;
 +/* ******************** debug ***************** */
  
 -                      if (dx < GRID_MIN_PX_D) {
 -                              rv3d->gridview *= sublines_fl;
 -                              dx *= sublines;
 +#define VIEW3D_DRAW_DEBUG 1
 +/* TODO: expand scope of this flag so UI reflects the underlying code */
  
 -                              if (dx < GRID_MIN_PX_D) {
 -                                      rv3d->gridview *= sublines_fl;
 -                                      dx *= sublines;
 -                                      if (dx < GRID_MIN_PX_D) {
 -                                              /* pass */
 -                                      }
 -                                      else {
 -                                              UI_ThemeColor(TH_GRID);
 -                                              drawgrid_draw(ar, wx, wy, x, y, dx);
 -                                      }
 -                              }
 -                              else {  /* start blending out */
 -                                      UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                                      drawgrid_draw(ar, wx, wy, x, y, dx);
 +#if VIEW3D_DRAW_DEBUG
  
 -                                      UI_ThemeColor(TH_GRID);
 -                                      drawgrid_draw(ar, wx, wy, x, y, sublines * dx);
 -                              }
 -                      }
 -                      else {  /* start blending out (GRID_MIN_PX < dx < (GRID_MIN_PX * 10)) */
 -                              UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                              drawgrid_draw(ar, wx, wy, x, y, dx);
 +static void view3d_draw_debug_store_depth(ARegion *UNUSED(ar), DrawData *draw_data)
 +{
 +      GPUViewport *viewport = draw_data->viewport;
 +      GLint viewport_size[4];
 +      glGetIntegerv(GL_VIEWPORT, viewport_size);
  
 -                              UI_ThemeColor(TH_GRID);
 -                              drawgrid_draw(ar, wx, wy, x, y, sublines * dx);
 -                      }
 -              }
 -              else {
 -                      if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
 -                              rv3d->gridview /= sublines_fl;
 -                              dx /= sublines;
 -                              if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
 -                                      rv3d->gridview /= sublines_fl;
 -                                      dx /= sublines;
 -                                      if (dx > (GRID_MIN_PX_D * 10.0)) {
 -                                              UI_ThemeColor(TH_GRID);
 -                                              drawgrid_draw(ar, wx, wy, x, y, dx);
 -                                      }
 -                                      else {
 -                                              UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                                              drawgrid_draw(ar, wx, wy, x, y, dx);
 -                                              UI_ThemeColor(TH_GRID);
 -                                              drawgrid_draw(ar, wx, wy, x, y, dx * sublines);
 -                                      }
 -                              }
 -                              else {
 -                                      UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                                      drawgrid_draw(ar, wx, wy, x, y, dx);
 -                                      UI_ThemeColor(TH_GRID);
 -                                      drawgrid_draw(ar, wx, wy, x, y, dx * sublines);
 -                              }
 -                      }
 -                      else {
 -                              UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
 -                              drawgrid_draw(ar, wx, wy, x, y, dx);
 -                              UI_ThemeColor(TH_GRID);
 -                              drawgrid_draw(ar, wx, wy, x, y, dx * sublines);
 -                      }
 +      const int x = viewport_size[0];
 +      const int y = viewport_size[1];
 +      const int w = viewport_size[2];
 +      const int h = viewport_size[3];
 +
 +      if (GPU_viewport_debug_depth_is_valid(viewport)) {
 +              if ((GPU_viewport_debug_depth_width(viewport) != w) ||
 +                  (GPU_viewport_debug_depth_height(viewport) != h))
 +              {
 +                      GPU_viewport_debug_depth_free(viewport);
                }
        }
  
@@@ -685,977 -912,1560 +714,970 @@@ static void drawviewborder(Scene *scene
                                }
                        }
                }
 -              else if (ELEM(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
 -                      Key *key = NULL;
 -                      KeyBlock *kb = NULL;
  
 -                      /* try to display active bone and active shapekey too (if they exist) */
 +              if (ca->flag & CAM_SHOWSENSOR) {
 +                      /* determine sensor fit, and get sensor x/y, for auto fit we
 +                       * assume and square sensor and only use sensor_x */
 +                      float sizex = scene->r.xsch * scene->r.xasp;
 +                      float sizey = scene->r.ysch * scene->r.yasp;
 +                      int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
 +                      float sensor_x = ca->sensor_x;
 +                      float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
  
 -                      if (ob->type == OB_MESH && ob->mode & OB_MODE_WEIGHT_PAINT) {
 -                              Object *armobj = BKE_object_pose_armature_get(ob);
 -                              if (armobj  && armobj->mode & OB_MODE_POSE) {
 -                                      bArmature *arm = armobj->data;
 -                                      if (arm->act_bone) {
 -                                              if (arm->act_bone->layer & arm->layer) {
 -                                                      s += BLI_strcpy_rlen(s, msg_sep);
 -                                                      s += BLI_strcpy_rlen(s, arm->act_bone->name);
 -                                              }
 -                                      }
 -                              }
 +                      /* determine sensor plane */
 +                      rctf rect;
 +
 +                      if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
 +                              float sensor_scale = (x2i - x1i) / sensor_x;
 +                              float sensor_height = sensor_scale * sensor_y;
 +
 +                              rect.xmin = x1i;
 +                              rect.xmax = x2i;
 +                              rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
 +                              rect.ymax = rect.ymin + sensor_height;
                        }
 +                      else {
 +                              float sensor_scale = (y2i - y1i) / sensor_y;
 +                              float sensor_width = sensor_scale * sensor_x;
  
 -                      key = BKE_key_from_object(ob);
 -                      if (key) {
 -                              kb = BLI_findlink(&key->block, ob->shapenr - 1);
 -                              if (kb) {
 -                                      s += BLI_strcpy_rlen(s, msg_sep);
 -                                      s += BLI_strcpy_rlen(s, kb->name);
 -                                      if (ob->shapeflag & OB_SHAPE_LOCK) {
 -                                              s += BLI_strcpy_rlen(s, IFACE_(msg_pin));
 -                                      }
 -                              }
 +                              rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
 +                              rect.xmax = rect.xmin + sensor_width;
 +                              rect.ymin = y1i;
 +                              rect.ymax = y2i;
                        }
 +
 +                      /* draw */
 +                      immUniformThemeColorShade(TH_VIEW_OVERLAY, 100);
 +
 +                      /* TODO Was using UI_draw_roundbox_4fv(false, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f, color).
 +                       * We'll probably need a new imm_draw_line_roundbox_dashed dor that - though in practice the
 +                       * 2.0f round corner effect was nearly not visible anyway... */
 +                      imm_draw_line_box(shdr_pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
                }
 -              
 -              /* color depends on whether there is a keyframe */
 -              if (id_frame_has_keyframe((ID *)ob, /* BKE_scene_frame_get(scene) */ (float)cfra, ANIMFILTER_KEYS_LOCAL))
 -                      UI_ThemeColor(TH_TIME_KEYFRAME);
 -              else if (ED_gpencil_has_keyframe_v3d(scene, ob, cfra))
 -                      UI_ThemeColor(TH_TIME_GP_KEYFRAME);
 -              else
 -                      UI_ThemeColor(TH_TEXT_HI);
 -      }
 -      else {
 -              /* no object */
 -              if (ED_gpencil_has_keyframe_v3d(scene, NULL, cfra))
 -                      UI_ThemeColor(TH_TIME_GP_KEYFRAME);
 -              else
 -                      UI_ThemeColor(TH_TEXT_HI);
 -      }
  
 -      if (markern) {
 -              s += sprintf(s, " <%s>", markern);
 +              immUnbindProgram();
        }
 -      
 -      if (U.uiflag & USER_SHOW_ROTVIEWICON)
 -              offset = U.widget_unit + (U.rvisize * 2) + rect->xmin;
  
 -      BLF_draw_default(offset, 0.5f * U.widget_unit, 0.0f, info, sizeof(info));
 +      /* camera name - draw in highlighted text color */
 +      if (ca && (ca->flag & CAM_SHOWNAME)) {
 +              UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
 +              BLF_draw_default(x1i, y1i - (0.7f * U.widget_unit), 0.0f,
 +                               v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
 +      }
  }
  
 -static void view3d_camera_border(
 -        const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
 -        rctf *r_viewborder, const bool no_shift, const bool no_zoom)
 +static void drawrenderborder(ARegion *ar, View3D *v3d)
  {
 -      CameraParams params;
 -      rctf rect_view, rect_camera;
 +      /* use the same program for everything */
 +      uint shdr_pos = VertexFormat_add_attrib(immVertexFormat(), "pos", COMP_F32, 2, KEEP_FLOAT);
  
 -      /* get viewport viewplane */
 -      BKE_camera_params_init(&params);
 -      BKE_camera_params_from_view3d(&params, v3d, rv3d);
 -      if (no_zoom)
 -              params.zoom = 1.0f;
 -      BKE_camera_params_compute_viewplane(&params, ar->winx, ar->winy, 1.0f, 1.0f);
 -      rect_view = params.viewplane;
 +      glLineWidth(1.0f);
  
 -      /* get camera viewplane */
 -      BKE_camera_params_init(&params);
 -      /* fallback for non camera objects */
 -      params.clipsta = v3d->near;
 -      params.clipend = v3d->far;
 -      BKE_camera_params_from_object(&params, v3d->camera);
 -      if (no_shift) {
 -              params.shiftx = 0.0f;
 -              params.shifty = 0.0f;
 -      }
 -      BKE_camera_params_compute_viewplane(&params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
 -      rect_camera = params.viewplane;
 +      immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_COLOR);
  
 -      /* get camera border within viewport */
 -      r_viewborder->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
 -      r_viewborder->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
 -      r_viewborder->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
 -      r_viewborder->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
 -}
 +      float viewport_size[4];
 +      glGetFloatv(GL_VIEWPORT, viewport_size);
 +      immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
  
 -void ED_view3d_calc_camera_border_size(
 -        const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
 -        float r_size[2])
 -{
 -      rctf viewborder;
 +      immUniform1i("num_colors", 0);  /* "simple" mode */
 +      immUniform4f("color", 1.0f, 0.25f, 0.25f, 1.0f);
 +      immUniform1f("dash_width", 6.0f);
 +      immUniform1f("dash_factor", 0.5f);
  
 -      view3d_camera_border(scene, ar, v3d, rv3d, &viewborder, true, true);
 -      r_size[0] = BLI_rctf_size_x(&viewborder);
 -      r_size[1] = BLI_rctf_size_y(&viewborder);
 -}
 +      imm_draw_line_box(shdr_pos,
 +                        v3d->render_border.xmin * ar->winx, v3d->render_border.ymin * ar->winy,
 +                        v3d->render_border.xmax * ar->winx, v3d->render_border.ymax * ar->winy);
  
 -void ED_view3d_calc_camera_border(
 -        const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
 -        rctf *r_viewborder, const bool no_shift)
 -{
 -      view3d_camera_border(scene, ar, v3d, rv3d, r_viewborder, no_shift, false);
 +      immUnbindProgram();
  }
  
 -static void drawviewborder_grid3(float x1, float x2, float y1, float y2, float fac)
 +void ED_view3d_draw_depth(
 +        struct Depsgraph *graph,
 +        ARegion *ar, View3D *v3d, bool alphaoverride)
  {
 -      float x3, y3, x4, y4;
 +      Scene *scene = DAG_get_scene(graph);
 +      RegionView3D *rv3d = ar->regiondata;
  
 -      x3 = x1 + fac * (x2 - x1);
 -      y3 = y1 + fac * (y2 - y1);
 -      x4 = x1 + (1.0f - fac) * (x2 - x1);
 -      y4 = y1 + (1.0f - fac) * (y2 - y1);
 +      short zbuf = v3d->zbuf;
 +      short flag = v3d->flag;
 +      float glalphaclip = U.glalphaclip;
 +      int obcenter_dia = U.obcenter_dia;
 +      /* temp set drawtype to solid */
 +      /* Setting these temporarily is not nice */
 +      v3d->flag &= ~V3D_SELECT_OUTLINE;
 +      U.glalphaclip = alphaoverride ? 0.5f : glalphaclip; /* not that nice but means we wont zoom into billboards */
 +      U.obcenter_dia = 0;
  
-       view3d_winmatrix_set(ar, v3d, NULL);
-       view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
-       mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
-       invert_m4_m4(rv3d->persinv, rv3d->persmat);
-       invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
 -      glBegin(GL_LINES);
 -      glVertex2f(x1, y3);
 -      glVertex2f(x2, y3);
++      ED_view3d_draw_setup_view(NULL, scene, ar, v3d, NULL, NULL);
  
 -      glVertex2f(x1, y4);
 -      glVertex2f(x2, y4);
 +      glClear(GL_DEPTH_BUFFER_BIT);
  
-       gpuLoadMatrix(rv3d->viewmat);
 -      glVertex2f(x3, y1);
 -      glVertex2f(x3, y2);
 +      if (rv3d->rflag & RV3D_CLIPPING) {
 +              ED_view3d_clipping_set(rv3d);
 +      }
 +      /* get surface depth without bias */
 +      rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
  
 -      glVertex2f(x4, y1);
 -      glVertex2f(x4, y2);
 -      glEnd();
 -}
 +      v3d->zbuf = true;
 +      glEnable(GL_DEPTH_TEST);
  
 -/* harmonious triangle */
 -static void drawviewborder_triangle(float x1, float x2, float y1, float y2, const char golden, const char dir)
 -{
 -      float ofs;
 -      float w = x2 - x1;
 -      float h = y2 - y1;
 +#ifdef WITH_OPENGL_LEGACY
 +      if (IS_VIEWPORT_LEGACY(vc->v3d)) {
 +              /* temp, calls into view3d_draw_legacy.c */
 +              ED_view3d_draw_depth_loop(scene, ar, v3d);
 +      }
 +      else
 +#endif /* WITH_OPENGL_LEGACY */
 +      {
 +              DRW_draw_depth_loop(graph, ar, v3d);
 +      }
  
 -      glBegin(GL_LINES);
 -      if (w > h) {
 -              if (golden) {
 -                      ofs = w * (1.0f - (1.0f / 1.61803399f));
 -              }
 -              else {
 -                      ofs = h * (h / w);
 -              }
 -              if (dir == 'B') SWAP(float, y1, y2);
 +      if (rv3d->rflag & RV3D_CLIPPING) {
 +              ED_view3d_clipping_disable();
 +      }
 +      rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
  
 -              glVertex2f(x1, y1);
 -              glVertex2f(x2, y2);
 +      v3d->zbuf = zbuf;
 +      if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
  
 -              glVertex2f(x2, y1);
 -              glVertex2f(x1 + (w - ofs), y2);
 +      U.glalphaclip = glalphaclip;
 +      v3d->flag = flag;
 +      U.obcenter_dia = obcenter_dia;
 +}
  
 -              glVertex2f(x1, y2);
 -              glVertex2f(x1 + ofs, y1);
 -      }
 -      else {
 -              if (golden) {
 -                      ofs = h * (1.0f - (1.0f / 1.61803399f));
 -              }
 -              else {
 -                      ofs = w * (w / h);
 -              }
 -              if (dir == 'B') SWAP(float, x1, x2);
 +/* ******************** offline engine ***************** */
  
 -              glVertex2f(x1, y1);
 -              glVertex2f(x2, y2);
 +static bool view3d_draw_render_draw(const bContext *C, Scene *scene,
 +    ARegion *ar, View3D *UNUSED(v3d),
 +    bool clip_border, const rcti *border_rect)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
 +      RenderEngineType *type;
 +      GLint scissor[4];
  
 -              glVertex2f(x2, y1);
 -              glVertex2f(x1, y1 + ofs);
 +      /* create render engine */
 +      if (!rv3d->render_engine) {
 +              RenderEngine *engine;
  
 -              glVertex2f(x1, y2);
 -              glVertex2f(x2, y1 + (h - ofs));
 -      }
 -      glEnd();
 -}
 +              type = RE_engines_find(scene->r.engine);
  
 -static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      float x1, x2, y1, y2;
 -      float x1i, x2i, y1i, y2i;
 +              if (!(type->view_update && type->render_to_view))
 +                      return false;
  
 -      rctf viewborder;
 -      Camera *ca = NULL;
 -      RegionView3D *rv3d = ar->regiondata;
 +              engine = RE_engine_create_ex(type, true);
  
 -      if (v3d->camera == NULL)
 -              return;
 -      if (v3d->camera->type == OB_CAMERA)
 -              ca = v3d->camera->data;
 -      
 -      ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
 -      /* the offsets */
 -      x1 = viewborder.xmin;
 -      y1 = viewborder.ymin;
 -      x2 = viewborder.xmax;
 -      y2 = viewborder.ymax;
 -      
 -      glLineWidth(1.0f);
 +              engine->tile_x = scene->r.tilex;
 +              engine->tile_y = scene->r.tiley;
  
 -      /* apply offsets so the real 3D camera shows through */
 +              type->view_update(engine, C);
  
 -      /* note: quite un-scientific but without this bit extra
 -       * 0.0001 on the lower left the 2D border sometimes
 -       * obscures the 3D camera border */
 -      /* note: with VIEW3D_CAMERA_BORDER_HACK defined this error isn't noticeable
 -       * but keep it here in case we need to remove the workaround */
 -      x1i = (int)(x1 - 1.0001f);
 -      y1i = (int)(y1 - 1.0001f);
 -      x2i = (int)(x2 + (1.0f - 0.0001f));
 -      y2i = (int)(y2 + (1.0f - 0.0001f));
 -      
 -      /* passepartout, specified in camera edit buttons */
 -      if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
 -              const float winx = (ar->winx + 1);
 -              const float winy = (ar->winy + 1);
 -
 -              if (ca->passepartalpha == 1.0f) {
 -                      glColor3f(0, 0, 0);
 +              rv3d->render_engine = engine;
 +      }
 +
 +      /* rendered draw */
 +      gpuPushMatrix();
 +      float original_proj[4][4];
 +      gpuGetProjectionMatrix(original_proj);
 +      ED_region_pixelspace(ar);
 +
 +      if (clip_border) {
 +              /* for border draw, we only need to clear a subset of the 3d view */
 +              if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
 +                      glGetIntegerv(GL_SCISSOR_BOX, scissor);
 +                      glScissor(border_rect->xmin, border_rect->ymin,
 +                              BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
                }
                else {
 -                      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 -                      glEnable(GL_BLEND);
 -                      glColor4f(0, 0, 0, ca->passepartalpha);
 +                      return false;
                }
 -
 -              if (x1i > 0.0f)
 -                      glRectf(0.0, winy, x1i, 0.0);
 -              if (x2i < winx)
 -                      glRectf(x2i, winy, winx, 0.0);
 -              if (y2i < winy)
 -                      glRectf(x1i, winy, x2i, y2i);
 -              if (y2i > 0.0f)
 -                      glRectf(x1i, y1i, x2i, 0.0);
 -              
 -              glDisable(GL_BLEND);
        }
  
 -      setlinestyle(0);
 +      /* don't change depth buffer */
 +      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
 +      glClear(GL_COLOR_BUFFER_BIT); /* is this necessary? -- merwin */
  
 -      UI_ThemeColor(TH_BACK);
 -              
 -      fdrawbox(x1i, y1i, x2i, y2i);
 +      /* render result draw */
 +      type = rv3d->render_engine->type;
 +      type->render_to_view(rv3d->render_engine, C);
  
 -#ifdef VIEW3D_CAMERA_BORDER_HACK
 -      if (view3d_camera_border_hack_test == true) {
 -              glColor3ubv(view3d_camera_border_hack_col);
 -              fdrawbox(x1i + 1, y1i + 1, x2i - 1, y2i - 1);
 -              view3d_camera_border_hack_test = false;
 +      if (clip_border) {
 +              /* restore scissor as it was before */
 +              glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
        }
 -#endif
 -
 -      setlinestyle(3);
  
 -      /* outer line not to confuse with object selecton */
 -      if (v3d->flag2 & V3D_LOCK_CAMERA) {
 -              UI_ThemeColor(TH_REDALERT);
 -              fdrawbox(x1i - 1, y1i - 1, x2i + 1, y2i + 1);
 -      }
 +      gpuLoadProjectionMatrix(original_proj);
 +      gpuPopMatrix();
  
 -      UI_ThemeColor(TH_VIEW_OVERLAY);
 -      fdrawbox(x1i, y1i, x2i, y2i);
 +      return true;
 +}
  
 -      /* border */
 -      if (scene->r.mode & R_BORDER) {
 -              float x3, y3, x4, y4;
 +/* ******************** background plates ***************** */
  
 -              x3 = floorf(x1 + (scene->r.border.xmin * (x2 - x1))) - 1;
 -              y3 = floorf(y1 + (scene->r.border.ymin * (y2 - y1))) - 1;
 -              x4 = floorf(x1 + (scene->r.border.xmax * (x2 - x1))) + (U.pixelsize - 1);
 -              y4 = floorf(y1 + (scene->r.border.ymax * (y2 - y1))) + (U.pixelsize - 1);
 +static void view3d_draw_background_gradient(void)
 +{
 +      /* TODO: finish 2D API & draw background with that */
  
 -              cpack(0x4040FF);
 -              sdrawbox(x3,  y3,  x4,  y4);
 -      }
 +      VertexFormat *format = immVertexFormat();
 +      unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
 +      unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
 +      unsigned char col_hi[3], col_lo[3];
  
 -      /* safety border */
 -      if (ca) {
 -              if (ca->dtx & CAM_DTX_CENTER) {
 -                      float x3, y3;
 +      immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR);
  
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 +      UI_GetThemeColor3ubv(TH_LOW_GRAD, col_lo);
 +      UI_GetThemeColor3ubv(TH_HIGH_GRAD, col_hi);
  
 -                      x3 = x1 + 0.5f * (x2 - x1);
 -                      y3 = y1 + 0.5f * (y2 - y1);
 +      immBegin(PRIM_TRIANGLE_FAN, 4);
 +      immAttrib3ubv(color, col_lo);
 +      immVertex2f(pos, -1.0f, -1.0f);
 +      immVertex2f(pos, 1.0f, -1.0f);
  
 -                      glBegin(GL_LINES);
 -                      glVertex2f(x1, y3);
 -                      glVertex2f(x2, y3);
 +      immAttrib3ubv(color, col_hi);
 +      immVertex2f(pos, 1.0f, 1.0f);
 +      immVertex2f(pos, -1.0f, 1.0f);
 +      immEnd();
  
 -                      glVertex2f(x3, y1);
 -                      glVertex2f(x3, y2);
 -                      glEnd();
 -              }
 +      immUnbindProgram();
 +}
  
 -              if (ca->dtx & CAM_DTX_CENTER_DIAG) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 +static void view3d_draw_background_none(void)
 +{
 +      UI_ThemeClearColorAlpha(TH_HIGH_GRAD, 1.0f);
 +      glClear(GL_COLOR_BUFFER_BIT);
 +}
  
 -                      glBegin(GL_LINES);
 -                      glVertex2f(x1, y1);
 -                      glVertex2f(x2, y2);
 +static void view3d_draw_background_world(Scene *scene, View3D *v3d, RegionView3D *rv3d)
 +{
 +      if (scene->world) {
 +              GPUMaterial *gpumat = GPU_material_world(scene, scene->world);
  
 -                      glVertex2f(x1, y2);
 -                      glVertex2f(x2, y1);
 +              /* calculate full shader for background */
 +              GPU_material_bind(gpumat, 1, 1, 1.0f, false, rv3d->viewmat, rv3d->viewinv, rv3d->viewcamtexcofac, (v3d->scenelock != 0));
 +
 +              if (GPU_material_bound(gpumat)) {
 +                      /* TODO viewport (dfelinto): GPU_material_bind relies on immediate mode,
 +                       * we can't get rid of the following code without a bigger refactor
 +                       * or we dropping this functionality. */
 +
 +                      glBegin(GL_TRIANGLE_STRIP);
 +                      glVertex2f(-1.0f, -1.0f);
 +                      glVertex2f(1.0f, -1.0f);
 +                      glVertex2f(-1.0f, 1.0f);
 +                      glVertex2f(1.0f, 1.0f);
                        glEnd();
 -              }
  
 -              if (ca->dtx & CAM_DTX_THIRDS) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_grid3(x1, x2, y1, y2, 1.0f / 3.0f);
 -              }
 -
 -              if (ca->dtx & CAM_DTX_GOLDEN) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_grid3(x1, x2, y1, y2, 1.0f - (1.0f / 1.61803399f));
 +                      GPU_material_unbind(gpumat);
 +                      return;
                }
 +      }
  
 -              if (ca->dtx & CAM_DTX_GOLDEN_TRI_A) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_triangle(x1, x2, y1, y2, 0, 'A');
 -              }
 +      /* if any of the above fails */
 +      view3d_draw_background_none();
 +}
  
 -              if (ca->dtx & CAM_DTX_GOLDEN_TRI_B) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_triangle(x1, x2, y1, y2, 0, 'B');
 -              }
 +/* ******************** solid plates ***************** */
  
 -              if (ca->dtx & CAM_DTX_HARMONY_TRI_A) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_triangle(x1, x2, y1, y2, 1, 'A');
 -              }
 +/**
 + * Clear the buffer and draw the proper shader
 + */
 +static void view3d_draw_background(const bContext *C)
 +{
 +      Scene *scene = CTX_data_scene(C);
 +      View3D *v3d = CTX_wm_view3d(C);
 +      RegionView3D *rv3d = CTX_wm_region_view3d(C);
  
 -              if (ca->dtx & CAM_DTX_HARMONY_TRI_B) {
 -                      UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
 -                      drawviewborder_triangle(x1, x2, y1, y2, 1, 'B');
 -              }
 +      /* Background functions do not read or write depth, but they do clear or completely
 +       * overwrite color buffer.
 +       */
  
 -              if (ca->flag & CAM_SHOW_SAFE_MARGINS) {
 -                      UI_draw_safe_areas(
 -                              x1, x2, y1, y2,
 -                              scene->safe_areas.title,
 -                              scene->safe_areas.action);
 -
 -                      if (ca->flag & CAM_SHOW_SAFE_CENTER) {
 -                              UI_draw_safe_areas(
 -                                      x1, x2, y1, y2,
 -                                      scene->safe_areas.title_center,
 -                                      scene->safe_areas.action_center);
 -                      }
 -              }
 +      switch (v3d->debug.background) {
 +              case V3D_DEBUG_BACKGROUND_WORLD:
 +                      view3d_draw_background_world(scene, v3d, rv3d);
 +                      break;
 +              case V3D_DEBUG_BACKGROUND_GRADIENT:
 +                      view3d_draw_background_gradient();
 +                      break;
 +              case V3D_DEBUG_BACKGROUND_NONE:
 +              default:
 +                      view3d_draw_background_none();
 +      }
 +}
  
 -              if (ca->flag & CAM_SHOWSENSOR) {
 -                      /* determine sensor fit, and get sensor x/y, for auto fit we
 -                       * assume and square sensor and only use sensor_x */
 -                      float sizex = scene->r.xsch * scene->r.xasp;
 -                      float sizey = scene->r.ysch * scene->r.yasp;
 -                      int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
 -                      float sensor_x = ca->sensor_x;
 -                      float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
 +/**
 + *
 + */
 +static void view3d_draw_render_solid_surfaces(const bContext *C, ARegion *ar, const bool UNUSED(run_screen_shaders))
 +{
 +      /* TODO viewport */
 +      draw_all_objects(C, ar, false, use_depth(C));
 +}
  
 -                      /* determine sensor plane */
 -                      rctf rect;
 +/**
 + *
 + */
 +static void view3d_draw_render_transparent_surfaces(const bContext *UNUSED(C))
 +{
 +      /* TODO viewport */
 +}
  
 -                      if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
 -                              float sensor_scale = (x2i - x1i) / sensor_x;
 -                              float sensor_height = sensor_scale * sensor_y;
 +/**
 + *
 + */
 +static void view3d_draw_post_draw(const bContext *UNUSED(C))
 +{
 +      /* TODO viewport */
 +}
  
 -                              rect.xmin = x1i;
 -                              rect.xmax = x2i;
 -                              rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
 -                              rect.ymax = rect.ymin + sensor_height;
 -                      }
 -                      else {
 -                              float sensor_scale = (y2i - y1i) / sensor_y;
 -                              float sensor_width = sensor_scale * sensor_x;
 +/* ******************** geometry overlay ***************** */
  
 -                              rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
 -                              rect.xmax = rect.xmin + sensor_width;
 -                              rect.ymin = y1i;
 -                              rect.ymax = y2i;
 -                      }
 +/**
 + * Front/back wire frames
 + */
 +static void view3d_draw_wire_plates(const bContext *UNUSED(C))
 +{
 +      /* TODO viewport */
 +}
  
 -                      /* draw */
 -                      UI_ThemeColorShade(TH_VIEW_OVERLAY, 100);
 -                      UI_draw_roundbox_gl_mode(GL_LINE_LOOP, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f);
 -              }
 -      }
 +/**
 + * Special treatment for selected objects
 + */
 +static void view3d_draw_outline_plates(const bContext *UNUSED(C))
 +{
 +      /* TODO viewport */
 +}
  
 -      setlinestyle(0);
 +/* ******************** other elements ***************** */
  
 -      /* camera name - draw in highlighted text color */
 -      if (ca && (ca->flag & CAM_SHOWNAME)) {
 -              UI_ThemeColor(TH_TEXT_HI);
 -              BLF_draw_default(
 -                      x1i, y1i - (0.7f * U.widget_unit), 0.0f,
 -                      v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
 -      }
 -}
  
 -/* *********************** backdraw for selection *************** */
 +#define DEBUG_GRID 0
  
 -static void backdrawview3d(Scene *scene, wmWindow *win, ARegion *ar, View3D *v3d)
 +static void gridline_range(double x0, double dx, double max, int *r_first, int *r_count)
  {
 -      RegionView3D *rv3d = ar->regiondata;
 -      struct Base *base = scene->basact;
 -      int multisample_enabled;
 +      /* determine range of gridlines that appear in this Area -- similar calc but separate ranges for x & y
 +       * x0 is gridline 0, the axis in screen space
 +       * Area covers [0 .. max) pixels */
  
 -      BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
 +      int first = (int)ceil(-x0 / dx);
 +      int last = (int)floor((max - x0) / dx);
  
 -      if (base && (base->object->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
 -                   BKE_paint_select_face_test(base->object)))
 -      {
 -              /* do nothing */
 -      }
 -      /* texture paint mode sampling */
 -      else if (base && (base->object->mode & OB_MODE_TEXTURE_PAINT) &&
 -               (v3d->drawtype > OB_WIRE))
 -      {
 -              /* do nothing */
 -      }
 -      else if ((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) &&
 -               V3D_IS_ZBUF(v3d))
 -      {
 -              /* do nothing */
 -      }
 -      else if (scene->obedit &&
 -               V3D_IS_ZBUF(v3d))
 -      {
 -              /* do nothing */
 +      if (first <= last) {
 +              *r_first = first;
 +              *r_count = last - first + 1;
        }
        else {
 -              v3d->flag &= ~V3D_INVALID_BACKBUF;
 -              return;
 +              *r_first = 0;
 +              *r_count = 0;
        }
  
 -      if (!(v3d->flag & V3D_INVALID_BACKBUF))
 -              return;
 -
 -#if 0
 -      if (test) {
 -              if (qtest()) {
 -                      addafterqueue(ar->win, BACKBUFDRAW, 1);
 -                      return;
 -              }
 -      }
 +#if DEBUG_GRID
 +      printf("   first %d * dx = %f\n", first, x0 + first * dx);
 +      printf("   last %d * dx = %f\n", last, x0 + last * dx);
 +      printf("   count = %d\n", *count_out);
  #endif
 +}
  
 -      if (v3d->drawtype > OB_WIRE) v3d->zbuf = true;
 -      
 -      /* dithering and AA break color coding, so disable */
 -      glDisable(GL_DITHER);
 -
 -      multisample_enabled = glIsEnabled(GL_MULTISAMPLE);
 -      if (multisample_enabled)
 -              glDisable(GL_MULTISAMPLE);
 -
 -      if (win->multisamples != USER_MULTISAMPLE_NONE) {
 -              /* for multisample we use an offscreen FBO. multisample drawing can fail
 -               * with color coded selection drawing, and reading back depths from such
 -               * a buffer can also cause a few seconds freeze on OS X / NVidia. */
 -              int w = BLI_rcti_size_x(&ar->winrct);
 -              int h = BLI_rcti_size_y(&ar->winrct);
 -              char error[256];
 -
 -              if (rv3d->gpuoffscreen) {
 -                      if (GPU_offscreen_width(rv3d->gpuoffscreen)  != w ||
 -                          GPU_offscreen_height(rv3d->gpuoffscreen) != h)
 -                      {
 -                              GPU_offscreen_free(rv3d->gpuoffscreen);
 -                              rv3d->gpuoffscreen = NULL;
 -                      }
 -              }
 -
 -              if (!rv3d->gpuoffscreen) {
 -                      rv3d->gpuoffscreen = GPU_offscreen_create(w, h, 0, error);
 +static int gridline_count(ARegion *ar, double x0, double y0, double dx)
 +{
 +      /* x0 & y0 establish the "phase" of the grid within this 2D region
 +       * dx is the frequency, shared by x & y directions
 +       * pass in dx of smallest (highest precision) grid we want to draw */
  
 -                      if (!rv3d->gpuoffscreen)
 -                              fprintf(stderr, "Failed to create offscreen selection buffer for multisample: %s\n", error);
 -              }
 -      }
 +#if DEBUG_GRID
 +      printf("  %s(%f, %f, dx:%f)\n", __FUNCTION__, x0, y0, dx);
 +#endif
  
 -      if (rv3d->gpuoffscreen)
 -              GPU_offscreen_bind(rv3d->gpuoffscreen, true);
 -      else
 -              glScissor(ar->winrct.xmin, ar->winrct.ymin, BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
 +      int first, x_ct, y_ct;
  
 -      glClearColor(0.0, 0.0, 0.0, 0.0);
 -      if (v3d->zbuf) {
 -              glEnable(GL_DEPTH_TEST);
 -              glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 -      }
 -      else {
 -              glClear(GL_COLOR_BUFFER_BIT);
 -              glDisable(GL_DEPTH_TEST);
 -      }
 -      
 -      if (rv3d->rflag & RV3D_CLIPPING)
 -              ED_view3d_clipping_set(rv3d);
 -      
 -      G.f |= G_BACKBUFSEL;
 -      
 -      if (base && (base->lay & v3d->lay))
 -              draw_object_backbufsel(scene, v3d, rv3d, base->object);
 -      
 -      if (rv3d->gpuoffscreen)
 -              GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
 -      else
 -              ar->swap = 0; /* mark invalid backbuf for wm draw */
 +      gridline_range(x0, dx, ar->winx, &first, &x_ct);
 +      gridline_range(y0, dx, ar->winy, &first, &y_ct);
  
 -      v3d->flag &= ~V3D_INVALID_BACKBUF;
 +      int total_ct = x_ct + y_ct;
  
 -      G.f &= ~G_BACKBUFSEL;
 -      v3d->zbuf = false;
 -      glDisable(GL_DEPTH_TEST);
 -      glEnable(GL_DITHER);
 -      if (multisample_enabled)
 -              glEnable(GL_MULTISAMPLE);
 +#if DEBUG_GRID
 +      printf("   %d + %d = %d gridlines\n", x_ct, y_ct, total_ct);
 +#endif
  
 -      if (rv3d->rflag & RV3D_CLIPPING)
 -              ED_view3d_clipping_disable();
 +      return total_ct;
  }
  
 -void view3d_opengl_read_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
 +static bool drawgrid_draw(ARegion *ar, double x0, double y0, double dx, int skip_mod, unsigned pos, unsigned col, GLubyte col_value[3])
  {
 -      RegionView3D *rv3d = ar->regiondata;
 +      /* skip every skip_mod lines relative to each axis; they will be overlaid by another drawgrid_draw
 +       * always skip exact x0 & y0 axes; they will be drawn later in color
 +       *
 +       * set grid color once, just before the first line is drawn
 +       * it's harmless to set same color for every line, or every vertex
 +       * but if no lines are drawn, color must not be set! */
  
 -      if (rv3d->gpuoffscreen) {
 -              GPU_offscreen_bind(rv3d->gpuoffscreen, true);
 -              glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
 -              glReadPixels(x, y, w, h, format, type, data);
 -              GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
 -      }
 -      else {
 -              glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
 -      }
 -}
 -
 -/* XXX depth reading exception, for code not using gpu offscreen */
 -static void view3d_opengl_read_Z_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
 -{
 -
 -      glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
 -}
 +#if DEBUG_GRID
 +      printf("  %s(%f, %f, dx:%f, skip_mod:%d)\n", __FUNCTION__, x0, y0, dx, skip_mod);
 +#endif
  
 -void ED_view3d_backbuf_validate(ViewContext *vc)
 -{
 -      if (vc->v3d->flag & V3D_INVALID_BACKBUF)
 -              backdrawview3d(vc->scene, vc->win, vc->ar, vc->v3d);
 -}
 +      const float x_max = (float)ar->winx;
 +      const float y_max = (float)ar->winy;
  
 -/**
 - * allow for small values [0.5 - 2.5],
 - * and large values, FLT_MAX by clamping by the area size
 - */
 -int ED_view3d_backbuf_sample_size_clamp(ARegion *ar, const float dist)
 -{
 -      return (int)min_ff(ceilf(dist), (float)max_ii(ar->winx, ar->winx));
 -}
 +      int first, ct;
 +      int x_ct = 0, y_ct = 0; /* count of lines actually drawn */
 +      int lines_skipped_for_next_unit = 0;
  
 -/* samples a single pixel (copied from vpaint) */
 -unsigned int ED_view3d_backbuf_sample(ViewContext *vc, int x, int y)
 -{
 -      unsigned int col;
 -      
 -      if (x >= vc->ar->winx || y >= vc->ar->winy) {
 -              return 0;
 -      }
 +      /* draw vertical lines */
 +      gridline_range(x0, dx, x_max, &first, &ct);
  
 -      ED_view3d_backbuf_validate(vc);
 +      for (int i = first; i < first + ct; ++i) {
 +              if (i == 0)
 +                      continue;
 +              else if (skip_mod && (i % skip_mod) == 0) {
 +                      ++lines_skipped_for_next_unit;
 +                      continue;
 +              }
  
 -      view3d_opengl_read_pixels(vc->ar, x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &col);
 -      glReadBuffer(GL_BACK);
 -      
 -      if (ENDIAN_ORDER == B_ENDIAN) {
 -              BLI_endian_switch_uint32(&col);
 -      }
 -      
 -      return GPU_select_to_index(col);
 -}
 +              if (x_ct == 0)
 +                      immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
  
 -/* reads full rect, converts indices */
 -ImBuf *ED_view3d_backbuf_read(ViewContext *vc, int xmin, int ymin, int xmax, int ymax)
 -{
 -      struct ImBuf *ibuf_clip;
 -      /* clip */
 -      const rcti clip = {
 -          max_ii(xmin, 0), min_ii(xmax, vc->ar->winx - 1),
 -          max_ii(ymin, 0), min_ii(ymax, vc->ar->winy - 1)};
 -      const int size_clip[2] = {
 -          BLI_rcti_size_x(&clip) + 1,
 -          BLI_rcti_size_y(&clip) + 1};
 -
 -      if (UNLIKELY((clip.xmin > clip.xmax) ||
 -                   (clip.ymin > clip.ymax)))
 -      {
 -              return NULL;
 +              float x = (float)(x0 + i * dx);
 +              immVertex2f(pos, x, 0.0f);
 +              immVertex2f(pos, x, y_max);
 +              ++x_ct;
        }
  
 -      ibuf_clip = IMB_allocImBuf(size_clip[0], size_clip[1], 32, IB_rect);
 -
 -      ED_view3d_backbuf_validate(vc);
 +      /* draw horizontal lines */
 +      gridline_range(y0, dx, y_max, &first, &ct);
  
 -      view3d_opengl_read_pixels(vc->ar, clip.xmin, clip.ymin, size_clip[0], size_clip[1], GL_RGBA, GL_UNSIGNED_BYTE, ibuf_clip->rect);
 -
 -      glReadBuffer(GL_BACK);
 +      for (int i = first; i < first + ct; ++i) {
 +              if (i == 0)
 +                      continue;
 +              else if (skip_mod && (i % skip_mod) == 0) {
 +                      ++lines_skipped_for_next_unit;
 +                      continue;
 +              }
  
 -      if (ENDIAN_ORDER == B_ENDIAN) {
 -              IMB_convert_rgba_to_abgr(ibuf_clip);
 -      }
 +              if (x_ct + y_ct == 0)
 +                      immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
  
 -      GPU_select_to_index_array(ibuf_clip->rect, size_clip[0] * size_clip[1]);
 -      
 -      if ((clip.xmin == xmin) &&
 -          (clip.xmax == xmax) &&
 -          (clip.ymin == ymin) &&
 -          (clip.ymax == ymax))
 -      {
 -              return ibuf_clip;
 -      }
 -      else {
 -              /* put clipped result into a non-clipped buffer */
 -              struct ImBuf *ibuf_full;
 -              const int size[2] = {
 -                  (xmax - xmin + 1),
 -                  (ymax - ymin + 1)};
 -
 -              ibuf_full = IMB_allocImBuf(size[0], size[1], 32, IB_rect);
 -
 -              IMB_rectcpy(
 -                      ibuf_full, ibuf_clip,
 -                      clip.xmin - xmin, clip.ymin - ymin,
 -                      0, 0,
 -                      size_clip[0], size_clip[1]);
 -              IMB_freeImBuf(ibuf_clip);
 -              return ibuf_full;
 +              float y = (float)(y0 + i * dx);
 +              immVertex2f(pos, 0.0f, y);
 +              immVertex2f(pos, x_max, y);
 +              ++y_ct;
        }
 -}
  
 -/* smart function to sample a rect spiralling outside, nice for backbuf selection */
 -unsigned int ED_view3d_backbuf_sample_rect(
 -        ViewContext *vc, const int mval[2], int size,
 -        unsigned int min, unsigned int max, float *r_dist)
 -{
 -      struct ImBuf *buf;
 -      const unsigned int *bufmin, *bufmax, *tbuf;
 -      int minx, miny;
 -      int a, b, rc, nr, amount, dirvec[4][2];
 -      unsigned int index = 0;
 -
 -      amount = (size - 1) / 2;
 -
 -      minx = mval[0] - (amount + 1);
 -      miny = mval[1] - (amount + 1);
 -      buf = ED_view3d_backbuf_read(vc, minx, miny, minx + size - 1, miny + size - 1);
 -      if (!buf) return 0;
 -
 -      rc = 0;
 -      
 -      dirvec[0][0] = 1; dirvec[0][1] = 0;
 -      dirvec[1][0] = 0; dirvec[1][1] = -size;
 -      dirvec[2][0] = -1; dirvec[2][1] = 0;
 -      dirvec[3][0] = 0; dirvec[3][1] = size;
 -      
 -      bufmin = buf->rect;
 -      tbuf = buf->rect;
 -      bufmax = buf->rect + size * size;
 -      tbuf += amount * size + amount;
 -      
 -      for (nr = 1; nr <= size; nr++) {
 -              
 -              for (a = 0; a < 2; a++) {
 -                      for (b = 0; b < nr; b++) {
 -                              if (*tbuf && *tbuf >= min && *tbuf < max) {
 -                                      /* we got a hit */
 -
 -                                      /* get x,y pixel coords from the offset
 -                                       * (manhatten distance in keeping with other screen-based selection) */
 -                                      *r_dist = (float)(
 -                                              abs(((int)(tbuf - buf->rect) % size) - (size / 2)) +
 -                                              abs(((int)(tbuf - buf->rect) / size) - (size / 2)));
 -
 -                                      /* indices start at 1 here */
 -                                      index = (*tbuf - min) + 1;
 -                                      goto exit;
 -                              }
 -                              
 -                              tbuf += (dirvec[rc][0] + dirvec[rc][1]);
 -                              
 -                              if (tbuf < bufmin || tbuf >= bufmax) {
 -                                      goto exit;
 -                              }
 -                      }
 -                      rc++;
 -                      rc &= 3;
 -              }
 -      }
 +#if DEBUG_GRID
 +      int total_ct = x_ct + y_ct;
 +      printf("    %d + %d = %d gridlines drawn, %d skipped for next unit\n", x_ct, y_ct, total_ct, lines_skipped_for_next_unit);
 +#endif
  
 -exit:
 -      IMB_freeImBuf(buf);
 -      return index;
 +      return lines_skipped_for_next_unit > 0;
  }
  
 +#define GRID_MIN_PX_D 6.0
 +#define GRID_MIN_PX_F 6.0f
  
 -/* ************************************************************* */
 -
 -static void view3d_stereo_bgpic_setup(Scene *scene, View3D *v3d, Image *ima, ImageUser *iuser)
 +static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
  {
 -      if (BKE_image_is_stereo(ima)) {
 -              iuser->flag |= IMA_SHOW_STEREO;
 -
 -              if ((scene->r.scemode & R_MULTIVIEW) == 0) {
 -                      iuser->multiview_eye = STEREO_LEFT_ID;
 -              }
 -              else if (v3d->stereo3d_camera != STEREO_3D_ID) {
 -                      /* show only left or right camera */
 -                      iuser->multiview_eye = v3d->stereo3d_camera;
 -              }
 +      RegionView3D *rv3d = ar->regiondata;
  
 -              BKE_image_multiview_index(ima, iuser);
 -      }
 -      else {
 -              iuser->flag &= ~IMA_SHOW_STEREO;
 -      }
 -}
 +#if DEBUG_GRID
 +      printf("%s width %d, height %d\n", __FUNCTION__, ar->winx, ar->winy);
 +#endif
  
 -static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
 -                              const bool do_foreground, const bool do_camera_frame)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -      BGpic *bgpic;
 -      int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
 +      double fx = rv3d->persmat[3][0];
 +      double fy = rv3d->persmat[3][1];
 +      double fw = rv3d->persmat[3][3];
  
 -      for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
 -              bgpic->iuser.scene = scene;  /* Needed for render results. */
 +      const double wx = 0.5 * ar->winx;  /* use double precision to avoid rounding errors */
 +      const double wy = 0.5 * ar->winy;
  
 -              if ((bgpic->flag & V3D_BGPIC_FOREGROUND) != fg_flag)
 -                      continue;
 +      double x = wx * fx / fw;
 +      double y = wy * fy / fw;
  
 -              if ((bgpic->view == 0) || /* zero for any */
 -                  (bgpic->view & (1 << rv3d->view)) || /* check agaist flags */
 -                  (rv3d->persp == RV3D_CAMOB && bgpic->view == (1 << RV3D_VIEW_CAMERA)))
 -              {
 -                      float image_aspect[2];
 -                      float fac, asp, zoomx, zoomy;
 -                      float x1, y1, x2, y2, centx, centy;
 -
 -                      ImBuf *ibuf = NULL, *freeibuf, *releaseibuf;
 -                      void *lock;
 -                      rctf clip_rect;
 -
 -                      Image *ima = NULL;
 -                      MovieClip *clip = NULL;
 -
 -                      /* disable individual images */
 -                      if ((bgpic->flag & V3D_BGPIC_DISABLED))
 -                              continue;
 -
 -                      freeibuf = NULL;
 -                      releaseibuf = NULL;
 -                      if (bgpic->source == V3D_BGPIC_IMAGE) {
 -                              ima = bgpic->ima;
 -                              if (ima == NULL)
 -                                      continue;
 -                              BKE_image_user_frame_calc(&bgpic->iuser, CFRA, 0);
 -                              if (ima->source == IMA_SRC_SEQUENCE && !(bgpic->iuser.flag & IMA_USER_FRAME_IN_RANGE)) {
 -                                      ibuf = NULL; /* frame is out of range, dont show */
 -                              }
 -                              else {
 -                                      view3d_stereo_bgpic_setup(scene, v3d, ima, &bgpic->iuser);
 -                                      ibuf = BKE_image_acquire_ibuf(ima, &bgpic->iuser, &lock);
 -                                      releaseibuf = ibuf;
 -                              }
 +      double vec4[4] = { v3d->grid, v3d->grid, 0.0, 1.0 };
 +      mul_m4_v4d(rv3d->persmat, vec4);
 +      fx = vec4[0];
 +      fy = vec4[1];
 +      fw = vec4[3];
  
 -                              image_aspect[0] = ima->aspx;
 -                              image_aspect[1] = ima->aspy;
 -                      }
 -                      else if (bgpic->source == V3D_BGPIC_MOVIE) {
 -                              /* TODO: skip drawing when out of frame range (as image sequences do above) */
 +      double dx = fabs(x - wx * fx / fw);
 +      if (dx == 0) dx = fabs(y - wy * fy / fw);
  
 -                              if (bgpic->flag & V3D_BGPIC_CAMERACLIP) {
 -                                      if (scene->camera)
 -                                              clip = BKE_object_movieclip_get(scene, scene->camera, true);
 -                              }
 -                              else {
 -                                      clip = bgpic->clip;
 -                              }
 +      x += wx;
 +      y += wy;
  
 -                              if (clip == NULL)
 -                                      continue;
 +      /* now x, y, and dx have their final values
 +       * (x,y) is the world origin (0,0,0) mapped to Area-relative screen space
 +       * dx is the distance in pixels between grid lines -- same for horiz or vert grid lines */
  
 -                              BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
 -                              ibuf = BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
 +      glLineWidth(1.0f);
  
 -                              image_aspect[0] = clip->aspx;
 -                              image_aspect[1] = clip->aspy;
 +#if 0 /* TODO: write to UI/widget depth buffer, not scene depth */
 +      glDepthMask(GL_FALSE);  /* disable write in zbuffer */
 +#endif
  
 -                              /* working with ibuf from image and clip has got different workflow now.
 -                               * ibuf acquired from clip is referenced by cache system and should
 -                               * be dereferenced after usage. */
 -                              freeibuf = ibuf;
 -                      }
 -                      else {
 -                              /* perhaps when loading future files... */
 -                              BLI_assert(0);
 -                              copy_v2_fl(image_aspect, 1.0f);
 -                      }
 +      VertexFormat *format = immVertexFormat();
 +      unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
 +      unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
  
 -                      if (ibuf == NULL)
 -                              continue;
 +      immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
  
 -                      if ((ibuf->rect == NULL && ibuf->rect_float == NULL) || ibuf->channels != 4) { /* invalid image format */
 -                              if (freeibuf)
 -                                      IMB_freeImBuf(freeibuf);
 -                              if (releaseibuf)
 -                                      BKE_image_release_ibuf(ima, releaseibuf, lock);
 +      unsigned char col[3], col2[3];
 +      UI_GetThemeColor3ubv(TH_GRID, col);
  
 -                              continue;
 -                      }
 +      if (unit->system) {
 +              const void *usys;
 +              int len;
  
 -                      if (ibuf->rect == NULL)
 -                              IMB_rect_from_float(ibuf);
 +              bUnit_GetSystem(unit->system, B_UNIT_LENGTH, &usys, &len);
  
 -                      if (rv3d->persp == RV3D_CAMOB) {
 +              bool first = true;
  
 -                              if (do_camera_frame) {
 -                                      rctf vb;
 -                                      ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, false);
 -                                      x1 = vb.xmin;
 -                                      y1 = vb.ymin;
 -                                      x2 = vb.xmax;
 -                                      y2 = vb.ymax;
 -                              }
 -                              else {
 -                                      x1 = ar->winrct.xmin;
 -                                      y1 = ar->winrct.ymin;
 -                                      x2 = ar->winrct.xmax;
 -                                      y2 = ar->winrct.ymax;
 -                              }
 +              if (usys) {
 +                      int i = len;
 +                      while (i--) {
 +                              double scalar = bUnit_GetScaler(usys, i);
  
 -                              /* apply offset last - camera offset is different to offset in blender units */
 -                              /* so this has some sane way of working - this matches camera's shift _exactly_ */
 -                              {
 -                                      const float max_dim = max_ff(x2 - x1, y2 - y1);
 -                                      const float xof_scale = bgpic->xof * max_dim;
 -                                      const float yof_scale = bgpic->yof * max_dim;
 -
 -                                      x1 += xof_scale;
 -                                      y1 += yof_scale;
 -                                      x2 += xof_scale;
 -                                      y2 += yof_scale;
 +                              double dx_scalar = dx * scalar / (double)unit->scale_length;
 +                              if (dx_scalar < (GRID_MIN_PX_D * 2.0)) {
 +                                      /* very very small grid items are less useful when dealing with units */
 +                                      continue;
                                }
  
 -                              centx = (x1 + x2) / 2.0f;
 -                              centy = (y1 + y2) / 2.0f;
 +                              if (first) {
 +                                      first = false;
  
 -                              /* aspect correction */
 -                              if (bgpic->flag & V3D_BGPIC_CAMERA_ASPECT) {
 -                                      /* apply aspect from clip */
 -                                      const float w_src = ibuf->x * image_aspect[0];
 -                                      const float h_src = ibuf->y * image_aspect[1];
 -
 -                                      /* destination aspect is already applied from the camera frame */
 -                                      const float w_dst = x1 - x2;
 -                                      const float h_dst = y1 - y2;
 +                                      /* Store the smallest drawn grid size units name so users know how big each grid cell is */
 +                                      *grid_unit = bUnit_GetNameDisplay(usys, i);
 +                                      rv3d->gridview = (float)((scalar * (double)v3d->grid) / (double)unit->scale_length);
  
 -                                      const float asp_src = w_src / h_src;
 -                                      const float asp_dst = w_dst / h_dst;
 +                                      int gridline_ct = gridline_count(ar, x, y, dx_scalar);
 +                                      if (gridline_ct == 0)
 +                                              goto drawgrid_cleanup; /* nothing to draw */
  
 -                                      if (fabsf(asp_src - asp_dst) >= FLT_EPSILON) {
 -                                              if ((asp_src > asp_dst) == ((bgpic->flag & V3D_BGPIC_CAMERA_CROP) != 0)) {
 -                                                      /* fit X */
 -                                                      const float div = asp_src / asp_dst;
 -                                                      x1 = ((x1 - centx) * div) + centx;
 -                                                      x2 = ((x2 - centx) * div) + centx;
 -                                              }
 -                                              else {
 -                                                      /* fit Y */
 -                                                      const float div = asp_dst / asp_src;
 -                                                      y1 = ((y1 - centy) * div) + centy;
 -                                                      y2 = ((y2 - centy) * div) + centy;
 -                                              }
 -                                      }
 +                                      immBegin(PRIM_LINES, gridline_ct * 2);
                                }
 -                      }
 -                      else {
 -                              float tvec[3];
 -                              float sco[2];
 -                              const float mval_f[2] = {1.0f, 0.0f};
 -                              const float co_zero[3] = {0};
 -                              float zfac;
 -
 -                              /* calc window coord */
 -                              zfac = ED_view3d_calc_zfac(rv3d, co_zero, NULL);
 -                              ED_view3d_win_to_delta(ar, mval_f, tvec, zfac);
 -                              fac = max_ff(fabsf(tvec[0]), max_ff(fabsf(tvec[1]), fabsf(tvec[2]))); /* largest abs axis */
 -                              fac = 1.0f / fac;
 -
 -                              asp = (float)ibuf->y / (float)ibuf->x;
 -
 -                              zero_v3(tvec);
 -                              ED_view3d_project_float_v2_m4(ar, tvec, sco, rv3d->persmat);
 -
 -                              x1 =  sco[0] + fac * (bgpic->xof - bgpic->size);
 -                              y1 =  sco[1] + asp * fac * (bgpic->yof - bgpic->size);
 -                              x2 =  sco[0] + fac * (bgpic->xof + bgpic->size);
 -                              y2 =  sco[1] + asp * fac * (bgpic->yof + bgpic->size);
 -
 -                              centx = (x1 + x2) / 2.0f;
 -                              centy = (y1 + y2) / 2.0f;
 -                      }
  
 -                      /* complete clip? */
 -                      BLI_rctf_init(&clip_rect, x1, x2, y1, y2);
 -                      if (bgpic->rotation) {
 -                              BLI_rctf_rotate_expand(&clip_rect, &clip_rect, bgpic->rotation);
 -                      }
 +                              float blend_fac = 1.0f - ((GRID_MIN_PX_F * 2.0f) / (float)dx_scalar);
 +                              /* tweak to have the fade a bit nicer */
 +                              blend_fac = (blend_fac * blend_fac) * 2.0f;
 +                              CLAMP(blend_fac, 0.3f, 1.0f);
  
 -                      if (clip_rect.xmax < 0 || clip_rect.ymax < 0 || clip_rect.xmin > ar->winx || clip_rect.ymin > ar->winy) {
 -                              if (freeibuf)
 -                                      IMB_freeImBuf(freeibuf);
 -                              if (releaseibuf)
 -                                      BKE_image_release_ibuf(ima, releaseibuf, lock);
 +                              UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, blend_fac, col2);
  
 -                              continue;
 +                              const int skip_mod = (i == 0) ? 0 : (int)round(bUnit_GetScaler(usys, i - 1) / scalar);
 +#if DEBUG_GRID
 +                              printf("%s %f, ", bUnit_GetNameDisplay(usys, i), scalar);
 +                              if (i > 0)
 +                                      printf("next unit is %d times larger\n", skip_mod);
 +                              else
 +                                      printf("largest unit\n");
 +#endif
 +                              if (!drawgrid_draw(ar, x, y, dx_scalar, skip_mod, pos, color, col2))
 +                                      break;
                        }
 +              }
 +      }
 +      else {
 +              const double sublines = v3d->gridsubdiv;
 +              const float  sublines_fl = v3d->gridsubdiv;
  
 -                      zoomx = (x2 - x1) / ibuf->x;
 -                      zoomy = (y2 - y1) / ibuf->y;
 -
 -                      /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
 -                      if (zoomx < 1.0f || zoomy < 1.0f) {
 -                              float tzoom = min_ff(zoomx, zoomy);
 -                              int mip = 0;
 +              int grids_to_draw = 2; /* first the faint fine grid, then the bold coarse grid */
  
 -                              if ((ibuf->userflags & IB_MIPMAP_INVALID) != 0) {
 -                                      IMB_remakemipmap(ibuf, 0);
 -                                      ibuf->userflags &= ~IB_MIPMAP_INVALID;
 -                              }
 -                              else if (ibuf->mipmap[0] == NULL)
 -                                      IMB_makemipmap(ibuf, 0);
 -
 -                              while (tzoom < 1.0f && mip < 8 && ibuf->mipmap[mip]) {
 -                                      tzoom *= 2.0f;
 -                                      zoomx *= 2.0f;
 -                                      zoomy *= 2.0f;
 -                                      mip++;
 +              if (dx < GRID_MIN_PX_D) {
 +                      rv3d->gridview *= sublines_fl;
 +                      dx *= sublines;
 +                      if (dx < GRID_MIN_PX_D) {
 +                              rv3d->gridview *= sublines_fl;
 +                              dx *= sublines;
 +                              if (dx < GRID_MIN_PX_D) {
 +                                      rv3d->gridview *= sublines_fl;
 +                                      dx *= sublines;
 +                                      grids_to_draw = (dx < GRID_MIN_PX_D) ? 0 : 1;
                                }
 -                              if (mip > 0)
 -                                      ibuf = ibuf->mipmap[mip - 1];
 -                      }
 -
 -                      if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
 -                      glDepthMask(0);
 -
 -                      glEnable(GL_BLEND);
 -                      glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
 -
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPushMatrix();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPushMatrix();
 -                      ED_region_pixelspace(ar);
 -
 -                      glTranslatef(centx, centy, 0.0);
 -                      glRotatef(RAD2DEGF(-bgpic->rotation), 0.0f, 0.0f, 1.0f);
 -
 -                      if (bgpic->flag & V3D_BGPIC_FLIP_X) {
 -                              zoomx *= -1.0f;
 -                              x1 = x2;
                        }
 -                      if (bgpic->flag & V3D_BGPIC_FLIP_Y) {
 -                              zoomy *= -1.0f;
 -                              y1 = y2;
 +              }
 +              else {
 +                      if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
 +                              rv3d->gridview /= sublines_fl;
 +                              dx /= sublines;
 +                              if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
 +                                      rv3d->gridview /= sublines_fl;
 +                                      dx /= sublines;
 +                                      if (dx > (GRID_MIN_PX_D * 10.0)) {
 +                                              grids_to_draw = 1;
 +                                      }
 +                              }
                        }
 -                      glPixelZoom(zoomx, zoomy);
 -                      glColor4f(1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend);
 -
 -                      /* could not use glaDrawPixelsAuto because it could fallback to
 -                       * glaDrawPixelsSafe in some cases, which will end up in missing
 -                       * alpha transparency for the background image (sergey)
 -                       */
 -                      glaDrawPixelsTex(x1 - centx, y1 - centy, ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR, ibuf->rect);
 +              }
  
 -                      glPixelZoom(1.0, 1.0);
 -                      glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
 +              int gridline_ct = gridline_count(ar, x, y, dx);
 +              if (gridline_ct == 0)
 +                      goto drawgrid_cleanup; /* nothing to draw */
  
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPopMatrix();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPopMatrix();
 +              immBegin(PRIM_LINES, gridline_ct * 2);
  
 -                      glDisable(GL_BLEND);
 +              if (grids_to_draw == 2) {
 +                      UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0), col2);
 +                      if (drawgrid_draw(ar, x, y, dx, v3d->gridsubdiv, pos, color, col2))
 +                              drawgrid_draw(ar, x, y, dx * sublines, 0, pos, color, col);
 +              }
 +              else if (grids_to_draw == 1) {
 +                      drawgrid_draw(ar, x, y, dx, 0, pos, color, col);
 +              }
 +      }
  
 -                      glDepthMask(1);
 -                      if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
 +      /* draw visible axes */
 +      /* horizontal line */
 +      if (0 <= y && y < ar->winy) {
 +              UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT) ? 'Y' : 'X');
 +              immAttrib3ub(color, col2[0], col2[1], col2[2]);
 +              immVertex2f(pos, 0.0f, y);
 +              immVertex2f(pos, (float)ar->winx, y);
 +      }
  
 -                      if (freeibuf)
 -                              IMB_freeImBuf(freeibuf);
 -                      if (releaseibuf)
 -                              BKE_image_release_ibuf(ima, releaseibuf, lock);
 -              }
 +      /* vertical line */
 +      if (0 <= x && x < ar->winx) {
 +              UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM) ? 'Y' : 'Z');
 +              immAttrib3ub(color, col2[0], col2[1], col2[2]);
 +              immVertex2f(pos, x, 0.0f);
 +              immVertex2f(pos, x, (float)ar->winy);
        }
 -}
  
 -static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
 -                                   const bool do_foreground, const bool do_camera_frame)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 +      immEnd();
  
 -      if ((v3d->flag & V3D_DISPBGPICS) == 0)
 -              return;
 +drawgrid_cleanup:
 +      immUnbindProgram();
  
 -      /* disabled - mango request, since footage /w only render is quite useful
 -       * and this option is easy to disable all background images at once */
 -#if 0
 -      if (v3d->flag2 & V3D_RENDER_OVERRIDE)
 -              return;
 +#if 0 /* depth write is left enabled above */
 +      glDepthMask(GL_TRUE);  /* enable write in zbuffer */
  #endif
 -
 -      if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
 -              if (rv3d->persp == RV3D_CAMOB) {
 -                      view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
 -              }
 -      }
 -      else {
 -              view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
 -      }
  }
  
 -/* ****************** View3d afterdraw *************** */
 -
 -typedef struct View3DAfter {
 -      struct View3DAfter *next, *prev;
 -      struct Base *base;
 -      short dflag;
 -} View3DAfter;
 +#undef DEBUG_GRID
 +#undef GRID_MIN_PX_D
 +#undef GRID_MIN_PX_F
  
 -/* temp storage of Objects that need to be drawn as last */
 -void ED_view3d_after_add(ListBase *lb, Base *base, const short dflag)
 +static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
  {
 -      View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
 -      BLI_assert((base->flag & OB_FROMDUPLI) == 0);
 -      BLI_addtail(lb, v3da);
 -      v3da->base = base;
 -      v3da->dflag = dflag;
 -}
 +      /* draw only if there is something to draw */
 +      if (v3d->gridflag & (V3D_SHOW_FLOOR | V3D_SHOW_X | V3D_SHOW_Y | V3D_SHOW_Z)) {
 +              /* draw how many lines?
 +               * trunc(v3d->gridlines / 2) * 4
 +               * + 2 for xy axes (possibly with special colors)
 +               * + 1 for z axis (the only line not in xy plane)
 +               * even v3d->gridlines are honored, odd rounded down */
 +              const int gridlines = v3d->gridlines / 2;
 +              const float grid_scale = ED_view3d_grid_scale(scene, v3d, grid_unit);
 +              const float grid = gridlines * grid_scale;
  
 -/* disables write in zbuffer and draws it over */
 -static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      View3DAfter *v3da;
 -      
 -      glDepthMask(GL_FALSE);
 -      v3d->transp = true;
 -      
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
 -              draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
 -              MEM_freeN(v3da);
 -      }
 -      v3d->transp = false;
 -      
 -      glDepthMask(GL_TRUE);
 -      
 -}
 +              const bool show_floor = (v3d->gridflag & V3D_SHOW_FLOOR) && gridlines >= 1;
  
 -/* clears zbuffer and draws it over */
 -static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, bool *clear)
 -{
 -      View3DAfter *v3da;
 +              bool show_axis_x = v3d->gridflag & V3D_SHOW_X;
 +              bool show_axis_y = v3d->gridflag & V3D_SHOW_Y;
 +              bool show_axis_z = v3d->gridflag & V3D_SHOW_Z;
  
 -      if (*clear && v3d->zbuf) {
 -              glClear(GL_DEPTH_BUFFER_BIT);
 -              *clear = false;
 -      }
 +              unsigned char col_grid[3], col_axis[3];
  
 -      v3d->xray = true;
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 -              draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
 -              MEM_freeN(v3da);
 -      }
 -      v3d->xray = false;
 -}
 +              glLineWidth(1.0f);
  
 +              UI_GetThemeColor3ubv(TH_GRID, col_grid);
  
 -/* clears zbuffer and draws it over */
 -static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, const bool clear)
 -{
 -      View3DAfter *v3da;
 +              if (!write_depth)
 +                      glDepthMask(GL_FALSE);
  
 -      if (clear && v3d->zbuf)
 -              glClear(GL_DEPTH_BUFFER_BIT);
 +              if (show_floor) {
 +                      const unsigned vertex_ct = 2 * (gridlines * 4 + 2);
 +                      const int sublines = v3d->gridsubdiv;
  
 -      v3d->xray = true;
 -      v3d->transp = true;
 -      
 -      glDepthMask(GL_FALSE);
 +                      unsigned char col_bg[3], col_grid_emphasise[3], col_grid_light[3];
  
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
 -              draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
 -              MEM_freeN(v3da);
 -      }
 +                      VertexFormat *format = immVertexFormat();
 +                      unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
 +                      unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
  
 -      v3d->transp = false;
 -      v3d->xray = false;
 +                      immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
  
 -      glDepthMask(GL_TRUE);
 -}
 +                      immBegin(PRIM_LINES, vertex_ct);
  
 -/* clears zbuffer and draws it over,
 - * note that in the select version we don't care about transparent flag as with regular drawing */
 -static void view3d_draw_xray_select(Scene *scene, ARegion *ar, View3D *v3d, bool *clear)
 -{
 -      /* Not ideal, but we need to read from the previous depths before clearing
 -       * otherwise we could have a function to load the depths after drawing.
 -       *
 -       * Clearing the depth buffer isn't all that common between drawing objects so accept this for now.
 -       */
 -      if (U.gpu_select_pick_deph) {
 -              GPU_select_load_id(-1);
 -      }
 +                      /* draw normal grid lines */
 +                      UI_GetColorPtrShade3ubv(col_grid, col_grid_light, 10);
  
 -      View3DAfter *v3da;
 -      if (*clear && v3d->zbuf) {
 -              glClear(GL_DEPTH_BUFFER_BIT);
 -              *clear = false;
 -      }
 +                      for (int a = 1; a <= gridlines; a++) {
 +                              /* skip emphasised divider lines */
 +                              if (a % sublines != 0) {
 +                                      const float line = a * grid_scale;
  
 -      v3d->xray = true;
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 -              if (GPU_select_load_id(v3da->base->selcol)) {
 -                      draw_object_select(scene, ar, v3d, v3da->base, v3da->dflag);
 -              }
 -              MEM_freeN(v3da);
 -      }
 -      v3d->xray = false;
 -}
 +                                      immAttrib3ubv(color, col_grid_light);
  
 -/* *********************** */
 +                                      immVertex2f(pos, -grid, -line);
 +                                      immVertex2f(pos, +grid, -line);
 +                                      immVertex2f(pos, -grid, +line);
 +                                      immVertex2f(pos, +grid, +line);
  
 -/*
 - * In most cases call draw_dupli_objects,
 - * draw_dupli_objects_color was added because when drawing set dupli's
 - * we need to force the color
 - */
 +                                      immVertex2f(pos, -line, -grid);
 +                                      immVertex2f(pos, -line, +grid);
 +                                      immVertex2f(pos, +line, -grid);
 +                                      immVertex2f(pos, +line, +grid);
 +                              }
 +                      }
  
 -#if 0
 -int dupli_ob_sort(void *arg1, void *arg2)
 -{
 -      void *p1 = ((DupliObject *)arg1)->ob;
 -      void *p2 = ((DupliObject *)arg2)->ob;
 -      int val = 0;
 -      if (p1 < p2) val = -1;
 -      else if (p1 > p2) val = 1;
 -      return val;
 -}
 -#endif
 +                      /* draw emphasised grid lines */
 +                      UI_GetThemeColor3ubv(TH_BACK, col_bg);
 +                      /* emphasise division lines lighter instead of darker, if background is darker than grid */
 +                      UI_GetColorPtrShade3ubv(col_grid, col_grid_emphasise,
 +                              (col_grid[0] + col_grid[1] + col_grid[2] + 30 >
 +                              col_bg[0] + col_bg[1] + col_bg[2]) ? 20 : -10);
  
 +                      if (sublines <= gridlines) {
 +                              immAttrib3ubv(color, col_grid_emphasise);
  
 -static DupliObject *dupli_step(DupliObject *dob)
 -{
 -      while (dob && dob->no_draw)
 -              dob = dob->next;
 -      return dob;
 -}
 +                              for (int a = sublines; a <= gridlines; a += sublines) {
 +                                      const float line = a * grid_scale;
  
 -static void draw_dupli_objects_color(
 -        Scene *scene, ARegion *ar, View3D *v3d, Base *base,
 -        const short dflag, const int color)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -      ListBase *lb;
 -      LodLevel *savedlod;
 -      DupliObject *dob_prev = NULL, *dob, *dob_next = NULL;
 -      Base tbase = {NULL};
 -      BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
 -      GLuint displist = 0;
 -      unsigned char color_rgb[3];
 -      const short dflag_dupli = dflag | DRAW_CONSTCOLOR;
 -      short transflag;
 -      bool use_displist = false;  /* -1 is initialize */
 -      char dt;
 -      short dtx;
 -      DupliApplyData *apply_data;
 -
 -      if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
 -      if ((base->object->restrictflag & OB_RESTRICT_RENDER) && (v3d->flag2 & V3D_RENDER_OVERRIDE)) return;
 -
 -      if (dflag & DRAW_CONSTCOLOR) {
 -              BLI_assert(color == TH_UNDEFINED);
 -      }
 -      else {
 -              UI_GetThemeColorBlend3ubv(color, TH_BACK, 0.5f, color_rgb);
 -      }
 +                                      immVertex2f(pos, -grid, -line);
 +                                      immVertex2f(pos, +grid, -line);
 +                                      immVertex2f(pos, -grid, +line);
 +                                      immVertex2f(pos, +grid, +line);
  
 -      tbase.flag = OB_FROMDUPLI | base->flag;
 -      lb = object_duplilist(G.main->eval_ctx, scene, base->object);
 -      // BLI_listbase_sort(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
 +                                      immVertex2f(pos, -line, -grid);
 +                                      immVertex2f(pos, -line, +grid);
 +                                      immVertex2f(pos, +line, -grid);
 +                                      immVertex2f(pos, +line, +grid);
 +                              }
 +                      }
  
 -      apply_data = duplilist_apply(base->object, scene, lb);
 +                      /* draw X axis */
 +                      if (show_axis_x) {
 +                              show_axis_x = false; /* drawing now, won't need to draw later */
 +                              UI_make_axis_color(col_grid, col_axis, 'X');
 +                              immAttrib3ubv(color, col_axis);
 +                      }
 +                      else
 +                              immAttrib3ubv(color, col_grid_emphasise);
  
 -      dob = dupli_step(lb->first);
 -      if (dob) dob_next = dupli_step(dob->next);
 +                      immVertex2f(pos, -grid, 0.0f);
 +                      immVertex2f(pos, +grid, 0.0f);
  
 -      for (; dob; dob_prev = dob, dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
 -              bool testbb = false;
 +                      /* draw Y axis */
 +                      if (show_axis_y) {
 +                              show_axis_y = false; /* drawing now, won't need to draw later */
 +                              UI_make_axis_color(col_grid, col_axis, 'Y');
 +                              immAttrib3ubv(color, col_axis);
 +                      }
 +                      else
 +                              immAttrib3ubv(color, col_grid_emphasise);
  
 -              tbase.object = dob->ob;
 +                      immVertex2f(pos, 0.0f, -grid);
 +                      immVertex2f(pos, 0.0f, +grid);
  
 -              /* Make sure lod is updated from dupli's position */
 -              savedlod = dob->ob->currentlod;
 +                      immEnd();
 +                      immUnbindProgram();
  
 -#ifdef WITH_GAMEENGINE
 -              if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
 -                      BKE_object_lod_update(dob->ob, rv3d->viewinv[3]);
 +                      /* done with XY plane */
                }
 -#endif
  
 -              /* extra service: draw the duplicator in drawtype of parent, minimum taken
 -               * to allow e.g. boundbox box objects in groups for LOD */
 -              dt = tbase.object->dt;
 -              tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
 +              if (show_axis_x || show_axis_y || show_axis_z) {
 +                      /* draw axis lines -- sometimes grid floor is off, other times we still need to draw the Z axis */
  
 -              /* inherit draw extra, but not if a boundbox under the assumption that this
 -               * is intended to speed up drawing, and drawing extra (especially wire) can
 -               * slow it down too much */
 -              dtx = tbase.object->dtx;
 -              if (tbase.object->dt != OB_BOUNDBOX)
 -                      tbase.object->dtx = base->object->dtx;
 +                      VertexFormat *format = immVertexFormat();
 +                      unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 3, KEEP_FLOAT);
 +                      unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
  
 -              /* negative scale flag has to propagate */
 -              transflag = tbase.object->transflag;
 +                      immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
 +                      immBegin(PRIM_LINES, (show_axis_x + show_axis_y + show_axis_z) * 2);
  
 -              if (is_negative_m4(dob->mat))
 -                      tbase.object->transflag |= OB_NEG_SCALE;
 -              else
 -                      tbase.object->transflag &= ~OB_NEG_SCALE;
 -              
 -              /* should move outside the loop but possible color is set in draw_object still */
 -              if ((dflag & DRAW_CONSTCOLOR) == 0) {
 -                      glColor3ubv(color_rgb);
 -              }
 -              
 -              /* generate displist, test for new object */
 -              if (dob_prev && dob_prev->ob != dob->ob) {
 -                      if (use_displist == true)
 -                              glDeleteLists(displist, 1);
 -                      
 -                      use_displist = false;
 -              }
 -              
 -              if ((bb_tmp = BKE_object_boundbox_get(dob->ob))) {
 -                      bb = *bb_tmp; /* must make a copy  */
 -                      testbb = true;
 -              }
 +                      if (show_axis_x) {
 +                              UI_make_axis_color(col_grid, col_axis, 'X');
 +                              immAttrib3ubv(color, col_axis);
 +                              immVertex3f(pos, -grid, 0.0f, 0.0f);
 +                              immVertex3f(pos, +grid, 0.0f, 0.0f);
 +                      }
  
 -              if (!testbb || ED_view3d_boundbox_clip_ex(rv3d, &bb, dob->mat)) {
 -                      /* generate displist */
 -                      if (use_displist == false) {
 -                              
 -                              /* note, since this was added, its checked (dob->type == OB_DUPLIGROUP)
 -                               * however this is very slow, it was probably needed for the NLA
 -                               * offset feature (used in group-duplicate.blend but no longer works in 2.5)
 -                               * so for now it should be ok to - campbell */
 -                              
 -                              if ( /* if this is the last no need  to make a displist */
 -                                   (dob_next == NULL || dob_next->ob != dob->ob) ||
 -                                   /* lamp drawing messes with matrices, could be handled smarter... but this works */
 -                                   (dob->ob->type == OB_LAMP) ||
 -                                   (dob->type == OB_DUPLIGROUP && dob->animated) ||
 -                                   !bb_tmp ||
 -                                   draw_glsl_material(scene, dob->ob, v3d, dt) ||
 -                                   check_object_draw_texture(scene, v3d, dt) ||
 -                                   (v3d->flag2 & V3D_SOLID_MATCAP) != 0)
 -                              {
 -                                      // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name + 2);
 -                                      use_displist = false;
 -                              }
 -                              else {
 -                                      // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name + 2);
 -                                      
 -                                      /* disable boundbox check for list creation */
 -                                      BKE_object_boundbox_flag(dob->ob, BOUNDBOX_DISABLED, 1);
 -                                      /* need this for next part of code */
 -                                      unit_m4(dob->ob->obmat);    /* obmat gets restored */
 -                                      
 -                                      displist = glGenLists(1);
 -                                      glNewList(displist, GL_COMPILE);
 -                                      draw_object(scene, ar, v3d, &tbase, dflag_dupli);
 -                                      glEndList();
 -                                      
 -                                      use_displist = true;
 -                                      BKE_object_boundbox_flag(dob->ob, BOUNDBOX_DISABLED, 0);
 -                              }               
 +                      if (show_axis_y) {
 +                              UI_make_axis_color(col_grid, col_axis, 'Y');
 +                              immAttrib3ubv(color, col_axis);
 +                              immVertex3f(pos, 0.0f, -grid, 0.0f);
 +                              immVertex3f(pos, 0.0f, +grid, 0.0f);
                        }
 -                      
 -                      if (use_displist) {
 -                              glPushMatrix();
 -                              glMultMatrixf(dob->mat);
 -                              glCallList(displist);
 -                              glPopMatrix();
 -                      }       
 -                      else {
 -                              copy_m4_m4(dob->ob->obmat, dob->mat);
 -                              GPU_begin_dupli_object(dob);
 -                              draw_object(scene, ar, v3d, &tbase, dflag_dupli);
 -                              GPU_end_dupli_object();
 +
 +                      if (show_axis_z) {
 +                              UI_make_axis_color(col_grid, col_axis, 'Z');
 +                              immAttrib3ubv(color, col_axis);
 +                              immVertex3f(pos, 0.0f, 0.0f, -grid);
 +                              immVertex3f(pos, 0.0f, 0.0f, +grid);
                        }
 +
 +                      immEnd();
 +                      immUnbindProgram();
                }
 -              
 -              tbase.object->dt = dt;
 -              tbase.object->dtx = dtx;
 -              tbase.object->transflag = transflag;
 -              tbase.object->currentlod = savedlod;
 -      }
  
 -      if (apply_data) {
 -              duplilist_restore(lb, apply_data);
 -              duplilist_free_apply_data(apply_data);
 +              if (!write_depth)
 +                      glDepthMask(GL_TRUE);
        }
 -
 -      free_object_duplilist(lb);
 -      
 -      if (use_displist)
 -              glDeleteLists(displist, 1);
 -}
 -
 -static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
 -{
 -      /* define the color here so draw_dupli_objects_color can be called
 -       * from the set loop */
 -      
 -      int color = (base->flag & SELECT) ? TH_SELECT : TH_WIRE;
 -      /* debug */
 -      if (base->object->dup_group && base->object->dup_group->id.us < 1)
 -              color = TH_REDALERT;
 -      
 -      draw_dupli_objects_color(scene, ar, v3d, base, 0, color);
  }
  
 -/* XXX warning, not using gpu offscreen here */
 -void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
 +/** could move this elsewhere, but tied into #ED_view3d_grid_scale */
 +float ED_scene_grid_scale(Scene *scene, const char **grid_unit)
  {
 -      int x, y, w, h;
 -      rcti r;
 -      /* clamp rect by region */
 -
 -      r.xmin = 0;
 -      r.xmax = ar->winx - 1;
 -      r.ymin = 0;
 -      r.ymax = ar->winy - 1;
 -
 -      /* Constrain rect to depth bounds */
 -      BLI_rcti_isect(&r, rect, rect);
 -
 -      /* assign values to compare with the ViewDepths */
 -      x = rect->xmin;
 -      y = rect->ymin;
 -
 -      w = BLI_rcti_size_x(rect);
 -      h = BLI_rcti_size_y(rect);
 -
 -      if (w <= 0 || h <= 0) {
 -              if (d->depths)
 -                      MEM_freeN(d->depths);
 -              d->depths = NULL;
 -
 -              d->damaged = false;
 -      }
 -      else if (d->w != w ||
 -               d->h != h ||
 -               d->x != x ||
 -               d->y != y ||
 -               d->depths == NULL
 -               )
 -      {
 -              d->x = x;
 -              d->y = y;
 -              d->w = w;
 -              d->h = h;
 +      /* apply units */
 +      if (scene->unit.system) {
 +              const void *usys;
 +              int len;
  
 -              if (d->depths)
 -                      MEM_freeN(d->depths);
 +              bUnit_GetSystem(scene->unit.system, B_UNIT_LENGTH, &usys, &len);
  
 -              d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
 -              
 -              d->damaged = true;
 +              if (usys) {
 +                      int i = bUnit_GetBaseUnit(usys);
 +                      if (grid_unit)
 +                              *grid_unit = bUnit_GetNameDisplay(usys, i);
 +                      return (float)bUnit_GetScaler(usys, i) / scene->unit.scale_length;
 +              }
        }
  
 -      if (d->damaged) {
 -              /* XXX using special function here, it doesn't use the gpu offscreen system */
 -              view3d_opengl_read_Z_pixels(ar, d->x, d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
 -              glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
 -              d->damaged = false;
 -      }
 +      return 1.0f;
  }
  
 -/* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
 -void ED_view3d_depth_update(ARegion *ar)
 +float ED_view3d_grid_scale(Scene *scene, View3D *v3d, const char **grid_unit)
  {
 -      RegionView3D *rv3d = ar->regiondata;
 -      
 -      /* Create storage for, and, if necessary, copy depth buffer */
 -      if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
 -      if (rv3d->depths) {
 -              ViewDepths *d = rv3d->depths;
 -              if (d->w != ar->winx ||
 -                  d->h != ar->winy ||
 -                  !d->depths)
 -              {
 -                      d->w = ar->winx;
 -                      d->h = ar->winy;
 -                      if (d->depths)
 -                              MEM_freeN(d->depths);
 -                      d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
 -                      d->damaged = true;
 -              }
 -              
 -              if (d->damaged) {
 -                      view3d_opengl_read_pixels(ar, 0, 0, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
 -                      glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
 -                      
 -                      d->damaged = false;
 -              }
 -      }
 +      return v3d->grid * ED_scene_grid_scale(scene, grid_unit);
  }
  
 -/* utility function to find the closest Z value, use for autodepth */
 -float view3d_depth_near(ViewDepths *d)
 +
 +static void view3d_draw_grid(const bContext *C, ARegion *ar)
  {
 -      /* convert to float for comparisons */
 -      const float near = (float)d->depth_range[0];
 -      const float far_real = (float)d->depth_range[1];
 -      float far = far_real;
 -
 -      const float *depths = d->depths;
 -      float depth = FLT_MAX;
 -      int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
 -
 -      /* far is both the starting 'far' value
 -       * and the closest value found. */
 -      while (i--) {
 -              depth = *depths++;
 -              if ((depth < far) && (depth > near)) {
 -                      far = depth;
 -              }
 -      }
 -
 -      return far == far_real ? FLT_MAX : far;
 -}
 -
 -void ED_view3d_draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      short zbuf = v3d->zbuf;
 +      /* TODO viewport
 +       * Missing is the flags to check whether to draw it
 +       * for now now we are using the flags in v3d itself.
 +       *
 +       * Also for now always assume depth is there, so we
 +       * draw on top of it.
 +       */
 +      /**
 +       * Calculate pixel-size factor once, is used for lamps and object centers.
 +       * Used by #ED_view3d_pixel_size and typically not accessed directly.
 +       *
 +       * \note #BKE_camera_params_compute_viewplane' also calculates a pixel-size value,
 +       * passed to #RE_SetPixelSize, in ortho mode this is compatible with this value,
 +       * but in perspective mode its offset by the near-clip.
 +       *
 +       * 'RegionView3D.pixsize' is used for viewport drawing, not rendering.
 +       */
 +      Scene *scene = CTX_data_scene(C);
 +      View3D *v3d = CTX_wm_view3d(C);
        RegionView3D *rv3d = ar->regiondata;
  
 -      /* Setup view matrix. */
 -      ED_view3d_draw_setup_view(NULL, scene, ar, v3d, rv3d->winmat, rv3d->viewmat);
 +      const bool draw_floor = (rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO);
 +      const char *grid_unit = NULL;
  
 -      glClear(GL_DEPTH_BUFFER_BIT);
 +      /* ortho grid goes first, does not write to depth buffer and doesn't need depth test so it will override
 +       * objects if done last
 +       * needs to be done always, gridview is adjusted in drawgrid() now, but only for ortho views.
 +       */
 +      rv3d->gridview = ED_view3d_grid_scale(scene, v3d, &grid_unit);
  
 -      v3d->zbuf = true;
        glEnable(GL_DEPTH_TEST);
 +      glDepthMask(GL_FALSE); /* read & test depth, but don't alter it. TODO: separate UI depth buffer */
 +
 +      if (!draw_floor) {
 +              ED_region_pixelspace(ar);
 +              *(&grid_unit) = NULL;  /* drawgrid need this to detect/affect smallest valid unit... */
 +              drawgrid(&scene->unit, ar, v3d, &grid_unit);
  
 -      if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 -              ED_gpencil_draw_view3d(NULL, scene, v3d, ar, true);
 +              gpuLoadProjectionMatrix(rv3d->winmat);
 +              gpuLoadMatrix(rv3d->viewmat);
        }
 -      
 -      v3d->zbuf = zbuf;
 +      else {
 +              drawfloor(scene, v3d, &grid_unit, false);
 +      }
 +
 +      glDisable(GL_DEPTH_TEST);
  }
  
 -static void view3d_draw_depth_loop(Scene *scene, ARegion *ar, View3D *v3d)
 +static bool is_cursor_visible(Scene *scene, SceneLayer *sl)
  {
 -      Base *base;
 -
 -      /* no need for color when drawing depth buffer */
 -      const short dflag_depth = DRAW_CONSTCOLOR;
 -
 -      /* draw set first */
 -      if (scene->set) {
 -              Scene *sce_iter;
 -              for (SETLOOPER(scene->set, sce_iter, base)) {
 -                      if (v3d->lay & base->lay) {
 -                              draw_object(scene, ar, v3d, base, 0);
 -                              if (base->object->transflag & OB_DUPLI) {
 -                                      draw_dupli_objects_color(scene, ar, v3d, base, dflag_depth, TH_UNDEFINED);
 -                              }
 +      Object *ob = OBACT_NEW;
 +
 +      /* don't draw cursor in paint modes, but with a few exceptions */
 +      if (ob && ob->mode & OB_MODE_ALL_PAINT) {
 +              /* exception: object is in weight paint and has deforming armature in pose mode */
 +              if (ob->mode & OB_MODE_WEIGHT_PAINT) {
 +                      if (BKE_object_pose_armature_get(ob) != NULL) {
 +                              return true;
                        }
                }
 -      }
 -      
 -      for (base = scene->base.first; base; base = base->next) {
 -              if (v3d->lay & base->lay) {
 -                      /* dupli drawing */
 -                      if (base->object->transflag & OB_DUPLI) {
 -                              draw_dupli_objects_color(scene, ar, v3d, base, dflag_depth, TH_UNDEFINED);
 +              /* exception: object in texture paint mode, clone brush, use_clone_layer disabled */
 +              else if (ob->mode & OB_MODE_TEXTURE_PAINT) {
 +                      const Paint *p = BKE_paint_get_active(scene, sl);
 +
 +                      if (p && p->brush && p->brush->imagepaint_tool == PAINT_TOOL_CLONE) {
 +                              if ((scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_LAYER_CLONE) == 0) {
 +                                      return true;
 +                              }
                        }
 -                      draw_object(scene, ar, v3d, base, dflag_depth);
                }
 +
 +              /* no exception met? then don't draw cursor! */
 +              return false;
        }
 -      
 -      /* this isn't that nice, draw xray objects as if they are normal */
 -      if (v3d->afterdraw_transp.first ||
 -          v3d->afterdraw_xray.first ||
 -          v3d->afterdraw_xraytransp.first)
 -      {
 -              View3DAfter *v3da;
 -              int mask_orig;
  
 -              v3d->xray = true;
 +      return true;
 +}
 +
 +static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
 +{
 +      int co[2];
 +
 +      /* we don't want the clipping for cursor */
 +      if (ED_view3d_project_int_global(ar, ED_view3d_cursor3d_get(scene, v3d), co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
 +              const float f5 = 0.25f * U.widget_unit;
 +              const float f10 = 0.5f * U.widget_unit;
 +              const float f20 = U.widget_unit;
                
 -              /* transp materials can change the depth mask, see #21388 */
 -              glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
 +              glLineWidth(1.0f);
  
 +              VertexFormat *format = immVertexFormat();
 +              unsigned int pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
 +              unsigned int color = VertexFormat_add_attrib(format, "color", COMP_U8, 3, NORMALIZE_INT_TO_FLOAT);
  
 -              if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
 -                      glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
 -                      for (v3da = v3d->afterdraw_xray.first; v3da; v3da = v3da->next) {
 -                              draw_object(scene, ar, v3d, v3da->base, dflag_depth);
 -                      }
 -                      glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
 -              }
 +              immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
  
 -              /* draw 3 passes, transp/xray/xraytransp */
 -              v3d->xray = false;
 -              v3d->transp = true;
 -              while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
 -                      draw_object(scene, ar, v3d, v3da->base, dflag_depth);
 -                      MEM_freeN(v3da);
 -              }
 +              const int segments = 16;
  
 -              v3d->xray = true;
 -              v3d->transp = false;
 -              while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 -                      draw_object(scene, ar, v3d, v3da->base, dflag_depth);
 -                      MEM_freeN(v3da);
 -              }
 +              immBegin(PRIM_LINE_LOOP, segments);
 +
 +              for (int i = 0; i < segments; ++i) {
 +                      float angle = 2 * M_PI * ((float)i / (float)segments);
 +                      float x = co[0] + f10 * cosf(angle);
 +                      float y = co[1] + f10 * sinf(angle);
  
 -              v3d->xray = true;
 -              v3d->transp = true;
 -              while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
 -                      draw_object(scene, ar, v3d, v3da->base, dflag_depth);
 -                      MEM_freeN(v3da);
 +                      if (i % 2 == 0)
 +                              immAttrib3ub(color, 255, 0, 0);
 +                      else
 +                              immAttrib3ub(color, 255, 255, 255);
 +
 +                      immVertex2f(pos, x, y);
                }
 +              immEnd();
  
 -              
 -              v3d->xray = false;
 -              v3d->transp = false;
 +              immUnbindProgram();
 +
 +              VertexFormat_clear(format);
 +              pos = VertexFormat_add_attrib(format, "pos", COMP_F32, 2, KEEP_FLOAT);
 +
 +              immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
  
 -              glDepthMask(mask_orig);
 +              unsigned char crosshair_color[3];
 +              UI_GetThemeColor3ubv(TH_VIEW_OVERLAY, crosshair_color);
 +              immUniformColor3ubv(crosshair_color);
 +
 +              immBegin(PRIM_LINES, 8);
 +              immVertex2f(pos, co[0] - f20, co[1]);
 +              immVertex2f(pos, co[0] - f5, co[1]);
 +              immVertex2f(pos, co[0] + f5, co[1]);
 +              immVertex2f(pos, co[0] + f20, co[1]);
 +              immVertex2f(pos, co[0], co[1] - f20);
 +              immVertex2f(pos, co[0], co[1] - f5);
 +              immVertex2f(pos, co[0], co[1] + f5);
 +              immVertex2f(pos, co[0], co[1] + f20);
 +              immEnd();
 +
 +              immUnbindProgram();
        }
  }
  
@@@ -2005,275 -3017,421 +2027,259 @@@ static void draw_viewport_name(ARegion 
  }
  
  /**
 - * Store values from #RegionView3D, set when drawing.
 - * This is needed when we draw with to a viewport using a different matrix (offscreen drawing for example).
 - *
 - * Values set by #ED_view3d_update_viewmat should be handled here.
 - */
 -struct RV3DMatrixStore {
 -      float winmat[4][4];
 -      float viewmat[4][4];
 -      float viewinv[4][4];
 -      float persmat[4][4];
 -      float persinv[4][4];
 -      float viewcamtexcofac[4];
 -      float pixsize;
 -};
 -
 -struct RV3DMatrixStore *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
 -{
 -      struct RV3DMatrixStore *rv3dmat = MEM_mallocN(sizeof(*rv3dmat), __func__);
 -      copy_m4_m4(rv3dmat->winmat, rv3d->winmat);
 -      copy_m4_m4(rv3dmat->viewmat, rv3d->viewmat);
 -      copy_m4_m4(rv3dmat->persmat, rv3d->persmat);
 -      copy_m4_m4(rv3dmat->persinv, rv3d->persinv);
 -      copy_m4_m4(rv3dmat->viewinv, rv3d->viewinv);
 -      copy_v4_v4(rv3dmat->viewcamtexcofac, rv3d->viewcamtexcofac);
 -      rv3dmat->pixsize = rv3d->pixsize;
 -      return (void *)rv3dmat;
 -}
 -
 -void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, struct RV3DMatrixStore *rv3dmat)
 -{
 -      copy_m4_m4(rv3d->winmat, rv3dmat->winmat);
 -      copy_m4_m4(rv3d->viewmat, rv3dmat->viewmat);
 -      copy_m4_m4(rv3d->persmat, rv3dmat->persmat);
 -      copy_m4_m4(rv3d->persinv, rv3dmat->persinv);
 -      copy_m4_m4(rv3d->viewinv, rv3dmat->viewinv);
 -      copy_v4_v4(rv3d->viewcamtexcofac, rv3dmat->viewcamtexcofac);
 -      rv3d->pixsize = rv3dmat->pixsize;
 -}
 -
 -void ED_view3d_draw_offscreen_init(Scene *scene, View3D *v3d)
 -{
 -      /* shadow buffers, before we setup matrices */
 -      if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
 -              gpu_update_lamps_shadows_world(scene, v3d);
 -}
 -
 -/*
 - * Function to clear the view
 + * draw info beside axes in bottom left-corner:
 + * framenum, object name, bone name (if available), marker name (if available)
   */
 -static void view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar)
 -{
 -      if (scene->world && (v3d->flag3 & V3D_SHOW_WORLD)) {
 -              RegionView3D *rv3d = ar->regiondata;
 -              GPUMaterial *gpumat = GPU_material_world(scene, scene->world);
 -
 -              /* calculate full shader for background */
 -              GPU_material_bind(gpumat, 1, 1, 1.0, false, rv3d->viewmat, rv3d->viewinv, rv3d->viewcamtexcofac, (v3d->scenelock != 0));
 -              
 -              bool material_not_bound = !GPU_material_bound(gpumat);
 -
 -              if (material_not_bound) {
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPushMatrix();
 -                      glLoadIdentity();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPushMatrix();
 -                      glLoadIdentity();
 -                      glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
 -              }
 -
 -              /* Draw world */
 -              glEnable(GL_DEPTH_TEST);
 -              glDepthFunc(GL_ALWAYS);
 -              glBegin(GL_TRIANGLE_STRIP);
 -              glVertex3f(-1.0, -1.0, 1.0);
 -              glVertex3f(1.0, -1.0, 1.0);
 -              glVertex3f(-1.0, 1.0, 1.0);
 -              glVertex3f(1.0, 1.0, 1.0);
 -              glEnd();
 -
 -              if (material_not_bound) {
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPopMatrix();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPopMatrix();
 -              }
  
 -              GPU_material_unbind(gpumat);
 -              
 -              glDepthFunc(GL_LEQUAL);
 -              glDisable(GL_DEPTH_TEST);
 -      }
 -      else {
 -              if (UI_GetThemeValue(TH_SHOW_BACK_GRAD)) {
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPushMatrix();
 -                      glLoadIdentity();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPushMatrix();
 -                      glLoadIdentity();
 -
 -                      glEnable(GL_DEPTH_TEST);
 -                      glDepthFunc(GL_ALWAYS);
 -                      glBegin(GL_QUADS);
 -                      UI_ThemeColor(TH_LOW_GRAD);
 -                      glVertex3f(-1.0, -1.0, 1.0);
 -                      glVertex3f(1.0, -1.0, 1.0);
 -                      UI_ThemeColor(TH_HIGH_GRAD);
 -                      glVertex3f(1.0, 1.0, 1.0);
 -                      glVertex3f(-1.0, 1.0, 1.0);
 -                      glEnd();
 -                      glDepthFunc(GL_LEQUAL);
 -                      glDisable(GL_DEPTH_TEST);
 -
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPopMatrix();
 -
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPopMatrix();
 -              }
 -              else {
 -                      UI_ThemeClearColorAlpha(TH_HIGH_GRAD, 1.0f);
 -                      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 -              }
 -      }
 -}
 -
 -/* ED_view3d_draw_offscreen_init should be called before this to initialize
 - * stuff like shadow buffers
 - */
 -void ED_view3d_draw_offscreen(
 -        Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy,
 -        float viewmat[4][4], float winmat[4][4],
 -        bool do_bgpic, bool do_sky, bool is_persp, const char *viewname,
 -        GPUFX *fx, GPUFXSettings *fx_settings,
 -        GPUOffScreen *ofs)
 +static void draw_selected_name(Scene *scene, Object *ob, rcti *rect)
  {
 -      struct bThemeState theme_state;
 -      int bwinx, bwiny;
 -      rcti brect;
 -      bool do_compositing = false;
 -      RegionView3D *rv3d = ar->regiondata;
 +      const int cfra = CFRA;
 +      const char *msg_pin = " (Pinned)";
 +      const char *msg_sep = " : ";
  
 -      glPushMatrix();
 +      const int font_id = BLF_default();
  
 -      /* set temporary new size */
 -      bwinx = ar->winx;
 -      bwiny = ar->winy;
 -      brect = ar->winrct;
 +      char info[300];
 +      char *s = info;
 +      short offset = 1.5f * UI_UNIT_X + rect->xmin;
  
 -      ar->winx = winx;
 -      ar->winy = winy;
 -      ar->winrct.xmin = 0;
 -      ar->winrct.ymin = 0;
 -      ar->winrct.xmax = winx;
 -      ar->winrct.ymax = winy;
 +      s += sprintf(s, "(%d)", cfra);
  
 -      UI_Theme_Store(&theme_state);
 -      UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
 +      /*
 +       * info can contain:
 +       * - a frame (7 + 2)
 +       * - 3 object names (MAX_NAME)
 +       * - 2 BREAD_CRUMB_SEPARATORs (6)
 +       * - a SHAPE_KEY_PINNED marker and a trailing '\0' (9+1) - translated, so give some room!
 +       * - a marker name (MAX_NAME + 3)
 +       */
  
 -      /* set flags */
 -      G.f |= G_RENDER_OGL;
 +      /* get name of marker on current frame (if available) */
 +      const char *markern = BKE_scene_find_marker_name(scene, cfra);
  
 -      if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
 -              /* free images which can have changed on frame-change
 -               * warning! can be slow so only free animated images - campbell */
 -              GPU_free_images_anim();
 -      }
 +      /* check if there is an object */
 +      if (ob) {
 +              *s++ = ' ';
 +              s += BLI_strcpy_rlen(s, ob->id.name + 2);
  
 -      /* setup view matrices before fx or unbinding the offscreen buffers will cause issues */
 -      if ((viewname != NULL && viewname[0] != '\0') && (viewmat == NULL) && rv3d->persp == RV3D_CAMOB && v3d->camera)
 -              view3d_stereo3d_setup_offscreen(scene, v3d, ar, winmat, viewname);
 -      else
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
 +              /* name(s) to display depends on type of object */
 +              if (ob->type == OB_ARMATURE) {
 +                      bArmature *arm = ob->data;
  
 -      /* framebuffer fx needed, we need to draw offscreen first */
 -      if (v3d->fx_settings.fx_flag && fx) {
 -              GPUSSAOSettings *ssao = NULL;
 +                      /* show name of active bone too (if possible) */
 +                      if (arm->edbo) {
 +                              if (arm->act_edbone) {
 +                                      s += BLI_strcpy_rlen(s, msg_sep);
 +                                      s += BLI_strcpy_rlen(s, arm->act_edbone->name);
 +                              }
 +                      }
 +                      else if (ob->mode & OB_MODE_POSE) {
 +                              if (arm->act_bone) {
  
 -              if (v3d->drawtype < OB_SOLID) {
 -                      ssao = v3d->fx_settings.ssao;
 -                      v3d->fx_settings.ssao = NULL;
 +                                      if (arm->act_bone->layer & arm->layer) {
 +                                              s += BLI_strcpy_rlen(s, msg_sep);
 +                                              s += BLI_strcpy_rlen(s, arm->act_bone->name);
 +                                      }
 +                              }
 +                      }
                }
 +              else if (ELEM(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
 +                      /* try to display active bone and active shapekey too (if they exist) */
  
 -              do_compositing = GPU_fx_compositor_initialize_passes(fx, &ar->winrct, NULL, fx_settings);
 +                      if (ob->type == OB_MESH && ob->mode & OB_MODE_WEIGHT_PAINT) {
 +                              Object *armobj = BKE_object_pose_armature_get(ob);
 +                              if (armobj  && armobj->mode & OB_MODE_POSE) {
 +                                      bArmature *arm = armobj->data;
 +                                      if (arm->act_bone) {
 +                                              if (arm->act_bone->layer & arm->layer) {
 +                                                      s += BLI_strcpy_rlen(s, msg_sep);
 +                                                      s += BLI_strcpy_rlen(s, arm->act_bone->name);
 +                                              }
 +                                      }
 +                              }
 +                      }
  
 -              if (ssao)
 -                      v3d->fx_settings.ssao = ssao;
 -      }
 +                      Key *key = BKE_key_from_object(ob);
 +                      if (key) {
 +                              KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1);
 +                              if (kb) {
 +                                      s += BLI_strcpy_rlen(s, msg_sep);
 +                                      s += BLI_strcpy_rlen(s, kb->name);
 +                                      if (ob->shapeflag & OB_SHAPE_LOCK) {
 +                                              s += BLI_strcpy_rlen(s, IFACE_(msg_pin));
 +                                      }
 +                              }
 +                      }
 +              }
  
 -      /* clear opengl buffers */
 -      if (do_sky) {
 -              view3d_main_region_clear(scene, v3d, ar);
 +              /* color depends on whether there is a keyframe */
 +              if (id_frame_has_keyframe((ID *)ob, /* BKE_scene_frame_get(scene) */ (float)cfra, ANIMFILTER_KEYS_LOCAL))
 +                      UI_FontThemeColor(font_id, TH_TIME_KEYFRAME);
 +              else if (ED_gpencil_has_keyframe_v3d(scene, ob, cfra))
 +                      UI_FontThemeColor(font_id, TH_TIME_GP_KEYFRAME);
 +              else
 +                      UI_FontThemeColor(font_id, TH_TEXT_HI);
        }
        else {
 -              glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
 -              glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 -      }
 -
 -      /* main drawing call */
 -      view3d_draw_objects(NULL, scene, v3d, ar, NULL, do_bgpic, true, do_compositing ? fx : NULL);
 -
 -      /* post process */
 -      if (do_compositing) {
 -              if (!winmat)
 -                      is_persp = rv3d->is_persp;
 -              GPU_fx_do_composite_pass(fx, winmat, is_persp, scene, ofs);
 +              /* no object */
 +              if (ED_gpencil_has_keyframe_v3d(scene, NULL, cfra))
 +                      UI_FontThemeColor(font_id, TH_TIME_GP_KEYFRAME);
 +              else
 +                      UI_FontThemeColor(font_id, TH_TEXT_HI);
        }
  
 -      if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
 -              /* draw grease-pencil stuff */
 -              ED_region_pixelspace(ar);
 -
 -
 -              if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 -                      /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
 -                      ED_gpencil_draw_view3d(NULL, scene, v3d, ar, false);
 -              }
 -
 -              /* freeing the images again here could be done after the operator runs, leaving for now */
 -              GPU_free_images_anim();
 +      if (markern) {
 +              s += sprintf(s, " <%s>", markern);
        }
  
 -      /* restore size */
 -      ar->winx = bwinx;
 -      ar->winy = bwiny;
 -      ar->winrct = brect;
 -
 -      glPopMatrix();
 -
 -      UI_Theme_Restore(&theme_state);
 +      if (U.uiflag & USER_SHOW_ROTVIEWICON)
 +              offset = U.widget_unit + (U.rvisize * 2) + rect->xmin;
  
 -      G.f &= ~G_RENDER_OGL;
 +      BLF_draw_default(offset, 0.5f * U.widget_unit, 0.0f, info, sizeof(info));
  }
  
 -/**
 - * Set the correct matrices
 - */
 -void ED_view3d_draw_setup_view(wmWindow *win, Scene *scene, ARegion *ar, View3D *v3d, float viewmat[4][4], float winmat[4][4])
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -
 -      /* Setup the view matrix. */
 -      if (view3d_stereo3d_active(win, scene, v3d, rv3d)) {
 -              view3d_stereo3d_setup(scene, v3d, ar);
 -      }
 -      else {
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
 -      }
 -}
 +/* ******************** view loop ***************** */
  
--/**
-  * Set the correct matrices
 - * Utility func for ED_view3d_draw_offscreen
 - *
 - * \param ofs: Optional off-screen buffer, can be NULL.
 - * (avoids re-creating when doing multiple GL renders).
-- */
- static void view3d_draw_setup_view(const bContext *C, ARegion *ar)
- {
-       Scene *scene = CTX_data_scene(C);
-       View3D *v3d = CTX_wm_view3d(C);
-       RegionView3D *rv3d = ar->regiondata;
-       /* setup the view matrix */
-       if (view3d_stereo3d_active(C, scene, v3d, rv3d))
-               view3d_stereo3d_setup(scene, v3d, ar);
-       else
-               view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
- }
 -ImBuf *ED_view3d_draw_offscreen_imbuf(
 -        Scene *scene, View3D *v3d, ARegion *ar, int sizex, int sizey,
 -        unsigned int flag, bool draw_background,
 -        int alpha_mode, int samples, bool full_samples, const char *viewname,
 -        /* output vars */
 -        GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
 +static void draw_all_objects(const bContext *C, ARegion *ar, const bool only_depth, const bool use_depth)
  {
 -      RegionView3D *rv3d = ar->regiondata;
 -      ImBuf *ibuf;
 -      const bool draw_sky = (alpha_mode == R_ADDSKY);
 -
 -      /* view state */
 -      GPUFXSettings fx_settings = v3d->fx_settings;
 -      bool is_ortho = false;
 -      float winmat[4][4];
 -
 -      if (ofs && ((GPU_offscreen_width(ofs) != sizex) || (GPU_offscreen_height(ofs) != sizey))) {
 -              /* sizes differ, can't reuse */
 -              ofs = NULL;
 -      }
 +      Scene *scene = CTX_data_scene(C);
 +      SceneLayer *sl = CTX_data_scene_layer(C);
 +      View3D *v3d = CTX_wm_view3d(C);
  
 -      const bool own_ofs = (ofs == NULL);
 +      if (only_depth)
 +              glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  
 -      if (own_ofs) {
 -              /* bind */
 -              ofs = GPU_offscreen_create(sizex, sizey, full_samples ? 0 : samples, err_out);
 -              if (ofs == NULL) {
 -                      return NULL;
 -              }
 +      if (only_depth || use_depth) {
 +              glEnable(GL_DEPTH_TEST);
 +              glDepthFunc(GL_LESS);
 +              glDepthMask(GL_TRUE);
 +              v3d->zbuf = true;
        }
  
 -      ED_view3d_draw_offscreen_init(scene, v3d);
 +      for (Base *base = sl->object_bases.first; base; base = base->next) {
 +              if ((base->flag & BASE_VISIBLED) != 0) {
 +                      /* dupli drawing */
 +                      if (base->object->transflag & OB_DUPLI)
 +                              draw_dupli_objects(scene, sl, ar, v3d, base);
  
 -      GPU_offscreen_bind(ofs, true);
 +                      draw_object(scene, sl, ar, v3d, base, 0);
 +              }
 +      }
  
 -      /* read in pixels & stamp */
 -      ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
 +      if (only_depth)
 +              glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  
 -      /* render 3d view */
 -      if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
 -              CameraParams params;
 -              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
 +      if (only_depth || use_depth) {
 +              glDisable(GL_DEPTH_TEST);
 +              v3d->zbuf = false;
 +      }
 +}
  
 -              BKE_camera_params_init(&params);
 -              /* fallback for non camera objects */
 -              params.clipsta = v3d->near;
 -              params.clipend = v3d->far;
 -              BKE_camera_params_from_object(&params, camera);
 -              BKE_camera_multiview_params(&scene->r, &params, camera, viewname);
 -              BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
 -              BKE_camera_params_compute_matrix(&params);
 +/**
 + * Draw only the scene depth buffer
 + */
 +static void draw_depth_buffer(const bContext *C, ARegion *ar)
 +{
 +      draw_all_objects(C, ar, true, true);
 +}
  
 -              BKE_camera_to_gpu_dof(camera, &fx_settings);
 +/**
 + * Required if the shaders need it or external engines
 + * (e.g., Cycles requires depth buffer handled separately).
 + */
 +static void view3d_draw_prerender_buffers(const bContext *C, ARegion *ar, DrawData *draw_data)
 +{
 +      View3D *v3d = CTX_wm_view3d(C);
  
 -              is_ortho = params.is_ortho;
 -              copy_m4_m4(winmat, params.winmat);
 +      /* TODO viewport */
 +      if (draw_data->is_render && ((!draw_data->clip_border) || (v3d->drawtype <= OB_WIRE))) {
 +              draw_depth_buffer(C, ar);
        }
 -      else {
 -              rctf viewplane;
 -              float clipsta, clipend;
 +}
  
 -              is_ortho = ED_view3d_viewplane_get(v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend, NULL);
 -              if (is_ortho) {
 -                      orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend);
 -              }
 -              else {
 -                      perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
 -              }
 +/**
 + * Draw all the plates that will fill the RGBD buffer
 + */
 +static void view3d_draw_solid_plates(const bContext *C, ARegion *ar, DrawData *draw_data)
 +{
 +      /* realtime plates */
 +      if ((!draw_data->is_render) || draw_data->clip_border) {
 +              view3d_draw_render_solid_surfaces(C, ar, true);
 +              view3d_draw_render_transparent_surfaces(C);
 +              view3d_draw_post_draw(C);
        }
  
 -      if ((samples && full_samples) == 0) {
 -              /* Single-pass render, common case */
 -              ED_view3d_draw_offscreen(
 -                      scene, v3d, ar, sizex, sizey, NULL, winmat,
 -                      draw_background, draw_sky, !is_ortho, viewname,
 -                      fx, &fx_settings, ofs);
 +      /* offline plates */
 +      if (draw_data->is_render) {
 +              Scene *scene = CTX_data_scene(C);
 +              View3D *v3d = CTX_wm_view3d(C);
  
 -              if (ibuf->rect_float) {
 -                      GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
 -              }
 -              else if (ibuf->rect) {
 -                      GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
 -              }
 +              /* TODO: move this outside of solid plates, after solid & before other 3D elements */
 +              view3d_draw_render_draw(C, scene, ar, v3d, draw_data->clip_border, &draw_data->border_rect);
        }
 -      else {
 -              /* Multi-pass render, use accumulation buffer & jitter for 'full' oversampling.
 -               * Use because OpenGL may use a lower quality MSAA, and only over-sample edges. */
 -              static float jit_ofs[32][2];
 -              float winmat_jitter[4][4];
 -              /* use imbuf as temp storage, before writing into it from accumulation buffer */
 -              unsigned char *rect_temp = ibuf->rect ? (void *)ibuf->rect : (void *)ibuf->rect_float;
 -              unsigned int *accum_buffer = MEM_mallocN(sizex * sizey * sizeof(int[4]), "accum1");
 -              unsigned int i;
 -              int j;
  
 -              BLI_jitter_init(jit_ofs, samples);
 +#if VIEW3D_DRAW_DEBUG
 +      view3d_draw_debug_post_solid(C, ar, draw_data);
 +#endif
 +}
  
 -              /* first sample buffer, also initializes 'rv3d->persmat' */
 -              ED_view3d_draw_offscreen(
 -                      scene, v3d, ar, sizex, sizey, NULL, winmat,
 -                      draw_background, draw_sky, !is_ortho, viewname,
 -                      fx, &fx_settings, ofs);
 -              GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, rect_temp);
 +/**
 + * Wires, outline, ...
 + */
 +static void view3d_draw_geometry_overlay(const bContext *C)
 +{
 +      view3d_draw_wire_plates(C);
 +      view3d_draw_outline_plates(C);
 +}
  
 -              i = sizex * sizey * 4;
 -              while (i--) {
 -                      accum_buffer[i] = rect_temp[i];
 -              }
 +/* drawing cameras, lamps, ... */
 +static void view3d_draw_non_meshes(const bContext *C, ARegion *ar)
 +{
 +      /* TODO viewport
 +       * for now we draw them all, in the near future
 +       * we filter them based on the plates/layers
 +       */
 +      Scene *scene = CTX_data_scene(C);
 +      SceneLayer *sl = CTX_data_scene_layer(C);
 +      View3D *v3d = CTX_wm_view3d(C);
 +      RegionView3D *rv3d = ar->regiondata;
  
 -              /* skip the first sample */
 -              for (j = 1; j < samples; j++) {
 -                      copy_m4_m4(winmat_jitter, winmat);
 -                      window_translate_m4(
 -                              winmat_jitter, rv3d->persmat,
 -                              (jit_ofs[j][0] * 2.0f) / sizex,
 -                              (jit_ofs[j][1] * 2.0f) / sizey);
 +      bool is_boundingbox = ((v3d->drawtype == OB_BOUNDBOX) ||
 +                              ((v3d->drawtype == OB_RENDER) && (v3d->prev_drawtype == OB_BOUNDBOX)));
  
 -                      ED_view3d_draw_offscreen(
 -                              scene, v3d, ar, sizex, sizey, NULL, winmat_jitter,
 -                              draw_background, draw_sky, !is_ortho, viewname,
 -                              fx, &fx_settings, ofs);
 -                      GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, rect_temp);
 +      glEnable(GL_DEPTH_TEST);
 +      /* TODO Viewport
 +       * we are already temporarily writing to zbuffer in draw_object()
 +       * for now let's avoid writing again to zbuffer to prevent glitches
 +       */
  
 -                      i = sizex * sizey * 4;
 -                      while (i--) {
 -                              accum_buffer[i] += rect_temp[i];
 -                      }
 -              }
 +      for (Base *base = sl->object_bases.first; base; base = base->next) {
 +              if ((base->flag & BASE_VISIBLED) != 0) {
 +                      Object *ob = base->object;
  
 -              if (ibuf->rect_float) {
 -                      float *rect_float = ibuf->rect_float;
 -                      i = sizex * sizey * 4;
 -                      while (i--) {
 -                              rect_float[i] = (float)(accum_buffer[i] / samples) * (1.0f / 255.0f);
 -                      }
 -              }
 -              else {
 -                      unsigned char *rect_ub = (unsigned char *)ibuf->rect;
 -                      i = sizex * sizey * 4;
 -                      while (i--) {
 -                              rect_ub[i] = accum_buffer[i] / samples;
 -                      }
 +                      unsigned char ob_wire_col[4];
 +                      draw_object_wire_color(scene, sl, base, ob_wire_col);
 +                      view3d_draw_non_mesh(scene, sl, ob, base, v3d, rv3d, is_boundingbox, ob_wire_col);
                }
 -
 -              MEM_freeN(accum_buffer);
        }
  
 -      /* unbind */
 -      GPU_offscreen_unbind(ofs, true);
 +      glDisable(GL_DEPTH_TEST);
 +}
  
 -      if (own_ofs) {
 -              GPU_offscreen_free(ofs);
 -      }
 +/**
 +* Parent lines, grid, ...
 +*/
 +static void view3d_draw_other_elements(const bContext *C, ARegion *ar)
 +{
 +      view3d_draw_grid(C, ar);
  
 -      if (ibuf->rect_float && ibuf->rect)
 -              IMB_rect_from_float(ibuf);
 +#ifdef WITH_INPUT_NDOF
 +      RegionView3D *rv3d = ar->regiondata;
  
 -      return ibuf;
 +      if ((U.ndof_flag & NDOF_SHOW_GUIDE) && ((rv3d->viewlock & RV3D_LOCKED) == 0) && (rv3d->persp != RV3D_CAMOB))
 +              /* TODO: draw something else (but not this) during fly mode */
 +              draw_rotation_guide(rv3d);
 +#endif
  }
  
  /**
@@@ -2363,410 -3559,381 +2369,410 @@@ void view3d_draw_region_info(const bCon
  #endif
  }
  
 -static bool view3d_main_region_do_render_draw(Scene *scene)
 +/**
 + * This could run once per view, or even in parallel
 + * for each of them. What is a "view"?
 + * - a viewport with the camera elsewhere
 + * - left/right stereo
 + * - panorama / fisheye individual cubemap faces
 + */
 +static void view3d_draw_view(const bContext *C, ARegion *ar, DrawData *draw_data)
  {
 -      RenderEngineType *type = RE_engines_find(scene->r.engine);
 +      /* TODO - Technically this should be drawn to a few FBO, so we can handle
 +       * compositing better, but for now this will get the ball rolling (dfelinto) */
  
 -      return (type && type->view_update && type->view_draw);
 -}
 +      glDepthMask(GL_TRUE); /* should be set by default */
 +      glClear(GL_DEPTH_BUFFER_BIT);
 +//    glDisable(GL_DEPTH_TEST); /* should be set by default */
  
 -bool ED_view3d_calc_render_border(Scene *scene, View3D *v3d, ARegion *ar, rcti *rect)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -      rctf viewborder;
 -      bool use_border;
 +      view3d_draw_background(C); /* clears/overwrites entire color buffer */
  
-       view3d_draw_setup_view(C, ar);
 -      /* test if there is a 3d view rendering */
 -      if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene))
 -              return false;
++      ED_view3d_draw_setup_view(CTX_wm_window(C), CTX_data_scene(C), ar, CTX_wm_view3d(C), NULL, NULL);
  
 -      /* test if there is a border render */
 -      if (rv3d->persp == RV3D_CAMOB)
 -              use_border = (scene->r.mode & R_BORDER) != 0;
 -      else
 -              use_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
 -      
 -      if (!use_border)
 -              return false;
 +      glEnable(GL_DEPTH_TEST);
 +      glDepthFunc(GL_LEQUAL);
 +      view3d_draw_prerender_buffers(C, ar, draw_data); /* depth pre-pass */
  
 -      /* compute border */
 -      if (rv3d->persp == RV3D_CAMOB) {
 -              ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
 +//    glDepthFunc(GL_EQUAL); /* TODO: do this after separating surfaces from wires */
 +//    glDepthMask(GL_FALSE); /* same TODO as above */
 +      view3d_draw_solid_plates(C, ar, draw_data);
  
 -              rect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
 -              rect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
 -              rect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
 -              rect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
 -      }
 -      else {
 -              rect->xmin = v3d->render_border.xmin * ar->winx;
 -              rect->xmax = v3d->render_border.xmax * ar->winx;
 -              rect->ymin = v3d->render_border.ymin * ar->winy;
 -              rect->ymax = v3d->render_border.ymax * ar->winy;
 -      }
 +//    glDepthFunc(GL_LEQUAL); /* same TODO as above */
 +//    glDepthMask(GL_TRUE); /* same TODO as above */
 +
 +      view3d_draw_geometry_overlay(C);
 +      view3d_draw_non_meshes(C, ar);
 +      view3d_draw_other_elements(C, ar);
 +      view3d_draw_tool_ui(C);
 +      view3d_draw_reference_images(C);
 +      view3d_draw_manipulators(C, ar);
  
 -      BLI_rcti_translate(rect, ar->winrct.xmin, ar->winrct.ymin);
 -      BLI_rcti_isect(&ar->winrct, rect, rect);
 +      glDisable(GL_DEPTH_TEST);
  
 -      return true;
 +      view3d_draw_region_info(C, ar, 0);
 +
 +#if VIEW3D_DRAW_DEBUG
 +      view3d_draw_debug(C, ar, draw_data);
 +#endif
  }
  
 -static bool view3d_main_region_draw_engine(const bContext *C, Scene *scene,
 -                                         ARegion *ar, View3D *v3d,
 -                                         bool clip_border, const rcti *border_rect)
 +static void view3d_draw_view_new(const bContext *C, ARegion *ar, DrawData *UNUSED(draw_data))
  {
-       view3d_draw_setup_view(C, ar);
 -      RegionView3D *rv3d = ar->regiondata;
 -      RenderEngineType *type;
 -      GLint scissor[4];
++      ED_view3d_draw_setup_view(CTX_wm_window(C), CTX_data_scene(C), ar, CTX_wm_view3d(C), NULL, NULL);
  
 -      /* create render engine */
 -      if (!rv3d->render_engine) {
 -              RenderEngine *engine;
 +      /* Only 100% compliant on new spec goes bellow */
 +      DRW_draw_view(C);
 +}
  
 -              type = RE_engines_find(scene->r.engine);
 +void view3d_main_region_draw(const bContext *C, ARegion *ar)
 +{
 +      Scene *scene = CTX_data_scene(C);
 +      View3D *v3d = CTX_wm_view3d(C);
 +      RegionView3D *rv3d = ar->regiondata;
 +      /* TODO layers - In the future we should get RE from Layers */
 +      RenderEngineType *type = RE_engines_find(scene->r.engine);
  
 -              if (!(type->view_update && type->view_draw))
 -                      return false;
 +      if (IS_VIEWPORT_LEGACY(v3d) && ((type->flag & RE_USE_LEGACY_PIPELINE) != 0)) {
 +              view3d_main_region_draw_legacy(C, ar);
 +              return;
 +      }
  
 -              engine = RE_engine_create_ex(type, true);
 +      if (!rv3d->viewport)
 +              rv3d->viewport = GPU_viewport_create();
  
 -              engine->tile_x = scene->r.tilex;
 -              engine->tile_y = scene->r.tiley;
 +      /* TODO viewport - there is so much to be done, in fact a lot will need to happen in the space_view3d.c
 +       * before we even call the drawing routine, but let's move on for now (dfelinto)
 +       * but this is a provisory way to start seeing things in the viewport */
 +      DrawData draw_data;
 +      view3d_draw_data_init(C, ar, rv3d, &draw_data);
  
 -              type->view_update(engine, C);
 +      GPU_viewport_bind(rv3d->viewport, &ar->winrct);
  
 -              rv3d->render_engine = engine;
 +      if ((type->flag & RE_USE_LEGACY_PIPELINE) == 0) {
 +              view3d_draw_view_new(C, ar, &draw_data);
 +      }
 +      else {
 +              view3d_draw_view(C, ar, &draw_data);
        }
  
 -      /* setup view matrices */
 -      view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
 -
 -      /* background draw */
 -      ED_region_pixelspace(ar);
 +      GPU_viewport_unbind(rv3d->viewport);
  
 -      if (clip_border) {
 -              /* for border draw, we only need to clear a subset of the 3d view */
 -              if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
 -                      glGetIntegerv(GL_SCISSOR_BOX, scissor);
 -                      glScissor(border_rect->xmin, border_rect->ymin,
 -                                BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
 -              }
 -              else {
 -                      return false;
 -              }
 -      }
 +      v3d->flag |= V3D_INVALID_BACKBUF;
 +}
  
 -      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
 -      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  
 -      if (v3d->flag & V3D_DISPBGPICS)
 -              view3d_draw_bgpic_test(scene, ar, v3d, false, true);
 -      else
 -              fdrawcheckerboard(0, 0, ar->winx, ar->winy);
 +/* -------------------------------------------------------------------- */
  
 -      /* render result draw */
 -      type = rv3d->render_engine->type;
 -      type->view_draw(rv3d->render_engine, C);
 +/** \name Offscreen Drawing
 + * \{ */
  
 -      if (v3d->flag & V3D_DISPBGPICS)
 -              view3d_draw_bgpic_test(scene, ar, v3d, true, true);
 +static void view3d_stereo3d_setup_offscreen(
 +        Scene *scene, View3D *v3d, ARegion *ar,
 +        float winmat[4][4], const char *viewname)
 +{
 +      /* update the viewport matrices with the new camera */
 +      if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
 +              float viewmat[4][4];
 +              const bool is_left = STREQ(viewname, STEREO_LEFT_NAME);
  
 -      if (clip_border) {
 -              /* restore scissor as it was before */
 -              glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
 +              BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
 +              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
        }
 +      else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
 +              float viewmat[4][4];
 +              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
  
 -      return true;
 +              BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
 +              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
 +      }
  }
  
 -static void view3d_main_region_draw_engine_info(View3D *v3d, RegionView3D *rv3d, ARegion *ar, bool render_border)
 +void ED_view3d_draw_offscreen_init(Scene *scene, SceneLayer *sl, View3D *v3d)
  {
 -      float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
 -
 -      if (!rv3d->render_engine || !rv3d->render_engine->text[0])
 -              return;
 -      
 -      if (render_border) {
 -              /* draw darkened background color. no alpha because border render does
 -               * partial redraw and will not redraw the region behind this info bar */
 -              float alpha = 1.0f - fill_color[3];
 -              Camera *camera = ED_view3d_camera_data_get(v3d, rv3d);
 -
 -              if (camera) {
 -                      if (camera->flag & CAM_SHOWPASSEPARTOUT) {
 -                              alpha *= (1.0f - camera->passepartalpha);
 -                      }
 +      RenderEngineType *type = RE_engines_find(scene->r.engine);
 +      if (IS_VIEWPORT_LEGACY(v3d) && ((type->flag & RE_USE_LEGACY_PIPELINE) != 0)) {
 +              /* shadow buffers, before we setup matrices */
 +              if (draw_glsl_material(scene, sl, NULL, v3d, v3d->drawtype)) {
 +                      VP_deprecated_gpu_update_lamps_shadows_world(scene, v3d);
                }
 -
 -              UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
 -              mul_v3_fl(fill_color, alpha);
 -              fill_color[3] = 1.0f;
        }
 -
 -      ED_region_info_draw(ar, rv3d->render_engine->text, fill_color, true);
  }
  
 -static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d)
 +/*
 + * Function to clear the view
 + */
 +static void view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar)
  {
 -      if ((scene->r.scemode & R_MULTIVIEW) == 0) {
 -              return false;
 -      }
 +      glClear(GL_DEPTH_BUFFER_BIT);
  
 -      if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB) {
 -              return false;
 +      if (scene->world && (v3d->flag3 & V3D_SHOW_WORLD)) {
 +              VP_view3d_draw_background_world(scene, v3d, ar->regiondata);
        }
 -
 -      switch (v3d->stereo3d_camera) {
 -              case STEREO_MONO_ID:
 -                      return false;
 -                      break;
 -              case STEREO_3D_ID:
 -                      /* win will be NULL when calling this from the selection or draw loop. */
 -                      if ((win == NULL) || (WM_stereo3d_enabled(win, true) == false)) {
 -                              return false;
 -                      }
 -                      if (((scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) != 0) &&
 -                          !BKE_scene_multiview_is_stereo3d(&scene->r))
 -                      {
 -                              return false;
 -                      }
 -                      break;
 -              /* We always need the stereo calculation for left and right cameras. */
 -              case STEREO_LEFT_ID:
 -              case STEREO_RIGHT_ID:
 -              default:
 -                      break;
 +      else {
 +              VP_view3d_draw_background_none();
        }
 -      return true;
  }
  
 -/* setup the view and win matrices for the multiview cameras
 - *
 - * unlike view3d_stereo3d_setup_offscreen, when view3d_stereo3d_setup is called
 - * we have no winmatrix (i.e., projection matrix) defined at that time.
 - * Since the camera and the camera shift are needed for the winmat calculation
 - * we do a small hack to replace it temporarily so we don't need to change the
 - * view3d)main_region_setup_view() code to account for that.
 +/* ED_view3d_draw_offscreen_init should be called before this to initialize
 + * stuff like shadow buffers
   */
 -static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar)
 +void ED_view3d_draw_offscreen(
 +        Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy,
 +        float viewmat[4][4], float winmat[4][4],
 +        bool do_bgpic, bool do_sky, bool is_persp, const char *viewname,
 +        GPUFX *fx, GPUFXSettings *fx_settings,
 +        GPUOffScreen *ofs)
  {
 -      bool is_left;
 -      const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
 -      const char *viewname;
 +      bool do_compositing = false;
 +      RegionView3D *rv3d = ar->regiondata;
  
 -      /* show only left or right camera */
 -      if (v3d->stereo3d_camera != STEREO_3D_ID)
 -              v3d->multiview_eye = v3d->stereo3d_camera;
 +      /* set temporary new size */
 +      int bwinx = ar->winx;
 +      int bwiny = ar->winy;
 +      rcti brect = ar->winrct;
  
 -      is_left = v3d->multiview_eye == STEREO_LEFT_ID;
 -      viewname = names[is_left ? STEREO_LEFT_ID : STEREO_RIGHT_ID];
 +      ar->winx = winx;
 +      ar->winy = winy;
 +      ar->winrct.xmin = 0;
 +      ar->winrct.ymin = 0;
 +      ar->winrct.xmax = winx;
 +      ar->winrct.ymax = winy;
  
 -      /* update the viewport matrices with the new camera */
 -      if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
 -              Camera *data;
 -              float viewmat[4][4];
 -              float shiftx;
 +      struct bThemeState theme_state;
 +      UI_Theme_Store(&theme_state);
 +      UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
  
 -              data = (Camera *)v3d->camera->data;
 -              shiftx = data->shiftx;
 +      /* set flags */
 +      G.f |= G_RENDER_OGL;
  
 -              BLI_lock_thread(LOCK_VIEW3D);
 -              data->shiftx = BKE_camera_multiview_shift_x(&scene->r, v3d->camera, viewname);
 +      if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
 +              /* free images which can have changed on frame-change
 +               * warning! can be slow so only free animated images - campbell */
 +              GPU_free_images_anim();
 +      }
  
 -              BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
 +      gpuPushProjectionMatrix();
 +      gpuLoadIdentity();
 +      gpuPushMatrix();
 +      gpuLoadIdentity();
  
 -              data->shiftx = shiftx;
 -              BLI_unlock_thread(LOCK_VIEW3D);
 +      /* clear opengl buffers */
 +      if (do_sky) {
 +              view3d_main_region_clear(scene, v3d, ar);
 +      }
 +      else {
 +              glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
 +              glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        }
 -      else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
 -              float viewmat[4][4];
 -              Object *view_ob = v3d->camera;
 -              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
  
 -              BLI_lock_thread(LOCK_VIEW3D);
 -              v3d->camera = camera;
 +      if ((viewname != NULL && viewname[0] != '\0') && (viewmat == NULL) && rv3d->persp == RV3D_CAMOB && v3d->camera)
 +              view3d_stereo3d_setup_offscreen(scene, v3d, ar, winmat, viewname);
 +      else
 +              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
  
 -              BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
 +      /* main drawing call */
 +      RenderEngineType *type = RE_engines_find(scene->r.engine);
 +      if (IS_VIEWPORT_LEGACY(v3d) && ((type->flag & RE_USE_LEGACY_PIPELINE) != 0)) {
  
 -              v3d->camera = view_ob;
 -              BLI_unlock_thread(LOCK_VIEW3D);
 +              /* framebuffer fx needed, we need to draw offscreen first */
 +              if (v3d->fx_settings.fx_flag && fx) {
 +                      GPUSSAOSettings *ssao = NULL;
 +
 +                      if (v3d->drawtype < OB_SOLID) {
 +                              ssao = v3d->fx_settings.ssao;
 +                              v3d->fx_settings.ssao = NULL;
 +                      }
 +
 +                      do_compositing = GPU_fx_compositor_initialize_passes(fx, &ar->winrct, NULL, fx_settings);
 +
 +                      if (ssao)
 +                              v3d->fx_settings.ssao = ssao;
 +              }
 +
 +              VP_deprecated_view3d_draw_objects(NULL, scene, v3d, ar, NULL, do_bgpic, true, do_compositing ? fx : NULL);
 +
 +              /* post process */
 +              if (do_compositing) {
 +                      if (!winmat)
 +                              is_persp = rv3d->is_persp;
 +                      GPU_fx_do_composite_pass(fx, winmat, is_persp, scene, ofs);
 +              }
 +
 +              if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
 +                      /* draw grease-pencil stuff */
 +                      ED_region_pixelspace(ar);
 +
 +                      if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 +                              /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
 +                              ED_gpencil_draw_view3d(NULL, scene, v3d, ar, false);
 +                      }
 +
 +                      /* freeing the images again here could be done after the operator runs, leaving for now */
 +                      GPU_free_images_anim();
 +              }
 +      }
 +      else {
 +              /* XXX, should take depsgraph as arg */
 +              DRW_draw_render_loop_offscreen(scene->depsgraph, ar, v3d, ofs);
        }
 +
 +      /* restore size */
 +      ar->winx = bwinx;
 +      ar->winy = bwiny;
 +      ar->winrct = brect;
 +
 +      gpuPopProjectionMatrix();
 +      gpuPopMatrix();
 +
 +      UI_Theme_Restore(&theme_state);
 +
 +      G.f &= ~G_RENDER_OGL;
  }
  
 -static void view3d_stereo3d_setup_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
 -                                            float winmat[4][4], const char *viewname)
 +/**
 + * Utility func for ED_view3d_draw_offscreen
 + *
 + * \param ofs: Optional off-screen buffer, can be NULL.
 + * (avoids re-creating when doing multiple GL renders).
 + */
 +ImBuf *ED_view3d_draw_offscreen_imbuf(
 +        Scene *scene, SceneLayer *sl, View3D *v3d, ARegion *ar, int sizex, int sizey,
 +        unsigned int flag, bool draw_background,
 +        int alpha_mode, int samples, bool full_samples, const char *viewname,
 +        /* output vars */
 +        GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
  {
 -      /* update the viewport matrices with the new camera */
 -      if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
 -              float viewmat[4][4];
 -              const bool is_left = STREQ(viewname, STEREO_LEFT_NAME);
 +      RegionView3D *rv3d = ar->regiondata;
 +      const bool draw_sky = (alpha_mode == R_ADDSKY);
  
 -              BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
 -      }
 -      else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
 -              float viewmat[4][4];
 -              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
 +      /* view state */
 +      GPUFXSettings fx_settings = v3d->fx_settings;
 +      bool is_ortho = false;
 +      float winmat[4][4];
  
 -              BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
 -              view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
 +      if (ofs && ((GPU_offscreen_width(ofs) != sizex) || (GPU_offscreen_height(ofs) != sizey))) {
 +              /* sizes differ, can't reuse */
 +              ofs = NULL;
        }
 -}
  
 -#ifdef WITH_GAMEENGINE
 -static void update_lods(Scene *scene, float camera_pos[3])
 -{
 -      Scene *sce_iter;
 -      Base *base;
 -      Object *ob;
 +      const bool own_ofs = (ofs == NULL);
  
 -      for (SETLOOPER(scene, sce_iter, base)) {
 -              ob = base->object;
 -              BKE_object_lod_update(ob, camera_pos);
 +      if (own_ofs) {
 +              /* bind */
 +              ofs = GPU_offscreen_create(sizex, sizey, full_samples ? 0 : samples, err_out);
 +              if (ofs == NULL) {
 +                      return NULL;
 +              }
        }
 -}
 -#endif
  
 -static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, View3D *v3d,
 -                                          ARegion *ar, const char **grid_unit)
 -{
 -      wmWindow *win = CTX_wm_window(C);
 -      RegionView3D *rv3d = ar->regiondata;
 -      unsigned int lay_used = v3d->lay_used;
 -      
 -      /* post processing */
 -      bool do_compositing = false;
 -      
 -      /* shadow buffers, before we setup matrices */
 -      if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
 -              gpu_update_lamps_shadows_world(scene, v3d);
 -
 -      /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
 -      if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
 -              rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
 -              GPU_default_lights();
 -      }
 +      ED_view3d_draw_offscreen_init(scene, sl, v3d);
 +
 +      GPU_offscreen_bind(ofs, true);
 +
 +      /* read in pixels & stamp */
 +      ImBuf *ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
 +
 +      /* render 3d view */
 +      if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
 +              CameraParams params;
 +              Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
  
 -      /* Setup the view matrix. */
 -      ED_view3d_draw_setup_view(CTX_wm_window(C), scene, ar, v3d, NULL, NULL);
 +              BKE_camera_params_init(&params);
 +              /* fallback for non camera objects */
 +              params.clipsta = v3d->near;
 +              params.clipend = v3d->far;
 +              BKE_camera_params_from_object(&params, camera);
 +              BKE_camera_multiview_params(&scene->r, &params, camera, viewname);
 +              BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
 +              BKE_camera_params_compute_matrix(&params);
  
 -      rv3d->rflag &= ~RV3D_IS_GAME_ENGINE;
 -#ifdef WITH_GAMEENGINE
 -      if (STREQ(scene->r.engine, RE_engine_id_BLENDER_GAME)) {
 -              rv3d->rflag |= RV3D_IS_GAME_ENGINE;
 +              BKE_camera_to_gpu_dof(camera, &fx_settings);
  
 -              /* Make sure LoDs are up to date */
 -              update_lods(scene, rv3d->viewinv[3]);
 +              is_ortho = params.is_ortho;
 +              copy_m4_m4(winmat, params.winmat);
        }
 -#endif
 +      else {
 +              rctf viewplane;
 +              float clipsta, clipend;
  
 -      /* framebuffer fx needed, we need to draw offscreen first */
 -      if (v3d->fx_settings.fx_flag && v3d->drawtype >= OB_SOLID) {
 -              GPUFXSettings fx_settings;
 -              BKE_screen_gpu_fx_validate(&v3d->fx_settings);
 -              fx_settings = v3d->fx_settings;
 -              if (!rv3d->compositor)
 -                      rv3d->compositor = GPU_fx_compositor_create();
 -              
 -              if (rv3d->persp == RV3D_CAMOB && v3d->camera)
 -                      BKE_camera_to_gpu_dof(v3d->camera, &fx_settings);
 +              is_ortho = ED_view3d_viewplane_get(v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend, NULL);
 +              if (is_ortho) {
 +                      orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend);
 +              }
                else {
 -                      fx_settings.dof = NULL;
 +                      perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
                }
 -
 -              do_compositing = GPU_fx_compositor_initialize_passes(rv3d->compositor, &ar->winrct, &ar->drawrct, &fx_settings);
 -      }
 -      
 -      /* clear the background */
 -      view3d_main_region_clear(scene, v3d, ar);
 -
 -      /* enables anti-aliasing for 3D view drawing */
 -      if (win->multisamples != USER_MULTISAMPLE_NONE) {
 -              glEnable(GL_MULTISAMPLE);
        }
  
 -      /* main drawing call */
 -      view3d_draw_objects(C, scene, v3d, ar, grid_unit, true, false, do_compositing ? rv3d->compositor : NULL);
 +      if ((samples && full_samples) == 0) {
 +              /* Single-pass render, common case */
 +              ED_view3d_draw_offscreen(
 +                      scene, v3d, ar, sizex, sizey, NULL, winmat,
 +                      draw_background, draw_sky, !is_ortho, viewname,
 +                      fx, &fx_settings, ofs);
  
 -      /* post process */
 -      if (do_compositing) {
 -              GPU_fx_do_composite_pass(rv3d->compositor, rv3d->winmat, rv3d->is_persp, scene, NULL);
 +              if (ibuf->rect_float) {
 +                      GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
 +              }
 +              else if (ibuf->rect) {
 +                      GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
 +              }
        }
 +      else {
 +              /* Multi-pass render, use accumulation buffer & jitter for 'full' oversampling.
 +               * Use because OpenGL may use a lower quality MSAA, and only over-sample edges. */
 +              static float jit_ofs[32][2];
 +              float winmat_jitter[4][4];
 +              /* use imbuf as temp storage, before writing into it from accumulation buffer */
 +              unsigned char *rect_temp = ibuf->rect ? (void *)ibuf->rect : (void *)ibuf->rect_float;
 +              unsigned int *accum_buffer = MEM_mallocN(sizex * sizey * sizeof(int[4]), "accum1");
  
 -      /* Disable back anti-aliasing */
 -      if (win->multisamples != USER_MULTISAMPLE_NONE) {
 -              glDisable(GL_MULTISAMPLE);
 -      }
 +              BLI_jitter_init(jit_ofs, samples);
  
 -      if (v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
 -              /* find header and force tag redraw */
 -              ScrArea *sa = CTX_wm_area(C);
 -              ARegion *ar_header = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
 -              ED_region_tag_redraw(ar_header); /* can be NULL */
 -      }
 +              /* first sample buffer, also initializes 'rv3d->persmat' */
 +              ED_view3d_draw_offscreen(
 +                      scene, v3d, ar, sizex, sizey, NULL, winmat,
 +                      draw_background, draw_sky, !is_ortho, viewname,
 +                      fx, &fx_settings, ofs);
 +              GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, rect_temp);
  
 -      if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
 -              BDR_drawSketch(C);
 -      }
 +              unsigned i = sizex * sizey * 4;
 +              while (i--) {
 +                      accum_buffer[i] = rect_temp[i];
 +              }
  
 -#ifdef WITH_INPUT_NDOF
 -      if ((U.ndof_flag & NDOF_SHOW_GUIDE) && ((rv3d->viewlock & RV3D_LOCKED) == 0) && (rv3d->persp != RV3D_CAMOB))
 -              /* TODO: draw something else (but not this) during fly mode */
 -              draw_rotation_guide(rv3d);
 -#endif
 -}
 +              /* skip the first sample */
 +              for (int j = 1; j < samples; j++) {
 +                      copy_m4_m4(winmat_jitter, winmat);
 +                      window_translate_m4(
 +                              winmat_jitter, rv3d->persmat,
 +                              (jit_ofs[j][0] * 2.0f) / sizex,
 +                              (jit_ofs[j][1] * 2.0f) / sizey);
  
 -static bool is_cursor_visible(Scene *scene)
 -{
 -      Object *ob = OBACT;
 +                      ED_view3d_draw_offscreen(
 +                              scene, v3d, ar, sizex, sizey, NULL, winmat_jitter,
 +                              draw_background, draw_sky, !is_ortho, viewname,
 +                              fx, &fx_settings, ofs);
 +                      GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, rect_temp);
  
 -      /* don't draw cursor in paint modes, but with a few exceptions */
 -      if (ob && ob->mode & OB_MODE_ALL_PAINT) {
 -              /* exception: object is in weight paint and has deforming armature in pose mode */
 -              if (ob->mode & OB_MODE_WEIGHT_PAINT) {
 -                      if (BKE_object_pose_armature_get(ob) != NULL) {
 -                              return true;
 +                      i = sizex * sizey * 4;
 +                      while (i--) {
 +                              accum_buffer[i] += rect_temp[i];
                        }
                }
 -              /* exception: object in texture paint mode, clone brush, use_clone_layer disabled */
 -              else if (ob->mode & OB_MODE_TEXTURE_PAINT) {
 -                      const Paint *p = BKE_paint_get_active(scene);
  
 -                      if (p && p->brush && p->brush->imagepaint_tool == PAINT_TOOL_CLONE) {
 -                              if ((scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_LAYER_CLONE) == 0) {
 -                                      return true;
 -                              }
 +              if (ibuf->rect_float) {
 +                      float *rect_float = ibuf->rect_float;
 +                      i = sizex * sizey * 4;
 +                      while (i--) {
 +                              rect_float[i] = (float)(accum_buffer[i] / samples) * (1.0f / 255.0f);
 +                      }
 +              }
 +              else {
 +                      unsigned char *rect_ub = (unsigned char *)ibuf->rect;
 +                      i = sizex * sizey * 4;
 +                      while (i--) {
 +                              rect_ub[i] = accum_buffer[i] / samples;
                        }
                }
  
@@@ -2873,79 -4020,142 +2879,79 @@@ void VP_legacy_drawcursor(Scene *scene
        }
  }
  
 -void view3d_main_region_draw(const bContext *C, ARegion *ar)
 +void VP_legacy_draw_view_axis(RegionView3D *rv3d, rcti *rect)
  {
 -      Scene *scene = CTX_data_scene(C);
 -      View3D *v3d = CTX_wm_view3d(C);
 -      const char *grid_unit = NULL;
 -      rcti border_rect;
 -      bool render_border, clip_border;
 +      draw_view_axis(rv3d, rect);
 +}
  
 -      /* if we only redraw render border area, skip opengl draw and also
 -       * don't do scissor because it's already set */
 -      render_border = ED_view3d_calc_render_border(scene, v3d, ar, &border_rect);
 -      clip_border = (render_border && !BLI_rcti_compare(&ar->drawrct, &border_rect));
 +void VP_legacy_draw_viewport_name(ARegion *ar, View3D *v3d, rcti *rect)
 +{
 +      draw_viewport_name(ar, v3d, rect);
 +}
  
 -      /* draw viewport using opengl */
 -      if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene) || clip_border) {
 -              view3d_main_region_draw_objects(C, scene, v3d, ar, &grid_unit);
 -              
 -#ifdef DEBUG_DRAW
 -              bl_debug_draw();
 -#endif
 -              if (G.debug & G_DEBUG_SIMDATA)
 -                      draw_sim_debug_data(scene, v3d, ar);
 -              
 -              ED_region_pixelspace(ar);
 -      }
 +void VP_legacy_draw_selected_name(Scene *scene, Object *ob, rcti *rect)
 +{
 +      draw_selected_name(scene, ob, rect);
 +}
 +
 +void VP_legacy_drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
 +{
 +      drawgrid(unit, ar, v3d, grid_unit);
 +}
  
 -      /* draw viewport using external renderer */
 -      if (v3d->drawtype == OB_RENDER)
 -              view3d_main_region_draw_engine(C, scene, ar, v3d, clip_border, &border_rect);
 -      
 -      view3d_main_region_draw_info(C, scene, ar, v3d, grid_unit, render_border);
 +void VP_legacy_drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
 +{
 +      drawfloor(scene, v3d, grid_unit, write_depth);
 +}
  
 -      v3d->flag |= V3D_INVALID_BACKBUF;
 +void VP_legacy_view3d_main_region_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
 +{
 +      view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
 +}
 +
 +bool VP_legacy_view3d_stereo3d_active(const bContext *C, Scene *scene, View3D *v3d, RegionView3D *rv3d)
 +{
-       return view3d_stereo3d_active(C, scene, v3d, rv3d);
++      return view3d_stereo3d_active(CTX_wm_window(C), scene, v3d, rv3d);
 +}
  
 -      BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_transp));
 -      BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xray));
 -      BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xraytransp));
 +void VP_legacy_view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar)
 +{
 +      view3d_stereo3d_setup(scene, v3d, ar);
  }
  
 -#ifdef DEBUG_DRAW
 -/* debug drawing */
 -#define _DEBUG_DRAW_QUAD_TOT 1024
 -#define _DEBUG_DRAW_EDGE_TOT 1024
 -static float _bl_debug_draw_quads[_DEBUG_DRAW_QUAD_TOT][4][3];
 -static int   _bl_debug_draw_quads_tot = 0;
 -static float _bl_debug_draw_edges[_DEBUG_DRAW_QUAD_TOT][2][3];
 -static int   _bl_debug_draw_edges_tot = 0;
 -static unsigned int _bl_debug_draw_quads_color[_DEBUG_DRAW_QUAD_TOT];
 -static unsigned int _bl_debug_draw_edges_color[_DEBUG_DRAW_EDGE_TOT];
 -static unsigned int _bl_debug_draw_color;
 -
 -void bl_debug_draw_quad_clear(void)
 +bool VP_legacy_use_depth(Scene *scene, View3D *v3d)
  {
 -      _bl_debug_draw_quads_tot = 0;
 -      _bl_debug_draw_edges_tot = 0;
 -      _bl_debug_draw_color = 0x00FF0000;
 +      return use_depth_doit(scene, v3d);
  }
 -void bl_debug_color_set(const unsigned int color)
 +
 +void VP_drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
  {
 -      _bl_debug_draw_color = color;
 +      drawviewborder(scene, ar, v3d);
  }
 -void bl_debug_draw_quad_add(const float v0[3], const float v1[3], const float v2[3], const float v3[3])
 +
 +void VP_drawrenderborder(ARegion *ar, View3D *v3d)
  {
 -      if (_bl_debug_draw_quads_tot >= _DEBUG_DRAW_QUAD_TOT) {
 -              printf("%s: max quad count hit %d!", __func__, _bl_debug_draw_quads_tot);
 -      }
 -      else {
 -              float *pt = &_bl_debug_draw_quads[_bl_debug_draw_quads_tot][0][0];
 -              copy_v3_v3(pt, v0); pt += 3;
 -              copy_v3_v3(pt, v1); pt += 3;
 -              copy_v3_v3(pt, v2); pt += 3;
 -              copy_v3_v3(pt, v3); pt += 3;
 -              _bl_debug_draw_quads_color[_bl_debug_draw_quads_tot] = _bl_debug_draw_color;
 -              _bl_debug_draw_quads_tot++;
 -      }
 +      drawrenderborder(ar, v3d);
  }
 -void bl_debug_draw_edge_add(const float v0[3], const float v1[3])
 +
 +void VP_view3d_draw_background_none(void)
  {
 -      if (_bl_debug_draw_quads_tot >= _DEBUG_DRAW_EDGE_TOT) {
 -              printf("%s: max edge count hit %d!", __func__, _bl_debug_draw_edges_tot);
 +      if (UI_GetThemeValue(TH_SHOW_BACK_GRAD)) {
 +              view3d_draw_background_gradient();
        }
        else {
 -              float *pt = &_bl_debug_draw_edges[_bl_debug_draw_edges_tot][0][0];
 -              copy_v3_v3(pt, v0); pt += 3;
 -              copy_v3_v3(pt, v1); pt += 3;
 -              _bl_debug_draw_edges_color[_bl_debug_draw_edges_tot] = _bl_debug_draw_color;
 -              _bl_debug_draw_edges_tot++;
 +              view3d_draw_background_none();
        }
  }
 -static void bl_debug_draw(void)
 +
 +void VP_view3d_draw_background_world(Scene *scene, View3D *v3d, RegionView3D *rv3d)
  {
 -      unsigned int color;
 -      if (_bl_debug_draw_quads_tot) {
 -              int i;
 -              color = _bl_debug_draw_quads_color[0];
 -              cpack(color);
 -              for (i = 0; i < _bl_debug_draw_quads_tot; i ++) {
 -                      if (_bl_debug_draw_quads_color[i] != color) {
 -                              color = _bl_debug_draw_quads_color[i];
 -                              cpack(color);
 -                      }
 -                      glBegin(GL_LINE_LOOP);
 -                      glVertex3fv(_bl_debug_draw_quads[i][0]);
 -                      glVertex3fv(_bl_debug_draw_quads[i][1]);
 -                      glVertex3fv(_bl_debug_draw_quads[i][2]);
 -                      glVertex3fv(_bl_debug_draw_quads[i][3]);
 -                      glEnd();
 -              }
 -      }
 -      if (_bl_debug_draw_edges_tot) {
 -              int i;
 -              color = _bl_debug_draw_edges_color[0];
 -              cpack(color);
 -              glBegin(GL_LINES);
 -              for (i = 0; i < _bl_debug_draw_edges_tot; i ++) {
 -                      if (_bl_debug_draw_edges_color[i] != color) {
 -                              color = _bl_debug_draw_edges_color[i];
 -                              cpack(color);
 -                      }
 -                      glVertex3fv(_bl_debug_draw_edges[i][0]);
 -                      glVertex3fv(_bl_debug_draw_edges[i][1]);
 -              }
 -              glEnd();
 -              color = _bl_debug_draw_edges_color[0];
 -              cpack(color);
 -              glPointSize(4.0);
 -              glBegin(GL_POINTS);
 -              for (i = 0; i < _bl_debug_draw_edges_tot; i ++) {
 -                      if (_bl_debug_draw_edges_color[i] != color) {
 -                              color = _bl_debug_draw_edges_color[i];
 -                              cpack(color);
 -                      }
 -                      glVertex3fv(_bl_debug_draw_edges[i][0]);
 -                      glVertex3fv(_bl_debug_draw_edges[i][1]);
 -              }
 -              glEnd();
 -      }
 +      view3d_draw_background_world(scene, v3d, rv3d);
  }
 -#endif
 +
 +void VP_view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar)
 +{
 +      view3d_main_region_clear(scene, v3d, ar);
 +}
 +
 +/** \} */
index 208a28cab4630cf1ba701203e57ff326df4792e2,0000000000000000000000000000000000000000..505096d6a64aaf5f14572151d675412ee4ddba2f
mode 100644,000000..100644
--- /dev/null
@@@ -1,2168 -1,0 +1,2161 @@@
-       RegionView3D *rv3d = ar->regiondata;
-       view3d_winmatrix_set(ar, v3d, NULL);
-       view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
 +/*
 + * ***** BEGIN GPL LICENSE BLOCK *****
 + *
 + * This program is free software; you can redistribute it and/or
 + * modify it under the terms of the GNU General Public License
 + * as published by the Free Software Foundation; either version 2
 + * of the License, or (at your option) any later version. 
 + *
 + * This program is distributed in the hope that it will be useful,
 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 + * GNU General Public License for more details.
 + *
 + * You should have received a copy of the GNU General Public License
 + * along with this program; if not, write to the Free Software Foundation,
 + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 + *
 + * The Original Code is Copyright (C) 2008 Blender Foundation.
 + * All rights reserved.
 + *
 + * 
 + * Contributor(s): Blender Foundation
 + *
 + * ***** END GPL LICENSE BLOCK *****
 + */
 +
 +/** \file blender/editors/space_view3d/view3d_draw_legacy.c
 + *  \ingroup spview3d
 + */
 +
 +#include <string.h>
 +#include <stdio.h>
 +#include <math.h>
 +
 +#include "DNA_armature_types.h"
 +#include "DNA_camera_types.h"
 +#include "DNA_customdata_types.h"
 +#include "DNA_object_types.h"
 +#include "DNA_group_types.h"
 +#include "DNA_mesh_types.h"
 +#include "DNA_key_types.h"
 +#include "DNA_lamp_types.h"
 +#include "DNA_scene_types.h"
 +#include "DNA_world_types.h"
 +#include "DNA_brush_types.h"
 +
 +#include "MEM_guardedalloc.h"
 +
 +#include "BLI_blenlib.h"
 +#include "BLI_math.h"
 +#include "BLI_jitter.h"
 +#include "BLI_utildefines.h"
 +#include "BLI_endian_switch.h"
 +#include "BLI_threads.h"
 +
 +#include "BKE_anim.h"
 +#include "BKE_camera.h"
 +#include "BKE_context.h"
 +#include "BKE_customdata.h"
 +#include "BKE_DerivedMesh.h"
 +#include "BKE_image.h"
 +#include "BKE_key.h"
 +#include "BKE_layer.h"
 +#include "BKE_main.h"
 +#include "BKE_object.h"
 +#include "BKE_global.h"
 +#include "BKE_paint.h"
 +#include "BKE_scene.h"
 +#include "BKE_screen.h"
 +#include "BKE_unit.h"
 +#include "BKE_movieclip.h"
 +
 +#include "RE_engine.h"
 +
 +#include "IMB_imbuf_types.h"
 +#include "IMB_imbuf.h"
 +#include "IMB_colormanagement.h"
 +
 +#include "BIF_glutil.h"
 +
 +#include "WM_api.h"
 +#include "WM_types.h"
 +
 +#include "BLF_api.h"
 +#include "BLT_translation.h"
 +
 +#include "ED_armature.h"
 +#include "ED_keyframing.h"
 +#include "ED_gpencil.h"
 +#include "ED_screen.h"
 +#include "ED_space_api.h"
 +#include "ED_screen_types.h"
 +#include "ED_transform.h"
 +
 +#include "UI_interface.h"
 +#include "UI_interface_icons.h"
 +#include "UI_resources.h"
 +
 +#include "GPU_draw.h"
 +#include "GPU_framebuffer.h"
 +#include "GPU_lamp.h"
 +#include "GPU_material.h"
 +#include "GPU_compositing.h"
 +#include "GPU_extensions.h"
 +#include "GPU_immediate.h"
 +#include "GPU_immediate_util.h"
 +#include "GPU_select.h"
 +#include "GPU_matrix.h"
 +
 +#include "RE_engine.h"
 +
 +#include "DRW_engine.h"
 +
 +#include "view3d_intern.h"  /* own include */
 +
 +/* ********* custom clipping *********** */
 +
 +static void view3d_draw_clipping(RegionView3D *rv3d)
 +{
 +      BoundBox *bb = rv3d->clipbb;
 +
 +      if (bb) {
 +              const unsigned int clipping_index[6][4] = {
 +                      {0, 1, 2, 3},
 +                      {0, 4, 5, 1},
 +                      {4, 7, 6, 5},
 +                      {7, 3, 2, 6},
 +                      {1, 5, 6, 2},
 +                      {7, 4, 0, 3}
 +              };
 +
 +              /* fill in zero alpha for rendering & re-projection [#31530] */
 +              unsigned char col[4];
 +              UI_GetThemeColor4ubv(TH_V3D_CLIPPING_BORDER, col);
 +              glColor4ubv(col);
 +
 +              glEnable(GL_BLEND);
 +              glEnableClientState(GL_VERTEX_ARRAY);
 +              glVertexPointer(3, GL_FLOAT, 0, bb->vec);
 +              glDrawElements(GL_QUADS, sizeof(clipping_index) / sizeof(unsigned int), GL_UNSIGNED_INT, clipping_index);
 +              glDisableClientState(GL_VERTEX_ARRAY);
 +              glDisable(GL_BLEND);
 +      }
 +}
 +
 +void ED_view3d_clipping_set(RegionView3D *rv3d)
 +{
 +      double plane[4];
 +      const unsigned int tot = (rv3d->viewlock & RV3D_BOXCLIP) ? 4 : 6;
 +
 +      for (unsigned a = 0; a < tot; a++) {
 +              copy_v4db_v4fl(plane, rv3d->clip[a]);
 +              glClipPlane(GL_CLIP_PLANE0 + a, plane);
 +              glEnable(GL_CLIP_PLANE0 + a);
 +      }
 +}
 +
 +/* use these to temp disable/enable clipping when 'rv3d->rflag & RV3D_CLIPPING' is set */
 +void ED_view3d_clipping_disable(void)
 +{
 +      for (unsigned a = 0; a < 6; a++) {
 +              glDisable(GL_CLIP_PLANE0 + a);
 +      }
 +}
 +void ED_view3d_clipping_enable(void)
 +{
 +      for (unsigned a = 0; a < 6; a++) {
 +              glEnable(GL_CLIP_PLANE0 + a);
 +      }
 +}
 +
 +static bool view3d_clipping_test(const float co[3], const float clip[6][4])
 +{
 +      if (plane_point_side_v3(clip[0], co) > 0.0f)
 +              if (plane_point_side_v3(clip[1], co) > 0.0f)
 +                      if (plane_point_side_v3(clip[2], co) > 0.0f)
 +                              if (plane_point_side_v3(clip[3], co) > 0.0f)
 +                                      return false;
 +
 +      return true;
 +}
 +
 +/* for 'local' ED_view3d_clipping_local must run first
 + * then all comparisons can be done in localspace */
 +bool ED_view3d_clipping_test(const RegionView3D *rv3d, const float co[3], const bool is_local)
 +{
 +      return view3d_clipping_test(co, is_local ? rv3d->clip_local : rv3d->clip);
 +}
 +
 +/* ********* end custom clipping *********** */
 +
 +static void draw_view_icon(RegionView3D *rv3d, rcti *rect)
 +{
 +      BIFIconID icon;
 +      
 +      if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM))
 +              icon = ICON_AXIS_TOP;
 +      else if (ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK))
 +              icon = ICON_AXIS_FRONT;
 +      else if (ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT))
 +              icon = ICON_AXIS_SIDE;
 +      else return;
 +      
 +      glEnable(GL_BLEND);
 +      glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
 +      
 +      UI_icon_draw(5.0 + rect->xmin, 5.0 + rect->ymin, icon);
 +      
 +      glDisable(GL_BLEND);
 +}
 +
 +/* *********************** backdraw for selection *************** */
 +
 +static void backdrawview3d(Scene *scene, SceneLayer *sl, wmWindow *win, ARegion *ar, View3D *v3d)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
 +      struct Base *base = sl->basact;
 +      int multisample_enabled;
 +
 +      BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
 +
 +      if (base && (base->object->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
 +                   BKE_paint_select_face_test(base->object)))
 +      {
 +              /* do nothing */
 +      }
 +      /* texture paint mode sampling */
 +      else if (base && (base->object->mode & OB_MODE_TEXTURE_PAINT) &&
 +               (v3d->drawtype > OB_WIRE))
 +      {
 +              /* do nothing */
 +      }
 +      else if ((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) &&
 +               V3D_IS_ZBUF(v3d))
 +      {
 +              /* do nothing */
 +      }
 +      else if (scene->obedit &&
 +               V3D_IS_ZBUF(v3d))
 +      {
 +              /* do nothing */
 +      }
 +      else {
 +              v3d->flag &= ~V3D_INVALID_BACKBUF;
 +              return;
 +      }
 +
 +      if (!(v3d->flag & V3D_INVALID_BACKBUF))
 +              return;
 +
 +#if 0
 +      if (test) {
 +              if (qtest()) {
 +                      addafterqueue(ar->win, BACKBUFDRAW, 1);
 +                      return;
 +              }
 +      }
 +#endif
 +
 +      if (v3d->drawtype > OB_WIRE) v3d->zbuf = true;
 +      
 +      /* dithering and AA break color coding, so disable */
 +      glDisable(GL_DITHER);
 +
 +      multisample_enabled = glIsEnabled(GL_MULTISAMPLE);
 +      if (multisample_enabled)
 +              glDisable(GL_MULTISAMPLE);
 +
 +      if (win->multisamples != USER_MULTISAMPLE_NONE) {
 +              /* for multisample we use an offscreen FBO. multisample drawing can fail
 +               * with color coded selection drawing, and reading back depths from such
 +               * a buffer can also cause a few seconds freeze on OS X / NVidia. */
 +              int w = BLI_rcti_size_x(&ar->winrct);
 +              int h = BLI_rcti_size_y(&ar->winrct);
 +              char error[256];
 +
 +              if (rv3d->gpuoffscreen) {
 +                      if (GPU_offscreen_width(rv3d->gpuoffscreen)  != w ||
 +                          GPU_offscreen_height(rv3d->gpuoffscreen) != h)
 +                      {
 +                              GPU_offscreen_free(rv3d->gpuoffscreen);
 +                              rv3d->gpuoffscreen = NULL;
 +                      }
 +              }
 +
 +              if (!rv3d->gpuoffscreen) {
 +                      rv3d->gpuoffscreen = GPU_offscreen_create(w, h, 0, error);
 +
 +                      if (!rv3d->gpuoffscreen)
 +                              fprintf(stderr, "Failed to create offscreen selection buffer for multisample: %s\n", error);
 +              }
 +      }
 +
 +      if (rv3d->gpuoffscreen)
 +              GPU_offscreen_bind(rv3d->gpuoffscreen, true);
 +      else
 +              glScissor(ar->winrct.xmin, ar->winrct.ymin, BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
 +
 +      glClearColor(0.0, 0.0, 0.0, 0.0);
 +      if (v3d->zbuf) {
 +              glEnable(GL_DEPTH_TEST);
 +              glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 +      }
 +      else {
 +              glClear(GL_COLOR_BUFFER_BIT);
 +              glDisable(GL_DEPTH_TEST);
 +      }
 +      
 +      if (rv3d->rflag & RV3D_CLIPPING)
 +              ED_view3d_clipping_set(rv3d);
 +      
 +      G.f |= G_BACKBUFSEL;
 +      
 +      if (base && ((base->flag & BASE_VISIBLED) != 0))
 +              draw_object_backbufsel(scene, v3d, rv3d, base->object);
 +      
 +      if (rv3d->gpuoffscreen)
 +              GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
 +      else
 +              ar->swap = 0; /* mark invalid backbuf for wm draw */
 +
 +      v3d->flag &= ~V3D_INVALID_BACKBUF;
 +
 +      G.f &= ~G_BACKBUFSEL;
 +      v3d->zbuf = false;
 +      glDisable(GL_DEPTH_TEST);
 +      glEnable(GL_DITHER);
 +      if (multisample_enabled)
 +              glEnable(GL_MULTISAMPLE);
 +
 +      if (rv3d->rflag & RV3D_CLIPPING)
 +              ED_view3d_clipping_disable();
 +}
 +
 +void view3d_opengl_read_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
 +
 +      if (rv3d->gpuoffscreen) {
 +              GPU_offscreen_bind(rv3d->gpuoffscreen, true);
 +              glReadBuffer(GL_COLOR_ATTACHMENT0);
 +              glReadPixels(x, y, w, h, format, type, data);
 +              GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
 +      }
 +      else {
 +              glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
 +      }
 +}
 +
 +/* XXX depth reading exception, for code not using gpu offscreen */
 +static void view3d_opengl_read_Z_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
 +{
 +      glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
 +}
 +
 +void ED_view3d_backbuf_validate(ViewContext *vc)
 +{
 +      if (vc->v3d->flag & V3D_INVALID_BACKBUF)
 +              backdrawview3d(vc->scene, vc->scene_layer, vc->win, vc->ar, vc->v3d);
 +}
 +
 +/**
 + * allow for small values [0.5 - 2.5],
 + * and large values, FLT_MAX by clamping by the area size
 + */
 +int ED_view3d_backbuf_sample_size_clamp(ARegion *ar, const float dist)
 +{
 +      return (int)min_ff(ceilf(dist), (float)max_ii(ar->winx, ar->winx));
 +}
 +
 +/* samples a single pixel (copied from vpaint) */
 +unsigned int ED_view3d_backbuf_sample(ViewContext *vc, int x, int y)
 +{
 +      if (x >= vc->ar->winx || y >= vc->ar->winy) {
 +              return 0;
 +      }
 +
 +      ED_view3d_backbuf_validate(vc);
 +
 +      unsigned int col;
 +      view3d_opengl_read_pixels(vc->ar, x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &col);
 +      glReadBuffer(GL_BACK);
 +
 +      if (ENDIAN_ORDER == B_ENDIAN) {
 +              BLI_endian_switch_uint32(&col);
 +      }
 +
 +      return GPU_select_to_index(col);
 +}
 +
 +/* reads full rect, converts indices */
 +ImBuf *ED_view3d_backbuf_read(ViewContext *vc, int xmin, int ymin, int xmax, int ymax)
 +{
 +      /* clip */
 +      const rcti clip = {
 +          max_ii(xmin, 0), min_ii(xmax, vc->ar->winx - 1),
 +          max_ii(ymin, 0), min_ii(ymax, vc->ar->winy - 1)};
 +      const int size_clip[2] = {
 +          BLI_rcti_size_x(&clip) + 1,
 +          BLI_rcti_size_y(&clip) + 1};
 +
 +      if (UNLIKELY((clip.xmin > clip.xmax) ||
 +                   (clip.ymin > clip.ymax)))
 +      {
 +              return NULL;
 +      }
 +
 +      ImBuf *ibuf_clip = IMB_allocImBuf(size_clip[0], size_clip[1], 32, IB_rect);
 +
 +      ED_view3d_backbuf_validate(vc);
 +
 +      view3d_opengl_read_pixels(vc->ar, clip.xmin, clip.ymin, size_clip[0], size_clip[1], GL_RGBA, GL_UNSIGNED_BYTE, ibuf_clip->rect);
 +
 +      glReadBuffer(GL_BACK);
 +
 +      if (ENDIAN_ORDER == B_ENDIAN) {
 +              IMB_convert_rgba_to_abgr(ibuf_clip);
 +      }
 +
 +      GPU_select_to_index_array(ibuf_clip->rect, size_clip[0] * size_clip[1]);
 +      
 +      if ((clip.xmin == xmin) &&
 +          (clip.xmax == xmax) &&
 +          (clip.ymin == ymin) &&
 +          (clip.ymax == ymax))
 +      {
 +              return ibuf_clip;
 +      }
 +      else {
 +              /* put clipped result into a non-clipped buffer */
 +              const int size[2] = {
 +                  (xmax - xmin + 1),
 +                  (ymax - ymin + 1)};
 +
 +              ImBuf *ibuf_full = IMB_allocImBuf(size[0], size[1], 32, IB_rect);
 +
 +              IMB_rectcpy(
 +                      ibuf_full, ibuf_clip,
 +                      clip.xmin - xmin, clip.ymin - ymin,
 +                      0, 0,
 +                      size_clip[0], size_clip[1]);
 +              IMB_freeImBuf(ibuf_clip);
 +              return ibuf_full;
 +      }
 +}
 +
 +/* smart function to sample a rect spiralling outside, nice for backbuf selection */
 +unsigned int ED_view3d_backbuf_sample_rect(
 +        ViewContext *vc, const int mval[2], int size,
 +        unsigned int min, unsigned int max, float *r_dist)
 +{
 +      int dirvec[4][2];
 +
 +      const int amount = (size - 1) / 2;
 +
 +      const int minx = mval[0] - (amount + 1);
 +      const int miny = mval[1] - (amount + 1);
 +      ImBuf *buf = ED_view3d_backbuf_read(vc, minx, miny, minx + size - 1, miny + size - 1);
 +      if (!buf) return 0;
 +
 +      unsigned index = 0;
 +      int rc = 0;
 +      
 +      dirvec[0][0] = 1; dirvec[0][1] = 0;
 +      dirvec[1][0] = 0; dirvec[1][1] = -size;
 +      dirvec[2][0] = -1; dirvec[2][1] = 0;
 +      dirvec[3][0] = 0; dirvec[3][1] = size;
 +      
 +      const unsigned *bufmin = buf->rect;
 +      const unsigned *tbuf = buf->rect;
 +      const unsigned *bufmax = buf->rect + size * size;
 +      tbuf += amount * size + amount;
 +      
 +      for (int nr = 1; nr <= size; nr++) {
 +              for (int a = 0; a < 2; a++) {
 +                      for (int b = 0; b < nr; b++) {
 +                              if (*tbuf && *tbuf >= min && *tbuf < max) {
 +                                      /* we got a hit */
 +
 +                                      /* get x,y pixel coords from the offset
 +                                       * (manhatten distance in keeping with other screen-based selection) */
 +                                      *r_dist = (float)(
 +                                              abs(((int)(tbuf - buf->rect) % size) - (size / 2)) +
 +                                              abs(((int)(tbuf - buf->rect) / size) - (size / 2)));
 +
 +                                      /* indices start at 1 here */
 +                                      index = (*tbuf - min) + 1;
 +                                      goto exit;
 +                              }
 +                              
 +                              tbuf += (dirvec[rc][0] + dirvec[rc][1]);
 +                              
 +                              if (tbuf < bufmin || tbuf >= bufmax) {
 +                                      goto exit;
 +                              }
 +                      }
 +                      rc++;
 +                      rc &= 3;
 +              }
 +      }
 +
 +exit:
 +      IMB_freeImBuf(buf);
 +      return index;
 +}
 +
 +
 +/* ************************************************************* */
 +
 +static void view3d_stereo_bgpic_setup(Scene *scene, View3D *v3d, Image *ima, ImageUser *iuser)
 +{
 +      if (BKE_image_is_stereo(ima)) {
 +              iuser->flag |= IMA_SHOW_STEREO;
 +
 +              if ((scene->r.scemode & R_MULTIVIEW) == 0) {
 +                      iuser->multiview_eye = STEREO_LEFT_ID;
 +              }
 +              else if (v3d->stereo3d_camera != STEREO_3D_ID) {
 +                      /* show only left or right camera */
 +                      iuser->multiview_eye = v3d->stereo3d_camera;
 +              }
 +
 +              BKE_image_multiview_index(ima, iuser);
 +      }
 +      else {
 +              iuser->flag &= ~IMA_SHOW_STEREO;
 +      }
 +}
 +
 +static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
 +                              const bool do_foreground, const bool do_camera_frame)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
 +      int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
 +
 +      for (BGpic *bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
 +              bgpic->iuser.scene = scene;  /* Needed for render results. */
 +
 +              if ((bgpic->flag & V3D_BGPIC_FOREGROUND) != fg_flag)
 +                      continue;
 +
 +              if ((bgpic->view == 0) || /* zero for any */
 +                  (bgpic->view & (1 << rv3d->view)) || /* check agaist flags */
 +                  (rv3d->persp == RV3D_CAMOB && bgpic->view == (1 << RV3D_VIEW_CAMERA)))
 +              {
 +                      float image_aspect[2];
 +                      float x1, y1, x2, y2, centx, centy;
 +
 +                      void *lock;
 +
 +                      Image *ima = NULL;
 +
 +                      /* disable individual images */
 +                      if ((bgpic->flag & V3D_BGPIC_DISABLED))
 +                              continue;
 +
 +                      ImBuf *ibuf = NULL;
 +                      ImBuf *freeibuf = NULL;
 +                      ImBuf *releaseibuf = NULL;
 +                      if (bgpic->source == V3D_BGPIC_IMAGE) {
 +                              ima = bgpic->ima;
 +                              if (ima == NULL)
 +                                      continue;
 +                              BKE_image_user_frame_calc(&bgpic->iuser, CFRA, 0);
 +                              if (ima->source == IMA_SRC_SEQUENCE && !(bgpic->iuser.flag & IMA_USER_FRAME_IN_RANGE)) {
 +                                      ibuf = NULL; /* frame is out of range, dont show */
 +                              }
 +                              else {
 +                                      view3d_stereo_bgpic_setup(scene, v3d, ima, &bgpic->iuser);
 +                                      ibuf = BKE_image_acquire_ibuf(ima, &bgpic->iuser, &lock);
 +                                      releaseibuf = ibuf;
 +                              }
 +
 +                              image_aspect[0] = ima->aspx;
 +                              image_aspect[1] = ima->aspy;
 +                      }
 +                      else if (bgpic->source == V3D_BGPIC_MOVIE) {
 +                              /* TODO: skip drawing when out of frame range (as image sequences do above) */
 +                              MovieClip *clip = NULL;
 +
 +                              if (bgpic->flag & V3D_BGPIC_CAMERACLIP) {
 +                                      if (scene->camera)
 +                                              clip = BKE_object_movieclip_get(scene, scene->camera, true);
 +                              }
 +                              else {
 +                                      clip = bgpic->clip;
 +                              }
 +
 +                              if (clip == NULL)
 +                                      continue;
 +
 +                              BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
 +                              ibuf = BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
 +
 +                              image_aspect[0] = clip->aspx;
 +                              image_aspect[1] = clip->aspy;
 +
 +                              /* working with ibuf from image and clip has got different workflow now.
 +                               * ibuf acquired from clip is referenced by cache system and should
 +                               * be dereferenced after usage. */
 +                              freeibuf = ibuf;
 +                      }
 +                      else {
 +                              /* perhaps when loading future files... */
 +                              BLI_assert(0);
 +                              copy_v2_fl(image_aspect, 1.0f);
 +                      }
 +
 +                      if (ibuf == NULL)
 +                              continue;
 +
 +                      if ((ibuf->rect == NULL && ibuf->rect_float == NULL) || ibuf->channels != 4) { /* invalid image format */
 +                              if (freeibuf)
 +                                      IMB_freeImBuf(freeibuf);
 +                              if (releaseibuf)
 +                                      BKE_image_release_ibuf(ima, releaseibuf, lock);
 +
 +                              continue;
 +                      }
 +
 +                      if (ibuf->rect == NULL)
 +                              IMB_rect_from_float(ibuf);
 +
 +                      if (rv3d->persp == RV3D_CAMOB) {
 +
 +                              if (do_camera_frame) {
 +                                      rctf vb;
 +                                      ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, false);
 +                                      x1 = vb.xmin;
 +                                      y1 = vb.ymin;
 +                                      x2 = vb.xmax;
 +                                      y2 = vb.ymax;
 +                              }
 +                              else {
 +                                      x1 = ar->winrct.xmin;
 +                                      y1 = ar->winrct.ymin;
 +                                      x2 = ar->winrct.xmax;
 +                                      y2 = ar->winrct.ymax;
 +                              }
 +
 +                              /* apply offset last - camera offset is different to offset in blender units */
 +                              /* so this has some sane way of working - this matches camera's shift _exactly_ */
 +                              {
 +                                      const float max_dim = max_ff(x2 - x1, y2 - y1);
 +                                      const float xof_scale = bgpic->xof * max_dim;
 +                                      const float yof_scale = bgpic->yof * max_dim;
 +
 +                                      x1 += xof_scale;
 +                                      y1 += yof_scale;
 +                                      x2 += xof_scale;
 +                                      y2 += yof_scale;
 +                              }
 +
 +                              centx = (x1 + x2) * 0.5f;
 +                              centy = (y1 + y2) * 0.5f;
 +
 +                              /* aspect correction */
 +                              if (bgpic->flag & V3D_BGPIC_CAMERA_ASPECT) {
 +                                      /* apply aspect from clip */
 +                                      const float w_src = ibuf->x * image_aspect[0];
 +                                      const float h_src = ibuf->y * image_aspect[1];
 +
 +                                      /* destination aspect is already applied from the camera frame */
 +                                      const float w_dst = x1 - x2;
 +                                      const float h_dst = y1 - y2;
 +
 +                                      const float asp_src = w_src / h_src;
 +                                      const float asp_dst = w_dst / h_dst;
 +
 +                                      if (fabsf(asp_src - asp_dst) >= FLT_EPSILON) {
 +                                              if ((asp_src > asp_dst) == ((bgpic->flag & V3D_BGPIC_CAMERA_CROP) != 0)) {
 +                                                      /* fit X */
 +                                                      const float div = asp_src / asp_dst;
 +                                                      x1 = ((x1 - centx) * div) + centx;
 +                                                      x2 = ((x2 - centx) * div) + centx;
 +                                              }
 +                                              else {
 +                                                      /* fit Y */
 +                                                      const float div = asp_dst / asp_src;
 +                                                      y1 = ((y1 - centy) * div) + centy;
 +                                                      y2 = ((y2 - centy) * div) + centy;
 +                                              }
 +                                      }
 +                              }
 +                      }
 +                      else {
 +                              float tvec[3];
 +                              float sco[2];
 +                              const float mval_f[2] = {1.0f, 0.0f};
 +                              const float co_zero[3] = {0};
 +
 +                              /* calc window coord */
 +                              float zfac = ED_view3d_calc_zfac(rv3d, co_zero, NULL);
 +                              ED_view3d_win_to_delta(ar, mval_f, tvec, zfac);
 +                              float fac = 1.0f / max_ff(fabsf(tvec[0]), max_ff(fabsf(tvec[1]), fabsf(tvec[2]))); /* largest abs axis */
 +                              float asp = (float)ibuf->y / (float)ibuf->x;
 +
 +                              zero_v3(tvec);
 +                              ED_view3d_project_float_v2_m4(ar, tvec, sco, rv3d->persmat);
 +
 +                              x1 =  sco[0] + fac * (bgpic->xof - bgpic->size);
 +                              y1 =  sco[1] + asp * fac * (bgpic->yof - bgpic->size);
 +                              x2 =  sco[0] + fac * (bgpic->xof + bgpic->size);
 +                              y2 =  sco[1] + asp * fac * (bgpic->yof + bgpic->size);
 +
 +                              centx = (x1 + x2) / 2.0f;
 +                              centy = (y1 + y2) / 2.0f;
 +                      }
 +
 +                      /* complete clip? */
 +                      rctf clip_rect;
 +                      BLI_rctf_init(&clip_rect, x1, x2, y1, y2);
 +                      if (bgpic->rotation) {
 +                              BLI_rctf_rotate_expand(&clip_rect, &clip_rect, bgpic->rotation);
 +                      }
 +
 +                      if (clip_rect.xmax < 0 || clip_rect.ymax < 0 || clip_rect.xmin > ar->winx || clip_rect.ymin > ar->winy) {
 +                              if (freeibuf)
 +                                      IMB_freeImBuf(freeibuf);
 +                              if (releaseibuf)
 +                                      BKE_image_release_ibuf(ima, releaseibuf, lock);
 +
 +                              continue;
 +                      }
 +
 +                      float zoomx = (x2 - x1) / ibuf->x;
 +                      float zoomy = (y2 - y1) / ibuf->y;
 +
 +                      /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
 +                      if (zoomx < 1.0f || zoomy < 1.0f) {
 +                              float tzoom = min_ff(zoomx, zoomy);
 +                              int mip = 0;
 +
 +                              if ((ibuf->userflags & IB_MIPMAP_INVALID) != 0) {
 +                                      IMB_remakemipmap(ibuf, 0);
 +                                      ibuf->userflags &= ~IB_MIPMAP_INVALID;
 +                              }
 +                              else if (ibuf->mipmap[0] == NULL)
 +                                      IMB_makemipmap(ibuf, 0);
 +
 +                              while (tzoom < 1.0f && mip < 8 && ibuf->mipmap[mip]) {
 +                                      tzoom *= 2.0f;
 +                                      zoomx *= 2.0f;
 +                                      zoomy *= 2.0f;
 +                                      mip++;
 +                              }
 +                              if (mip > 0)
 +                                      ibuf = ibuf->mipmap[mip - 1];
 +                      }
 +
 +                      if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
 +                      glDepthMask(GL_FALSE);
 +
 +                      glEnable(GL_BLEND);
 +                      glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
 +
 +                      gpuPushProjectionMatrix();
 +                      gpuPushMatrix();
 +                      ED_region_pixelspace(ar);
 +
 +                      gpuTranslate2f(centx, centy);
 +                      gpuRotate2D(RAD2DEGF(-bgpic->rotation));
 +
 +                      if (bgpic->flag & V3D_BGPIC_FLIP_X) {
 +                              zoomx *= -1.0f;
 +                              x1 = x2;
 +                      }
 +                      if (bgpic->flag & V3D_BGPIC_FLIP_Y) {
 +                              zoomy *= -1.0f;
 +                              y1 = y2;
 +                      }
 +
 +                      float col[4] = {1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend};
 +                      IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR);
 +                      immDrawPixelsTex(&state, x1 - centx, y1 - centy, ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR, ibuf->rect,
 +                                       zoomx, zoomy, col);
 +
 +                      gpuPopProjectionMatrix();
 +                      gpuPopMatrix();
 +
 +                      glDisable(GL_BLEND);
 +
 +                      glDepthMask(GL_TRUE);
 +                      if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
 +
 +                      if (freeibuf)
 +                              IMB_freeImBuf(freeibuf);
 +                      if (releaseibuf)
 +                              BKE_image_release_ibuf(ima, releaseibuf, lock);
 +              }
 +      }
 +}
 +
 +static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
 +                                   const bool do_foreground, const bool do_camera_frame)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
 +
 +      if ((v3d->flag & V3D_DISPBGPICS) == 0)
 +              return;
 +
 +      /* disabled - mango request, since footage /w only render is quite useful
 +       * and this option is easy to disable all background images at once */
 +#if 0
 +      if (v3d->flag2 & V3D_RENDER_OVERRIDE)
 +              return;
 +#endif
 +
 +      if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
 +              if (rv3d->persp == RV3D_CAMOB) {
 +                      view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
 +              }
 +      }
 +      else {
 +              view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
 +      }
 +}
 +
 +/* ****************** View3d afterdraw *************** */
 +
 +typedef struct View3DAfter {
 +      struct View3DAfter *next, *prev;
 +      struct BaseLegacy *base;
 +      short dflag;
 +} View3DAfter;
 +
 +/* temp storage of Objects that need to be drawn as last */
 +void ED_view3d_after_add(ListBase *lb, BaseLegacy *base, const short dflag)
 +{
 +      View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
 +      BLI_assert((base->flag_legacy & OB_FROMDUPLI) == 0);
 +      BLI_addtail(lb, v3da);
 +      v3da->base = base;
 +      v3da->dflag = dflag;
 +}
 +
 +/* disables write in zbuffer and draws it over */
 +static void view3d_draw_transp(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d)
 +{
 +      View3DAfter *v3da;
 +      
 +      glDepthMask(GL_FALSE);
 +      v3d->transp = true;
 +      
 +      while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
 +              draw_object(scene, sl, ar, v3d, v3da->base, v3da->dflag);
 +              MEM_freeN(v3da);
 +      }
 +      v3d->transp = false;
 +      
 +      glDepthMask(GL_TRUE);
 +      
 +}
 +
 +/* clears zbuffer and draws it over */
 +static void view3d_draw_xray(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, bool *clear)
 +{
 +      if (*clear && v3d->zbuf) {
 +              glClear(GL_DEPTH_BUFFER_BIT);
 +              *clear = false;
 +      }
 +
 +      v3d->xray = true;
 +      View3DAfter *v3da;
 +      while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 +              draw_object(scene, sl, ar, v3d, v3da->base, v3da->dflag);
 +              MEM_freeN(v3da);
 +      }
 +      v3d->xray = false;
 +}
 +
 +
 +/* clears zbuffer and draws it over */
 +static void view3d_draw_xraytransp(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, const bool clear)
 +{
 +      if (clear && v3d->zbuf)
 +              glClear(GL_DEPTH_BUFFER_BIT);
 +
 +      v3d->xray = true;
 +      v3d->transp = true;
 +      
 +      glDepthMask(GL_FALSE);
 +
 +      View3DAfter *v3da;
 +      while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
 +              draw_object(scene, sl, ar, v3d, v3da->base, v3da->dflag);
 +              MEM_freeN(v3da);
 +      }
 +
 +      v3d->transp = false;
 +      v3d->xray = false;
 +
 +      glDepthMask(GL_TRUE);
 +}
 +
 +/* clears zbuffer and draws it over,
 + * note that in the select version we don't care about transparent flag as with regular drawing */
 +static void view3d_draw_xray_select(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, bool *clear)
 +{
 +      /* Not ideal, but we need to read from the previous depths before clearing
 +       * otherwise we could have a function to load the depths after drawing.
 +       *
 +       * Clearing the depth buffer isn't all that common between drawing objects so accept this for now.
 +       */
 +      if (U.gpu_select_pick_deph) {
 +              GPU_select_load_id(-1);
 +      }
 +
 +      View3DAfter *v3da;
 +      if (*clear && v3d->zbuf) {
 +              glClear(GL_DEPTH_BUFFER_BIT);
 +              *clear = false;
 +      }
 +
 +      v3d->xray = true;
 +      while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 +              if (GPU_select_load_id(v3da->base->selcol)) {
 +                      draw_object_select(scene, sl, ar, v3d, v3da->base, v3da->dflag);
 +              }
 +              MEM_freeN(v3da);
 +      }
 +      v3d->xray = false;
 +}
 +
 +/* *********************** */
 +
 +/*
 + * In most cases call draw_dupli_objects,
 + * draw_dupli_objects_color was added because when drawing set dupli's
 + * we need to force the color
 + */
 +
 +#if 0
 +int dupli_ob_sort(void *arg1, void *arg2)
 +{
 +      void *p1 = ((DupliObject *)arg1)->ob;
 +      void *p2 = ((DupliObject *)arg2)->ob;
 +      int val = 0;
 +      if (p1 < p2) val = -1;
 +      else if (p1 > p2) val = 1;
 +      return val;
 +}
 +#endif
 +
 +
 +static DupliObject *dupli_step(DupliObject *dob)
 +{
 +      while (dob && dob->no_draw)
 +              dob = dob->next;
 +      return dob;
 +}
 +
 +static void draw_dupli_objects_color(
 +        Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, BaseLegacy *base,
 +        const short dflag, const int color)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
 +      ListBase *lb;
 +      LodLevel *savedlod;
 +      Base tbase = {NULL};
 +      BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
 +      unsigned char color_rgb[3];
 +      const short dflag_dupli = dflag | DRAW_CONSTCOLOR;
 +      short transflag;
 +      char dt;
 +      short dtx;
 +      DupliApplyData *apply_data;
 +
 +      if ((base->flag & BASE_VISIBLED) == 0) return;
 +      if ((base->object->restrictflag & OB_RESTRICT_RENDER) && (v3d->flag2 & V3D_RENDER_OVERRIDE)) return;
 +
 +      if (dflag & DRAW_CONSTCOLOR) {
 +              BLI_assert(color == TH_UNDEFINED);
 +      }
 +      else {
 +              UI_GetThemeColorBlend3ubv(color, TH_BACK, 0.5f, color_rgb);
 +      }
 +
 +      tbase.flag_legacy = OB_FROMDUPLI | base->flag_legacy;
 +      tbase.flag = base->flag;
 +      lb = object_duplilist(G.main->eval_ctx, scene, base->object);
 +      // BLI_listbase_sort(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
 +
 +      apply_data = duplilist_apply(base->object, scene, lb);
 +
 +      DupliObject *dob_next = NULL;
 +      DupliObject *dob = dupli_step(lb->first);
 +      if (dob) dob_next = dupli_step(dob->next);
 +
 +      for (; dob; dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
 +              bool testbb = false;
 +
 +              tbase.object = dob->ob;
 +
 +              /* Make sure lod is updated from dupli's position */
 +              savedlod = dob->ob->currentlod;
 +
 +#ifdef WITH_GAMEENGINE
 +              if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
 +                      BKE_object_lod_update(dob->ob, rv3d->viewinv[3]);
 +              }
 +#endif
 +
 +              /* extra service: draw the duplicator in drawtype of parent, minimum taken
 +               * to allow e.g. boundbox box objects in groups for LOD */
 +              dt = tbase.object->dt;
 +              tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
 +
 +              /* inherit draw extra, but not if a boundbox under the assumption that this
 +               * is intended to speed up drawing, and drawing extra (especially wire) can
 +               * slow it down too much */
 +              dtx = tbase.object->dtx;
 +              if (tbase.object->dt != OB_BOUNDBOX)
 +                      tbase.object->dtx = base->object->dtx;
 +
 +              /* negative scale flag has to propagate */
 +              transflag = tbase.object->transflag;
 +
 +              if (is_negative_m4(dob->mat))
 +                      tbase.object->transflag |= OB_NEG_SCALE;
 +              else
 +                      tbase.object->transflag &= ~OB_NEG_SCALE;
 +              
 +              /* should move outside the loop but possible color is set in draw_object still */
 +              if ((dflag & DRAW_CONSTCOLOR) == 0) {
 +                      glColor3ubv(color_rgb);
 +              }
 +              
 +              if ((bb_tmp = BKE_object_boundbox_get(dob->ob))) {
 +                      bb = *bb_tmp; /* must make a copy  */
 +                      testbb = true;
 +              }
 +
 +              if (!testbb || ED_view3d_boundbox_clip_ex(rv3d, &bb, dob->mat)) {
 +                      copy_m4_m4(dob->ob->obmat, dob->mat);
 +                      GPU_begin_dupli_object(dob);
 +                      draw_object(scene, sl, ar, v3d, &tbase, dflag_dupli);
 +                      GPU_end_dupli_object();
 +              }
 +              
 +              tbase.object->dt = dt;
 +              tbase.object->dtx = dtx;
 +              tbase.object->transflag = transflag;
 +              tbase.object->currentlod = savedlod;
 +      }
 +
 +      if (apply_data) {
 +              duplilist_restore(lb, apply_data);
 +              duplilist_free_apply_data(apply_data);
 +      }
 +
 +      free_object_duplilist(lb);
 +}
 +
 +void draw_dupli_objects(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, BaseLegacy *base)
 +{
 +      /* define the color here so draw_dupli_objects_color can be called
 +       * from the set loop */
 +      
 +      int color = (base->flag & BASE_SELECTED) ? TH_SELECT : TH_WIRE;
 +      /* debug */
 +      if (base->object->dup_group && base->object->dup_group->id.us < 1)
 +              color = TH_REDALERT;
 +      
 +      draw_dupli_objects_color(scene, sl, ar, v3d, base, 0, color);
 +}
 +
 +/* XXX warning, not using gpu offscreen here */
 +void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
 +{
 +      /* clamp rect by region */
 +      rcti r = {
 +              .xmin = 0,
 +              .xmax = ar->winx - 1,
 +              .ymin = 0,
 +              .ymax = ar->winy - 1
 +      };
 +
 +      /* Constrain rect to depth bounds */
 +      BLI_rcti_isect(&r, rect, rect);
 +
 +      /* assign values to compare with the ViewDepths */
 +      int x = rect->xmin;
 +      int y = rect->ymin;
 +
 +      int w = BLI_rcti_size_x(rect);
 +      int h = BLI_rcti_size_y(rect);
 +
 +      if (w <= 0 || h <= 0) {
 +              if (d->depths)
 +                      MEM_freeN(d->depths);
 +              d->depths = NULL;
 +
 +              d->damaged = false;
 +      }
 +      else if (d->w != w ||
 +               d->h != h ||
 +               d->x != x ||
 +               d->y != y ||
 +               d->depths == NULL
 +               )
 +      {
 +              d->x = x;
 +              d->y = y;
 +              d->w = w;
 +              d->h = h;
 +
 +              if (d->depths)
 +                      MEM_freeN(d->depths);
 +
 +              d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
 +              
 +              d->damaged = true;
 +      }
 +
 +      if (d->damaged) {
 +              /* XXX using special function here, it doesn't use the gpu offscreen system */
 +              view3d_opengl_read_Z_pixels(ar, d->x, d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
 +              glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
 +              d->damaged = false;
 +      }
 +}
 +
 +/* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
 +void ED_view3d_depth_update(ARegion *ar)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
 +      
 +      /* Create storage for, and, if necessary, copy depth buffer */
 +      if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
 +      if (rv3d->depths) {
 +              ViewDepths *d = rv3d->depths;
 +              if (d->w != ar->winx ||
 +                  d->h != ar->winy ||
 +                  !d->depths)
 +              {
 +                      d->w = ar->winx;
 +                      d->h = ar->winy;
 +                      if (d->depths)
 +                              MEM_freeN(d->depths);
 +                      d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
 +                      d->damaged = true;
 +              }
 +              
 +              if (d->damaged) {
 +                      view3d_opengl_read_pixels(ar, 0, 0, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
 +                      glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
 +                      
 +                      d->damaged = false;
 +              }
 +      }
 +}
 +
 +/* utility function to find the closest Z value, use for autodepth */
 +float view3d_depth_near(ViewDepths *d)
 +{
 +      /* convert to float for comparisons */
 +      const float near = (float)d->depth_range[0];
 +      const float far_real = (float)d->depth_range[1];
 +      float far = far_real;
 +
 +      const float *depths = d->depths;
 +      float depth = FLT_MAX;
 +      int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
 +
 +      /* far is both the starting 'far' value
 +       * and the closest value found. */
 +      while (i--) {
 +              depth = *depths++;
 +              if ((depth < far) && (depth > near)) {
 +                      far = depth;
 +              }
 +      }
 +
 +      return far == far_real ? FLT_MAX : far;
 +}
 +
 +void ED_view3d_draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
 +{
 +      bool zbuf = v3d->zbuf;
-       mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
-       invert_m4_m4(rv3d->persinv, rv3d->persmat);
-       invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
 +
-       gpuLoadMatrix(rv3d->viewmat);
++      /* Setup view matrix. */
++      ED_view3d_draw_setup_view(NULL, scene, ar, v3d, NULL, NULL);
 +
 +      glClear(GL_DEPTH_BUFFER_BIT);
 +
 +      v3d->zbuf = true;
 +      glEnable(GL_DEPTH_TEST);
 +
 +      if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 +              ED_gpencil_draw_view3d(NULL, scene, v3d, ar, true);
 +      }
 +
 +      v3d->zbuf = zbuf;
 +      if (!zbuf) glDisable(GL_DEPTH_TEST);
 +}
 +
 +void ED_view3d_draw_depth_loop(Scene *scene, ARegion *ar, View3D *v3d)
 +{
 +      Base *base;
 +      SceneLayer *sl = BKE_scene_layer_context_active(scene);
 +      /* no need for color when drawing depth buffer */
 +      const short dflag_depth = DRAW_CONSTCOLOR;
 +
 +      /* draw set first */
 +      if (scene->set) {
 +              Scene *sce_iter;
 +              for (SETLOOPER(scene->set, sce_iter, base)) {
 +                      if ((base->flag & BASE_VISIBLED) != 0) {
 +                              draw_object(scene, sl, ar, v3d, base, 0);
 +                              if (base->object->transflag & OB_DUPLI) {
 +                                      draw_dupli_objects_color(scene, sl, ar, v3d, base, dflag_depth, TH_UNDEFINED);
 +                              }
 +                      }
 +              }
 +      }
 +      
 +      for (base = sl->object_bases.first; base; base = base->next) {
 +              if ((base->flag & BASE_VISIBLED) != 0) {
 +                      /* dupli drawing */
 +                      if (base->object->transflag & OB_DUPLI) {
 +                              draw_dupli_objects_color(scene, sl, ar, v3d, base, dflag_depth, TH_UNDEFINED);
 +                      }
 +                      draw_object(scene, sl, ar, v3d, base, dflag_depth);
 +              }
 +      }
 +      
 +      /* this isn't that nice, draw xray objects as if they are normal */
 +      if (v3d->afterdraw_transp.first ||
 +          v3d->afterdraw_xray.first ||
 +          v3d->afterdraw_xraytransp.first)
 +      {
 +              View3DAfter *v3da;
 +              int mask_orig;
 +
 +              v3d->xray = true;
 +              
 +              /* transp materials can change the depth mask, see #21388 */
 +              glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
 +
 +
 +              if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
 +                      glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
 +                      for (v3da = v3d->afterdraw_xray.first; v3da; v3da = v3da->next) {
 +                              draw_object(scene, sl, ar, v3d, v3da->base, dflag_depth);
 +                      }
 +                      glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
 +              }
 +
 +              /* draw 3 passes, transp/xray/xraytransp */
 +              v3d->xray = false;
 +              v3d->transp = true;
 +              while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
 +                      draw_object(scene, sl, ar, v3d, v3da->base, dflag_depth);
 +                      MEM_freeN(v3da);
 +              }
 +
 +              v3d->xray = true;
 +              v3d->transp = false;
 +              while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 +                      draw_object(scene, sl, ar, v3d, v3da->base, dflag_depth);
 +                      MEM_freeN(v3da);
 +              }
 +
 +              v3d->xray = true;
 +              v3d->transp = true;
 +              while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
 +                      draw_object(scene, sl, ar, v3d, v3da->base, dflag_depth);
 +                      MEM_freeN(v3da);
 +              }
 +
 +              
 +              v3d->xray = false;
 +              v3d->transp = false;
 +
 +              glDepthMask(mask_orig);
 +      }
 +}
 +
 +void ED_view3d_draw_select_loop(
 +        ViewContext *vc, Scene *scene, SceneLayer *sl, View3D *v3d, ARegion *ar,
 +        bool use_obedit_skip, bool use_nearest)
 +{
 +      short code = 1;
 +      const short dflag = DRAW_PICKING | DRAW_CONSTCOLOR;
 +
 +      if (vc->obedit && vc->obedit->type == OB_MBALL) {
 +              draw_object(scene, sl, ar, v3d, BASACT_NEW, dflag);
 +      }
 +      else if ((vc->obedit && vc->obedit->type == OB_ARMATURE)) {
 +              /* if not drawing sketch, draw bones */
 +              if (!BDR_drawSketchNames(vc)) {
 +                      draw_object(scene, sl, ar, v3d, BASACT_NEW, dflag);
 +              }
 +      }
 +      else {
 +              Base *base;
 +
 +              for (base = sl->object_bases.first; base; base = base->next) {
 +                      if ((base->flag & BASE_VISIBLED) != 0) {
 +                              if (((base->flag & BASE_SELECTABLED) == 0) ||
 +                                  (use_obedit_skip && (scene->obedit->data == base->object->data)))
 +                              {
 +                                      base->selcol = 0;
 +                              }
 +                              else {
 +                                      base->selcol = code;
 +
 +                                      if (use_nearest && (base->object->dtx & OB_DRAWXRAY)) {
 +                                              ED_view3d_after_add(&v3d->afterdraw_xray, base, dflag);
 +                                      }
 +                                      else {
 +                                              if (GPU_select_load_id(code)) {
 +                                                      draw_object(scene, sl, ar, v3d, base, dflag);
 +                                              }
 +                                      }
 +                                      code++;
 +                              }
 +                      }
 +              }
 +
 +              if (use_nearest) {
 +                      bool xrayclear = true;
 +                      if (v3d->afterdraw_xray.first) {
 +                              view3d_draw_xray_select(scene, sl, ar, v3d, &xrayclear);
 +                      }
 +              }
 +      }
 +}
 +
 +typedef struct View3DShadow {
 +      struct View3DShadow *next, *prev;
 +      GPULamp *lamp;
 +} View3DShadow;
 +
 +static void gpu_render_lamp_update(Scene *scene, View3D *v3d,
 +                                   Object *ob, Object *par,
 +                                   float obmat[4][4], unsigned int lay,
 +                                   ListBase *shadows, SceneRenderLayer *srl)
 +{
 +      GPULamp *lamp = GPU_lamp_from_blender(scene, ob, par);
 +      
 +      if (lamp) {
 +              Lamp *la = (Lamp *)ob->data;
 +
 +              GPU_lamp_update(lamp, lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
 +              GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
 +              
 +              unsigned int layers = lay & v3d->lay;
 +              if (srl)
 +                      layers &= srl->lay;
 +
 +              if (layers &&
 +                  GPU_lamp_has_shadow_buffer(lamp) &&
 +                  /* keep last, may do string lookup */
 +                  GPU_lamp_override_visible(lamp, srl, NULL))
 +              {
 +                      View3DShadow *shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
 +                      shadow->lamp = lamp;
 +                      BLI_addtail(shadows, shadow);
 +              }
 +      }
 +}
 +
 +static void gpu_update_lamps_shadows_world(Scene *scene, View3D *v3d)
 +{
 +      ListBase shadows;
 +      Scene *sce_iter;
 +      Base *base;
 +      World *world = scene->world;
 +      SceneRenderLayer *srl = v3d->scenelock ? BLI_findlink(&scene->r.layers, scene->r.actlay) : NULL;
 +      
 +      BLI_listbase_clear(&shadows);
 +      
 +      /* update lamp transform and gather shadow lamps */
 +      for (SETLOOPER(scene, sce_iter, base)) {
 +              Object *ob = base->object;
 +              
 +              if (ob->type == OB_LAMP)
 +                      gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, ob->lay, &shadows, srl);
 +              
 +              if (ob->transflag & OB_DUPLI) {
 +                      DupliObject *dob;
 +                      ListBase *lb = object_duplilist(G.main->eval_ctx, scene, ob);
 +                      
 +                      for (dob = lb->first; dob; dob = dob->next)
 +                              if (dob->ob->type == OB_LAMP)
 +                                      gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, ob->lay, &shadows, srl);
 +                      
 +                      free_object_duplilist(lb);
 +              }
 +      }
 +      
 +      /* render shadows after updating all lamps, nested object_duplilist
 +       * don't work correct since it's replacing object matrices */
 +      for (View3DShadow *shadow = shadows.first; shadow; shadow = shadow->next) {
 +              /* this needs to be done better .. */
 +              float viewmat[4][4], winmat[4][4];
 +              ARegion ar = {NULL};
 +              RegionView3D rv3d = {{{0}}};
 +
 +              int drawtype = v3d->drawtype;
 +              int lay = v3d->lay;
 +              int flag2 = v3d->flag2;
 +
 +              v3d->drawtype = OB_SOLID;
 +              v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
 +              v3d->flag2 &= ~(V3D_SOLID_TEX | V3D_SHOW_SOLID_MATCAP);
 +              v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
 +              
 +              int winsize;
 +              GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
 +
 +              ar.regiondata = &rv3d;
 +              ar.regiontype = RGN_TYPE_WINDOW;
 +              rv3d.persp = RV3D_CAMOB;
 +              copy_m4_m4(rv3d.winmat, winmat);
 +              copy_m4_m4(rv3d.viewmat, viewmat);
 +              invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
 +              mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
 +              invert_m4_m4(rv3d.persinv, rv3d.viewinv);
 +
 +              /* no need to call ED_view3d_draw_offscreen_init since shadow buffers were already updated */
 +              ED_view3d_draw_offscreen(
 +                          scene, v3d, &ar, winsize, winsize, viewmat, winmat,
 +                          false, false, true,
 +                          NULL, NULL, NULL, NULL);
 +              GPU_lamp_shadow_buffer_unbind(shadow->lamp);
 +              
 +              v3d->drawtype = drawtype;
 +              v3d->lay = lay;
 +              v3d->flag2 = flag2;
 +      }
 +
 +      BLI_freelistN(&shadows);
 +
 +      /* update world values */
 +      if (world) {
 +              GPU_mist_update_enable(world->mode & WO_MIST);
 +              GPU_mist_update_values(world->mistype, world->miststa, world->mistdist, world->misi, &world->horr);
 +              GPU_horizon_update_color(&world->horr);
 +              GPU_ambient_update_color(&world->ambr);
 +              GPU_zenith_update_color(&world->zenr);
 +      }
 +}
 +
 +/* *********************** customdata **************** */
 +
 +CustomDataMask ED_view3d_datamask(const Scene *scene, const View3D *v3d)
 +{
 +      CustomDataMask mask = 0;
 +      const int drawtype = view3d_effective_drawtype(v3d);
 +
 +      if (ELEM(drawtype, OB_TEXTURE, OB_MATERIAL) ||
 +          ((drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
 +      {
 +              mask |= CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL;
 +
 +              if (BKE_scene_use_new_shading_nodes(scene)) {
 +                      if (drawtype == OB_MATERIAL)
 +                              mask |= CD_MASK_ORCO;
 +              }
 +              else {
 +                      if ((scene->gm.matmode == GAME_MAT_GLSL && drawtype == OB_TEXTURE) || 
 +                          (drawtype == OB_MATERIAL))
 +                      {
 +                              mask |= CD_MASK_ORCO;
 +                      }
 +              }
 +      }
 +
 +      return mask;
 +}
 +
 +/* goes over all modes and view3d settings */
 +CustomDataMask ED_view3d_screen_datamask(const bScreen *screen)
 +{
 +      const Scene *scene = screen->scene;
 +      CustomDataMask mask = CD_MASK_BAREMESH;
 +      
 +      /* check if we need tfaces & mcols due to view mode */
 +      for (const ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
 +              if (sa->spacetype == SPACE_VIEW3D) {
 +                      mask |= ED_view3d_datamask(scene, sa->spacedata.first);
 +              }
 +      }
 +
 +      return mask;
 +}
 +
 +/**
 + * Shared by #ED_view3d_draw_offscreen and #view3d_main_region_draw_objects
 + *
 + * \note \a C and \a grid_unit will be NULL when \a draw_offscreen is set.
 + * \note Drawing lamps and opengl render uses this, so dont do grease pencil or view widgets here.
 + */
 +static void view3d_draw_objects(
 +        const bContext *C,
 +        Scene *scene, View3D *v3d, ARegion *ar,
 +        const char **grid_unit,
 +        const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
 +{
 +      SceneLayer *sl = C ? CTX_data_scene_layer(C) : BKE_scene_layer_render_active(scene);
 +      RegionView3D *rv3d = ar->regiondata;
 +      Base *base;
 +      const bool do_camera_frame = !draw_offscreen;
 +      const bool draw_grids = !draw_offscreen && (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0;
 +      const bool draw_floor = (rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO);
 +      /* only draw grids after in solid modes, else it hovers over mesh wires */
 +      const bool draw_grids_after = draw_grids && draw_floor && (v3d->drawtype > OB_WIRE) && fx;
 +      bool do_composite_xray = false;
 +      bool xrayclear = true;
 +
 +      if (!draw_offscreen) {
 +              ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
 +      }
 +
 +      if (rv3d->rflag & RV3D_CLIPPING)
 +              view3d_draw_clipping(rv3d);
 +
 +      /* set zbuffer after we draw clipping region */
 +      v3d->zbuf = VP_legacy_use_depth(scene, v3d);
 +
 +      if (v3d->zbuf) {
 +              glEnable(GL_DEPTH_TEST);
 +      }
 +
 +      /* ortho grid goes first, does not write to depth buffer and doesn't need depth test so it will override
 +       * objects if done last */
 +      if (draw_grids) {
 +              /* needs to be done always, gridview is adjusted in drawgrid() now, but only for ortho views. */
 +              rv3d->gridview = ED_view3d_grid_scale(scene, v3d, grid_unit);
 +
 +              if (!draw_floor) {
 +                      ED_region_pixelspace(ar);
 +                      *grid_unit = NULL;  /* drawgrid need this to detect/affect smallest valid unit... */
 +                      VP_legacy_drawgrid(&scene->unit, ar, v3d, grid_unit);
 +                      gpuLoadProjectionMatrix(rv3d->winmat);
 +                      gpuLoadMatrix(rv3d->viewmat);
 +              }
 +              else if (!draw_grids_after) {
 +                      VP_legacy_drawfloor(scene, v3d, grid_unit, true);
 +              }
 +      }
 +
 +      /* important to do before clipping */
 +      if (do_bgpic) {
 +              view3d_draw_bgpic_test(scene, ar, v3d, false, do_camera_frame);
 +      }
 +
 +      if (rv3d->rflag & RV3D_CLIPPING) {
 +              ED_view3d_clipping_set(rv3d);
 +      }
 +
 +      /* draw set first */
 +      if (scene->set) {
 +              const short dflag = DRAW_CONSTCOLOR | DRAW_SCENESET;
 +              Scene *sce_iter;
 +              for (SETLOOPER(scene->set, sce_iter, base)) {
 +                      if ((base->flag & BASE_VISIBLED) != 0) {
 +                              UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
 +                              draw_object(scene, sl, ar, v3d, base, dflag);
 +
 +                              if (base->object->transflag & OB_DUPLI) {
 +                                      draw_dupli_objects_color(scene, sl, ar, v3d, base, dflag, TH_UNDEFINED);
 +                              }
 +                      }
 +              }
 +
 +              /* Transp and X-ray afterdraw stuff for sets is done later */
 +      }
 +
 +      if (draw_offscreen) {
 +              for (base = sl->object_bases.first; base; base = base->next) {
 +                      if ((base->flag & BASE_VISIBLED) != 0) {
 +                              /* dupli drawing */
 +                              if (base->object->transflag & OB_DUPLI)
 +                                      draw_dupli_objects(scene, sl, ar, v3d, base);
 +
 +                              draw_object(scene, sl, ar, v3d, base, 0);
 +                      }
 +              }
 +      }
 +      else {
 +              unsigned int lay_used = 0;
 +
 +              /* then draw not selected and the duplis, but skip editmode object */
 +              for (base = sl->object_bases.first; base; base = base->next) {
 +                      lay_used |= base->lay;
 +
 +                      if ((base->flag & BASE_VISIBLED) != 0) {
 +
 +                              /* dupli drawing */
 +                              if (base->object->transflag & OB_DUPLI) {
 +                                      draw_dupli_objects(scene, sl, ar, v3d, base);
 +                              }
 +                              if ((base->flag & BASE_SELECTED) == 0) {
 +                                      if (base->object != scene->obedit)
 +                                              draw_object(scene, sl, ar, v3d, base, 0);
 +                              }
 +                      }
 +              }
 +
 +              /* mask out localview */
 +              v3d->lay_used = lay_used & ((1 << 20) - 1);
 +
 +              /* draw selected and editmode */
 +              for (base = sl->object_bases.first; base; base = base->next) {
 +                      if ((base->flag & BASE_VISIBLED) != 0) {
 +                              if (base->object == scene->obedit || (base->flag & BASE_SELECTED)) {
 +                                      draw_object(scene, sl, ar, v3d, base, 0);
 +                              }
 +                      }
 +              }
 +      }
 +
 +      /* perspective floor goes last to use scene depth and avoid writing to depth buffer */
 +      if (draw_grids_after) {
 +              VP_legacy_drawfloor(scene, v3d, grid_unit, false);
 +      }
 +
 +      /* must be before xray draw which clears the depth buffer */
 +      if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 +              wmWindowManager *wm = (C != NULL) ? CTX_wm_manager(C) : NULL;
 +              
 +              /* must be before xray draw which clears the depth buffer */
 +              if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
 +              ED_gpencil_draw_view3d(wm, scene, v3d, ar, true);
 +              if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
 +      }
 +
 +      /* transp and X-ray afterdraw stuff */
 +      if (v3d->afterdraw_transp.first)     view3d_draw_transp(scene, sl, ar, v3d);
 +
 +      /* always do that here to cleanup depth buffers if none needed */
 +      if (fx) {
 +              do_composite_xray = v3d->zbuf && (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first);
 +              GPU_fx_compositor_setup_XRay_pass(fx, do_composite_xray);
 +      }
 +
 +      if (v3d->afterdraw_xray.first)       view3d_draw_xray(scene, sl, ar, v3d, &xrayclear);
 +      if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(scene, sl, ar, v3d, xrayclear);
 +
 +      if (fx && do_composite_xray) {
 +              GPU_fx_compositor_XRay_resolve(fx);
 +      }
 +
 +      if (!draw_offscreen) {
 +              ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
 +      }
 +
 +      if (rv3d->rflag & RV3D_CLIPPING)
 +              ED_view3d_clipping_disable();
 +
 +      /* important to do after clipping */
 +      if (do_bgpic) {
 +              view3d_draw_bgpic_test(scene, ar, v3d, true, do_camera_frame);
 +      }
 +
 +      /* cleanup */
 +      if (v3d->zbuf) {
 +              v3d->zbuf = false;
 +              glDisable(GL_DEPTH_TEST);
 +      }
 +
 +      if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
 +              GPU_free_images_old();
 +      }
 +}
 +
 +/**
 + * Store values from #RegionView3D, set when drawing.
 + * This is needed when we draw with to a viewport using a different matrix (offscreen drawing for example).
 + *
 + * Values set by #ED_view3d_update_viewmat should be handled here.
 + */
 +struct RV3DMatrixStore {
 +      float winmat[4][4];
 +      float viewmat[4][4];
 +      float viewinv[4][4];
 +      float persmat[4][4];
 +      float persinv[4][4];
 +      float viewcamtexcofac[4];
 +      float pixsize;
 +};
 +
 +struct RV3DMatrixStore *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
 +{
 +      struct RV3DMatrixStore *rv3dmat = MEM_mallocN(sizeof(*rv3dmat), __func__);
 +      copy_m4_m4(rv3dmat->winmat, rv3d->winmat);
 +      copy_m4_m4(rv3dmat->viewmat, rv3d->viewmat);
 +      copy_m4_m4(rv3dmat->persmat, rv3d->persmat);
 +      copy_m4_m4(rv3dmat->persinv, rv3d->persinv);
 +      copy_m4_m4(rv3dmat->viewinv, rv3d->viewinv);
 +      copy_v4_v4(rv3dmat->viewcamtexcofac, rv3d->viewcamtexcofac);
 +      rv3dmat->pixsize = rv3d->pixsize;
 +      return (void *)rv3dmat;
 +}
 +
 +void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, struct RV3DMatrixStore *rv3dmat_pt)
 +{
 +      struct RV3DMatrixStore *rv3dmat = rv3dmat_pt;
 +      copy_m4_m4(rv3d->winmat, rv3dmat->winmat);
 +      copy_m4_m4(rv3d->viewmat, rv3dmat->viewmat);
 +      copy_m4_m4(rv3d->persmat, rv3dmat->persmat);
 +      copy_m4_m4(rv3d->persinv, rv3dmat->persinv);
 +      copy_m4_m4(rv3d->viewinv, rv3dmat->viewinv);
 +      copy_v4_v4(rv3d->viewcamtexcofac, rv3dmat->viewcamtexcofac);
 +      rv3d->pixsize = rv3dmat->pixsize;
 +}
 +
 +/**
 + * \note The info that this uses is updated in #ED_refresh_viewport_fps,
 + * which currently gets called during #SCREEN_OT_animation_step.
 + */
 +void ED_scene_draw_fps(Scene *scene, const rcti *rect)
 +{
 +      ScreenFrameRateInfo *fpsi = scene->fps_info;
 +      char printable[16];
 +      
 +      if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
 +              return;
 +      
 +      printable[0] = '\0';
 +      
 +#if 0
 +      /* this is too simple, better do an average */
 +      fps = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime))
 +#else
 +      fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime));
 +      
 +      float fps = 0.0f;
 +      int tot = 0;
 +      for (int i = 0; i < REDRAW_FRAME_AVERAGE; i++) {
 +              if (fpsi->redrawtimes_fps[i]) {
 +                      fps += fpsi->redrawtimes_fps[i];
 +                      tot++;
 +              }
 +      }
 +      if (tot) {
 +              fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
 +              
 +              //fpsi->redrawtime_index++;
 +              //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
 +              //      fpsi->redrawtime = 0;
 +              
 +              fps = fps / tot;
 +      }
 +#endif
 +
 +      const int font_id = BLF_default();
 +
 +      /* is this more than half a frame behind? */
 +      if (fps + 0.5f < (float)(FPS)) {
 +              UI_FontThemeColor(font_id, TH_REDALERT);
 +              BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %.2f"), fps);
 +      }
 +      else {
 +              UI_FontThemeColor(font_id, TH_TEXT_HI);
 +              BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %i"), (int)(fps + 0.5f));
 +      }
 +
 +#ifdef WITH_INTERNATIONAL
 +      BLF_draw_default(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
 +#else
 +      BLF_draw_default_ascii(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
 +#endif
 +}
 +
 +static bool view3d_main_region_do_render_draw(Scene *scene)
 +{
 +      RenderEngineType *type = RE_engines_find(scene->r.engine);
 +
 +      return (type && type->view_update && type->render_to_view);
 +}
 +
 +bool ED_view3d_calc_render_border(Scene *scene, View3D *v3d, ARegion *ar, rcti *rect)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
 +      bool use_border;
 +
 +      /* test if there is a 3d view rendering */
 +      if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene))
 +              return false;
 +
 +      /* test if there is a border render */
 +      if (rv3d->persp == RV3D_CAMOB)
 +              use_border = (scene->r.mode & R_BORDER) != 0;
 +      else
 +              use_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
 +      
 +      if (!use_border)
 +              return false;
 +
 +      /* compute border */
 +      if (rv3d->persp == RV3D_CAMOB) {
 +              rctf viewborder;
 +              ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
 +
 +              rect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
 +              rect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
 +              rect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
 +              rect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
 +      }
 +      else {
 +              rect->xmin = v3d->render_border.xmin * ar->winx;
 +              rect->xmax = v3d->render_border.xmax * ar->winx;
 +              rect->ymin = v3d->render_border.ymin * ar->winy;
 +              rect->ymax = v3d->render_border.ymax * ar->winy;
 +      }
 +
 +      BLI_rcti_translate(rect, ar->winrct.xmin, ar->winrct.ymin);
 +      BLI_rcti_isect(&ar->winrct, rect, rect);
 +
 +      return true;
 +}
 +
 +/**
 +  * IMPORTANT: this is deprecated, any changes made in this function should
 +  * be mirrored in view3d_draw_render_draw() in view3d_draw.c
 +  */
 +static bool view3d_main_region_draw_engine(const bContext *C, Scene *scene,
 +                                         ARegion *ar, View3D *v3d,
 +                                         bool clip_border, const rcti *border_rect)
 +{
 +      RegionView3D *rv3d = ar->regiondata;
 +      RenderEngineType *type;
 +      GLint scissor[4];
 +
 +      /* create render engine */
 +      if (!rv3d->render_engine) {
 +              RenderEngine *engine;
 +
 +              type = RE_engines_find(scene->r.engine);
 +
 +              if (!(type->view_update && type->render_to_view))
 +                      return false;
 +
 +              engine = RE_engine_create_ex(type, true);
 +
 +              engine->tile_x = scene->r.tilex;
 +              engine->tile_y = scene->r.tiley;
 +
 +              type->view_update(engine, C);
 +
 +              rv3d->render_engine = engine;
 +      }
 +
 +      /* setup view matrices */
 +      VP_legacy_view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
 +
 +      /* background draw */
 +      ED_region_pixelspace(ar);
 +
 +      if (clip_border) {
 +              /* for border draw, we only need to clear a subset of the 3d view */
 +              if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
 +                      glGetIntegerv(GL_SCISSOR_BOX, scissor);
 +                      glScissor(border_rect->xmin, border_rect->ymin,
 +                                BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
 +              }
 +              else {
 +                      return false;
 +              }
 +      }
 +
 +      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
 +      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 +
 +      if (v3d->flag & V3D_DISPBGPICS)
 +              view3d_draw_bgpic_test(scene, ar, v3d, false, true);
 +      else
 +              imm_draw_checker_box(0, 0, ar->winx, ar->winy);
 +
 +      /* render result draw */
 +      type = rv3d->render_engine->type;
 +      type->render_to_view(rv3d->render_engine, C);
 +
 +      if (v3d->flag & V3D_DISPBGPICS)
 +              view3d_draw_bgpic_test(scene, ar, v3d, true, true);
 +
 +      if (clip_border) {
 +              /* restore scissor as it was before */
 +              glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
 +      }
 +
 +      return true;
 +}
 +
 +static void view3d_main_region_draw_engine_info(View3D *v3d, RegionView3D *rv3d, ARegion *ar, bool render_border)
 +{
 +      float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
 +
 +      if (!rv3d->render_engine || !rv3d->render_engine->text[0])
 +              return;
 +      
 +      if (render_border) {
 +              /* draw darkened background color. no alpha because border render does
 +               * partial redraw and will not redraw the region behind this info bar */
 +              float alpha = 1.0f - fill_color[3];
 +              Camera *camera = ED_view3d_camera_data_get(v3d, rv3d);
 +
 +              if (camera) {
 +                      if (camera->flag & CAM_SHOWPASSEPARTOUT) {
 +                              alpha *= (1.0f - camera->passepartalpha);
 +                      }
 +              }
 +
 +              UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
 +              mul_v3_fl(fill_color, alpha);
 +              fill_color[3] = 1.0f;
 +      }
 +
 +      ED_region_info_draw(ar, rv3d->render_engine->text, fill_color, true);
 +}
 +
 +#ifdef WITH_GAMEENGINE
 +static void update_lods(Scene *scene, float camera_pos[3])
 +{
 +      Scene *sce_iter;
 +      Base *base;
 +
 +      for (SETLOOPER(scene, sce_iter, base)) {
 +              Object *ob = base->object;
 +              BKE_object_lod_update(ob, camera_pos);
 +      }
 +}
 +#endif
 +
 +static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, SceneLayer *sl, View3D *v3d,
 +                                          ARegion *ar, const char **grid_unit)
 +{
 +      wmWindow *win = CTX_wm_window(C);
 +      RegionView3D *rv3d = ar->regiondata;
 +      unsigned int lay_used = v3d->lay_used;
 +      
 +      /* post processing */
 +      bool do_compositing = false;
 +      
 +      /* shadow buffers, before we setup matrices */
 +      if (draw_glsl_material(scene, sl, NULL, v3d, v3d->drawtype))
 +              gpu_update_lamps_shadows_world(scene, v3d);
 +
 +      /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
 +      if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
 +              rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
 +              GPU_default_lights();
 +      }
 +
 +      /* setup the view matrix */
 +      if (VP_legacy_view3d_stereo3d_active(C, scene, v3d, rv3d))
 +              VP_legacy_view3d_stereo3d_setup(scene, v3d, ar);
 +      else
 +              VP_legacy_view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
 +
 +      rv3d->rflag &= ~RV3D_IS_GAME_ENGINE;
 +#ifdef WITH_GAMEENGINE
 +      if (STREQ(scene->r.engine, RE_engine_id_BLENDER_GAME)) {
 +              rv3d->rflag |= RV3D_IS_GAME_ENGINE;
 +
 +              /* Make sure LoDs are up to date */
 +              update_lods(scene, rv3d->viewinv[3]);
 +      }
 +#endif
 +
 +      /* framebuffer fx needed, we need to draw offscreen first */
 +      if (v3d->fx_settings.fx_flag && v3d->drawtype >= OB_SOLID) {
 +              BKE_screen_gpu_fx_validate(&v3d->fx_settings);
 +              GPUFXSettings fx_settings = v3d->fx_settings;
 +              if (!rv3d->compositor)
 +                      rv3d->compositor = GPU_fx_compositor_create();
 +              
 +              if (rv3d->persp == RV3D_CAMOB && v3d->camera)
 +                      BKE_camera_to_gpu_dof(v3d->camera, &fx_settings);
 +              else {
 +                      fx_settings.dof = NULL;
 +              }
 +
 +              do_compositing = GPU_fx_compositor_initialize_passes(rv3d->compositor, &ar->winrct, &ar->drawrct, &fx_settings);
 +      }
 +      
 +      /* enables anti-aliasing for 3D view drawing */
 +      if (win->multisamples != USER_MULTISAMPLE_NONE) {
 +              glEnable(GL_MULTISAMPLE);
 +      }
 +
 +      /* main drawing call */
 +      view3d_draw_objects(C, scene, v3d, ar, grid_unit, true, false, do_compositing ? rv3d->compositor : NULL);
 +
 +      /* draw depth culled manipulators - manipulators need to be updated *after* view matrix was set up */
 +      /* TODO depth culling manipulators is not yet supported, just drawing _3D here, should
 +       * later become _IN_SCENE (and draw _3D separate) */
 +      WM_manipulatormap_draw(ar->manipulator_map, C, WM_MANIPULATORMAP_DRAWSTEP_3D);
 +
 +      /* post process */
 +      if (do_compositing) {
 +              GPU_fx_do_composite_pass(rv3d->compositor, rv3d->winmat, rv3d->is_persp, scene, NULL);
 +      }
 +
 +      /* Disable back anti-aliasing */
 +      if (win->multisamples != USER_MULTISAMPLE_NONE) {
 +              glDisable(GL_MULTISAMPLE);
 +      }
 +
 +      if (v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
 +              /* find header and force tag redraw */
 +              ScrArea *sa = CTX_wm_area(C);
 +              ARegion *ar_header = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
 +              ED_region_tag_redraw(ar_header); /* can be NULL */
 +      }
 +
 +      if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
 +              BDR_drawSketch(C);
 +      }
 +}
 +
 +static void view3d_main_region_draw_info(const bContext *C, Scene *scene,
 +                                       ARegion *ar, View3D *v3d,
 +                                       const char *grid_unit, bool render_border)
 +{
 +      SceneLayer *sl = CTX_data_scene_layer(C);
 +      wmWindowManager *wm = CTX_wm_manager(C);
 +      RegionView3D *rv3d = ar->regiondata;
 +      rcti rect;
 +      
 +      /* local coordinate visible rect inside region, to accomodate overlapping ui */
 +      ED_region_visible_rect(ar, &rect);
 +
 +      if (rv3d->persp == RV3D_CAMOB) {
 +              VP_drawviewborder(scene, ar, v3d);
 +      }
 +      else if (v3d->flag2 & V3D_RENDER_BORDER) {
 +              VP_drawrenderborder(ar, v3d);
 +      }
 +
 +      if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 +              /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
 +              ED_gpencil_draw_view3d(wm, scene, v3d, ar, false);
 +      }
 +
 +      if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
 +              VP_legacy_drawcursor(scene, sl, ar, v3d); /* 3D cursor */
 +
 +              if (U.uiflag & USER_SHOW_ROTVIEWICON)
 +                      VP_legacy_draw_view_axis(rv3d, &rect);
 +              else
 +                      draw_view_icon(rv3d, &rect);
 +
 +              if (U.uiflag & USER_DRAWVIEWINFO) {
 +                      Object *ob = OBACT_NEW;
 +                      VP_legacy_draw_selected_name(scene, ob, &rect);
 +              }
 +      }
 +
 +      if (rv3d->render_engine) {
 +              view3d_main_region_draw_engine_info(v3d, rv3d, ar, render_border);
 +              return;
 +      }
 +
 +      if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
 +              if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_no_scrub(wm)) {
 +                      ED_scene_draw_fps(scene, &rect);
 +              }
 +              else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
 +                      VP_legacy_draw_viewport_name(ar, v3d, &rect);
 +              }
 +
 +              if (grid_unit) { /* draw below the viewport name */
 +                      char numstr[32] = "";
 +
 +                      UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
 +                      if (v3d->grid != 1.0f) {
 +                              BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
 +                      }
 +
 +                      BLF_draw_default_ascii(rect.xmin + U.widget_unit,
 +                                             rect.ymax - (USER_SHOW_VIEWPORTNAME ? 2 * U.widget_unit : U.widget_unit), 0.0f,
 +                                             numstr[0] ? numstr : grid_unit, sizeof(numstr));
 +              }
 +      }
 +}
 +
 +void view3d_main_region_draw_legacy(const bContext *C, ARegion *ar)
 +{
 +      Scene *scene = CTX_data_scene(C);
 +      SceneLayer *sl = CTX_data_scene_layer(C);
 +      View3D *v3d = CTX_wm_view3d(C);
 +      const char *grid_unit = NULL;
 +      rcti border_rect;
 +
 +      /* if we only redraw render border area, skip opengl draw and also
 +       * don't do scissor because it's already set */
 +      bool render_border = ED_view3d_calc_render_border(scene, v3d, ar, &border_rect);
 +      bool clip_border = (render_border && !BLI_rcti_compare(&ar->drawrct, &border_rect));
 +
 +      gpuPushProjectionMatrix();
 +      gpuLoadIdentityProjectionMatrix();
 +      gpuPushMatrix();
 +      gpuLoadIdentity();
 +
 +      /* draw viewport using opengl */
 +      if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene) || clip_border) {
 +              VP_view3d_main_region_clear(scene, v3d, ar); /* background */
 +              view3d_main_region_draw_objects(C, scene, sl, v3d, ar, &grid_unit);
 +
 +              if (G.debug & G_DEBUG_SIMDATA)
 +                      draw_sim_debug_data(scene, v3d, ar);
 +
 +              glDisable(GL_DEPTH_TEST);
 +              ED_region_pixelspace(ar);
 +      }
 +
 +      /* draw viewport using external renderer */
 +      if (v3d->drawtype == OB_RENDER)
 +              view3d_main_region_draw_engine(C, scene, ar, v3d, clip_border, &border_rect);
 +
 +      VP_legacy_view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
 +      glClear(GL_DEPTH_BUFFER_BIT);
 +
 +      WM_manipulatormap_draw(ar->manipulator_map, C, WM_MANIPULATORMAP_DRAWSTEP_2D);
 +
 +      ED_region_pixelspace(ar);
 +
 +      view3d_main_region_draw_info(C, scene, ar, v3d, grid_unit, render_border);
 +
 +      gpuPopProjectionMatrix();
 +      gpuPopMatrix();
 +
 +      v3d->flag |= V3D_INVALID_BACKBUF;
 +
 +      BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_transp));
 +      BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xray));
 +      BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xraytransp));
 +}
 +
 +
 +/* -------------------------------------------------------------------- */
 +
 +/** \name Deprecated Interface
 + *
 + * New viewport sometimes has a check for new/old viewport code.
 + * Use these functions so new viewport can *optionally* call.
 + *
 + * \{ */
 +
 +
 +void VP_deprecated_view3d_draw_objects(
 +        const bContext *C,
 +        Scene *scene, View3D *v3d, ARegion *ar,
 +        const char **grid_unit,
 +        const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
 +{
 +      view3d_draw_objects(C, scene, v3d, ar, grid_unit, do_bgpic, draw_offscreen, fx);
 +}
 +
 +void VP_deprecated_gpu_update_lamps_shadows_world(Scene *scene, View3D *v3d)
 +{
 +      gpu_update_lamps_shadows_world(scene, v3d);
 +}
 +
 +/** \} */