Merge branch 'master' into blender2.8
authorCampbell Barton <ideasman42@gmail.com>
Fri, 25 Aug 2017 10:45:16 +0000 (20:45 +1000)
committerCampbell Barton <ideasman42@gmail.com>
Fri, 25 Aug 2017 10:45:16 +0000 (20:45 +1000)
1  2 
source/blender/editors/space_view3d/view3d_draw.c
source/blender/python/bmesh/bmesh_py_types.c
source/blender/windowmanager/intern/wm.c
source/blender/windowmanager/intern/wm_event_system.c
source/blender/windowmanager/wm_event_system.h

index c85cf6890683cd1d53abf968897f14996c8ebeed,56508ea989a8689eb5d20898873056d23cf651d6..688bee4760b287a532496e284554efa2da1bc159
@@@ -628,420 -1275,1264 +628,427 @@@ static void drawviewborder(Scene *scene
                        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;
 -
 -                      /* 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;
 -
 -                              rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
 -                              rect.xmax = rect.xmin + sensor_width;
 -                              rect.ymin = y1i;
 -                              rect.ymax = y2i;
 -                      }
 -
 -                      /* 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);
 -              }
 -      }
 -
 -      setlinestyle(0);
 -
 -      /* 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 *************** */
 -
 -static void backdrawview3d(Scene *scene, wmWindow *win, ARegion *ar, View3D *v3d)
 -{
 -      RegionView3D *rv3d = ar->regiondata;
 -      struct Base *base = scene->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->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 */
 -
 -      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_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);
 -}
 -
 -void ED_view3d_backbuf_validate(ViewContext *vc)
 -{
 -      if (vc->v3d->flag & V3D_INVALID_BACKBUF)
 -              backdrawview3d(vc->scene, 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)
 -{
 -      unsigned int col;
 -      
 -      if (x >= vc->ar->winx || y >= vc->ar->winy) {
 -              return 0;
 -      }
 -
 -      ED_view3d_backbuf_validate(vc);
 -
 -      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)
 -{
 -      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;
 -      }
 -
 -      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 */
 -              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;
 -      }
 -}
 -
 -/* 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;
 -              }
 -      }
 -
 -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;
 -      BGpic *bgpic;
 -      int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
 -
 -      for (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 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;
 -                              }
 -
 -                              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) */
 -
 -                              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) / 2.0f;
 -                              centy = (y1 + y2) / 2.0f;
 -
 -                              /* 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};
 -                              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;
 -                      }
 +                      float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
  
 -                      /* complete clip? */
 -                      BLI_rctf_init(&clip_rect, x1, x2, y1, y2);
 -                      if (bgpic->rotation) {
 -                              BLI_rctf_rotate_expand(&clip_rect, &clip_rect, bgpic->rotation);
 -                      }
 +                      /* determine sensor plane */
 +                      rctf rect;
  
 -                      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);
 +                      if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
 +                              float sensor_scale = (x2i - x1i) / sensor_x;
 +                              float sensor_height = sensor_scale * sensor_y;
  
 -                              continue;
 +                              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;
  
 -                      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;
 -
 -                              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];
 +                              rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
 +                              rect.xmax = rect.xmin + sensor_width;
 +                              rect.ymin = y1i;
 +                              rect.ymax = y2i;
                        }
  
 -                      if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
 -                      glDepthMask(0);
 -
 -                      glEnable(GL_BLEND);
 -                      glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
 +                      /* 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);
 +              }
 +      }
  
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPushMatrix();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPushMatrix();
 -                      ED_region_pixelspace(ar);
 +      immUnbindProgram();
 +      /* end dashed lines */
  
 -                      glTranslatef(centx, centy, 0.0);
 -                      glRotatef(RAD2DEGF(-bgpic->rotation), 0.0f, 0.0f, 1.0f);
 +      /* 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);
 +      }
 +}
  
 -                      if (bgpic->flag & V3D_BGPIC_FLIP_X) {
 -                              zoomx *= -1.0f;
 -                              x1 = x2;
 -                      }
 -                      if (bgpic->flag & V3D_BGPIC_FLIP_Y) {
 -                              zoomy *= -1.0f;
 -                              y1 = y2;
 -                      }
 -                      glPixelZoom(zoomx, zoomy);
 -                      glColor4f(1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend);
 +static void drawrenderborder(ARegion *ar, View3D *v3d)
 +{
 +      /* use the same program for everything */
 +      uint shdr_pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
  
 -                      /* 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);
 +      glLineWidth(1.0f);
  
 -                      glPixelZoom(1.0, 1.0);
 -                      glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
 +      immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
  
 -                      glMatrixMode(GL_PROJECTION);
 -                      glPopMatrix();
 -                      glMatrixMode(GL_MODELVIEW);
 -                      glPopMatrix();
 +      float viewport_size[4];
 +      glGetFloatv(GL_VIEWPORT, viewport_size);
 +      immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
  
 -                      glDisable(GL_BLEND);
 +      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);
  
 -                      glDepthMask(1);
 -                      if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
 +      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);
  
 -                      if (freeibuf)
 -                              IMB_freeImBuf(freeibuf);
 -                      if (releaseibuf)
 -                              BKE_image_release_ibuf(ima, releaseibuf, lock);
 -              }
 -      }
 +      immUnbindProgram();
  }
  
 -static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
 -                                   const bool do_foreground, const bool do_camera_frame)
 +void ED_view3d_draw_depth(
 +        const EvaluationContext *eval_ctx, struct Depsgraph *graph,
 +        ARegion *ar, View3D *v3d, bool alphaoverride)
  {
++      struct bThemeState theme_state;
 +      Scene *scene = DEG_get_evaluated_scene(graph);
        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);
 -      }
 -}
 +      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 afterdraw *************** */
++      /* Tools may request depth outside of regular drawing code. */
++      UI_Theme_Store(&theme_state);
++      UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
 -typedef struct View3DAfter {
 -      struct View3DAfter *next, *prev;
 -      struct Base *base;
 -      short dflag;
 -} View3DAfter;
 +      ED_view3d_draw_setup_view(NULL, eval_ctx, scene, ar, v3d, NULL, NULL, NULL);
  
 -/* temp storage of Objects that need to be drawn as last */
 -void ED_view3d_after_add(ListBase *lb, Base *base, const short dflag)
 -{
 -      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;
 -}
 +      glClear(GL_DEPTH_BUFFER_BIT);
  
 -/* 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);
 +      if (rv3d->rflag & RV3D_CLIPPING) {
 +              ED_view3d_clipping_set(rv3d);
        }
 -      v3d->transp = false;
 -      
 -      glDepthMask(GL_TRUE);
 -      
 -}
 +      /* get surface depth without bias */
 +      rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
  
 -/* clears zbuffer and draws it over */
 -static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, bool *clear)
 -{
 -      View3DAfter *v3da;
 +      v3d->zbuf = true;
 +      glEnable(GL_DEPTH_TEST);
  
 -      if (*clear && v3d->zbuf) {
 -              glClear(GL_DEPTH_BUFFER_BIT);
 -              *clear = false;
 +#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);
        }
  
 -      v3d->xray = true;
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
 -              draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
 -              MEM_freeN(v3da);
 +      if (rv3d->rflag & RV3D_CLIPPING) {
 +              ED_view3d_clipping_disable();
        }
 -      v3d->xray = false;
 +      rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
 +
 +      v3d->zbuf = zbuf;
 +      if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
 +
 +      U.glalphaclip = glalphaclip;
 +      v3d->flag = flag;
 +      U.obcenter_dia = obcenter_dia;
++
++      UI_Theme_Restore(&theme_state);
  }
  
 +/* ******************** background plates ***************** */
  
 -/* clears zbuffer and draws it over */
 -static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, const bool clear)
 +static void view3d_draw_background_gradient(void)
  {
 -      View3DAfter *v3da;
 +      /* TODO: finish 2D API & draw background with that */
  
 -      if (clear && v3d->zbuf)
 -              glClear(GL_DEPTH_BUFFER_BIT);
 +      Gwn_VertFormat *format = immVertexFormat();
 +      unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
 +      unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
 +      unsigned char col_hi[3], col_lo[3];
  
 -      v3d->xray = true;
 -      v3d->transp = true;
 -      
 -      glDepthMask(GL_FALSE);
 +      immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR);
  
 -      while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
 -              draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
 -              MEM_freeN(v3da);
 -      }
 +      UI_GetThemeColor3ubv(TH_LOW_GRAD, col_lo);
 +      UI_GetThemeColor3ubv(TH_HIGH_GRAD, col_hi);
  
 -      v3d->transp = false;
 -      v3d->xray = false;
 +      immBegin(GWN_PRIM_TRI_FAN, 4);
 +      immAttrib3ubv(color, col_lo);
 +      immVertex2f(pos, -1.0f, -1.0f);
 +      immVertex2f(pos, 1.0f, -1.0f);
  
 -      glDepthMask(GL_TRUE);
 +      immAttrib3ubv(color, col_hi);
 +      immVertex2f(pos, 1.0f, 1.0f);
 +      immVertex2f(pos, -1.0f, 1.0f);
 +      immEnd();
 +
 +      immUnbindProgram();
  }
  
 -/* 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)
 +static void view3d_draw_background_none(void)
  {
 -      /* 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);
 -      }
 +      UI_ThemeClearColorAlpha(TH_HIGH_GRAD, 1.0f);
 +      glClear(GL_COLOR_BUFFER_BIT);
 +}
  
 -      View3DAfter *v3da;
 -      if (*clear && v3d->zbuf) {
 -              glClear(GL_DEPTH_BUFFER_BIT);
 -              *clear = false;
 -      }
 +static void view3d_draw_background_world(Scene *scene, View3D *v3d, RegionView3D *rv3d)
 +{
 +      if (scene->world) {
 +              GPUMaterial *gpumat = GPU_material_world(scene, scene->world);
 +
 +              /* 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();
  
 -      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);
 +                      GPU_material_unbind(gpumat);
 +                      return;
                }
 -              MEM_freeN(v3da);
        }
 -      v3d->xray = false;
 -}
  
 -/* *********************** */
 +      /* if any of the above fails */
 +      view3d_draw_background_none();
 +}
  
 -/*
 - * 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
 - */
 +/* ******************** other elements ***************** */
  
 -#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
  
 +#define DEBUG_GRID 0
  
 -static DupliObject *dupli_step(DupliObject *dob)
 +static void gridline_range(double x0, double dx, double max, int *r_first, int *r_count)
  {
 -      while (dob && dob->no_draw)
 -              dob = dob->next;
 -      return dob;
 -}
 +      /* 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 */
  
 -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);
 +      int first = (int)ceil(-x0 / dx);
 +      int last = (int)floor((max - x0) / dx);
 +
 +      if (first <= last) {
 +              *r_first = first;
 +              *r_count = last - first + 1;
        }
        else {
 -              UI_GetThemeColorBlend3ubv(color, TH_BACK, 0.5f, color_rgb);
 +              *r_first = 0;
 +              *r_count = 0;
        }
  
 -      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. */
 -
 -      apply_data = duplilist_apply(base->object, scene, lb);
 -
 -      dob = dupli_step(lb->first);
 -      if (dob) dob_next = dupli_step(dob->next);
 -
 -      for (; dob; dob_prev = 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]);
 -              }
 +#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
 +}
  
 -              /* 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);
 +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 */
  
 -              /* 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;
 +#if DEBUG_GRID
 +      printf("  %s(%f, %f, dx:%f)\n", __FUNCTION__, x0, y0, dx);
 +#endif
  
 -              /* negative scale flag has to propagate */
 -              transflag = tbase.object->transflag;
 +      int first, x_ct, y_ct;
  
 -              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;
 -              }
 +      gridline_range(x0, dx, ar->winx, &first, &x_ct);
 +      gridline_range(y0, dx, ar->winy, &first, &y_ct);
  
 -              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 (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();
 -                      }
 -              }
 -              
 -              tbase.object->dt = dt;
 -              tbase.object->dtx = dtx;
 -              tbase.object->transflag = transflag;
 -              tbase.object->currentlod = savedlod;
 -      }
 +      int total_ct = x_ct + y_ct;
  
 -      if (apply_data) {
 -              duplilist_restore(lb, apply_data);
 -              duplilist_free_apply_data(apply_data);
 -      }
 +#if DEBUG_GRID
 +      printf("   %d + %d = %d gridlines\n", x_ct, y_ct, total_ct);
 +#endif
  
 -      free_object_duplilist(lb);
 -      
 -      if (use_displist)
 -              glDeleteLists(displist, 1);
 +      return total_ct;
  }
  
 -static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
 +static bool drawgrid_draw(ARegion *ar, double x0, double y0, double dx, int skip_mod, unsigned pos, unsigned col, GLubyte col_value[3])
  {
 -      /* 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);
 -}
 +      /* 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! */
  
 -/* XXX warning, not using gpu offscreen here */
 -void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
 -{
 -      int x, y, w, h;
 -      rcti r;
 -      /* clamp rect by region */
 +#if DEBUG_GRID
 +      printf("  %s(%f, %f, dx:%f, skip_mod:%d)\n", __FUNCTION__, x0, y0, dx, skip_mod);
 +#endif
  
 -      r.xmin = 0;
 -      r.xmax = ar->winx - 1;
 -      r.ymin = 0;
 -      r.ymax = ar->winy - 1;
 +      const float x_max = (float)ar->winx;
 +      const float y_max = (float)ar->winy;
  
 -      /* Constrain rect to depth bounds */
 -      BLI_rcti_isect(&r, rect, rect);
 +      int first, ct;
 +      int x_ct = 0, y_ct = 0; /* count of lines actually drawn */
 +      int lines_skipped_for_next_unit = 0;
  
 -      /* assign values to compare with the ViewDepths */
 -      x = rect->xmin;
 -      y = rect->ymin;
 +      /* draw vertical lines */
 +      gridline_range(x0, dx, x_max, &first, &ct);
  
 -      w = BLI_rcti_size_x(rect);
 -      h = BLI_rcti_size_y(rect);
 +      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 (w <= 0 || h <= 0) {
 -              if (d->depths)
 -                      MEM_freeN(d->depths);
 -              d->depths = NULL;
 +              if (x_ct == 0)
 +                      immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
  
 -              d->damaged = false;
 +              float x = (float)(x0 + i * dx);
 +              immVertex2f(pos, x, 0.0f);
 +              immVertex2f(pos, x, y_max);
 +              ++x_ct;
        }
 -      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);
 +      /* draw horizontal lines */
 +      gridline_range(y0, dx, y_max, &first, &ct);
  
 -              d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
 -              
 -              d->damaged = true;
 -      }
 +      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 (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;
 -      }
 -}
 +              if (x_ct + y_ct == 0)
 +                      immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
  
 -/* 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;
 -              }
 +              float y = (float)(y0 + i * dx);
 +              immVertex2f(pos, 0.0f, y);
 +              immVertex2f(pos, x_max, y);
 +              ++y_ct;
        }
 -}
  
 -/* 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;
 -              }
 -      }
 +#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
  
 -      return far == far_real ? FLT_MAX : far;
 +      return lines_skipped_for_next_unit > 0;
  }
  
 -void ED_view3d_draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
 +#define GRID_MIN_PX_D 6.0
 +#define GRID_MIN_PX_F 6.0f
 +
 +static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
  {
 -      short zbuf = v3d->zbuf;
        RegionView3D *rv3d = ar->regiondata;
  
 -      /* Setup view matrix. */
 -      ED_view3d_draw_setup_view(NULL, scene, ar, v3d, rv3d->viewmat, rv3d->winmat, NULL);
 +#if DEBUG_GRID
 +      printf("%s width %d, height %d\n", __FUNCTION__, ar->winx, ar->winy);
 +#endif
  
 -      glClear(GL_DEPTH_BUFFER_BIT);
 +      double fx = rv3d->persmat[3][0];
 +      double fy = rv3d->persmat[3][1];
 +      double fw = rv3d->persmat[3][3];
  
 -      v3d->zbuf = true;
 -      glEnable(GL_DEPTH_TEST);
 +      const double wx = 0.5 * ar->winx;  /* use double precision to avoid rounding errors */
 +      const double wy = 0.5 * ar->winy;
  
 -      if (v3d->flag2 & V3D_SHOW_GPENCIL) {
 -              ED_gpencil_draw_view3d(NULL, scene, v3d, ar, true);
 -      }
 -      
 -      v3d->zbuf = zbuf;
 -}
 +      double x = wx * fx / fw;
 +      double y = wy * fy / fw;
  
 -static void view3d_draw_depth_loop(Scene *scene, ARegion *ar, View3D *v3d)
 -{
 -      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);
 -                              }
 -                      }
 -              }
 -      }
 -      
 -      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);
 -                      }
 -                      draw_object(scene, 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;
 +      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];
  
 -              v3d->xray = true;
 -              
 -              /* transp materials can change the depth mask, see #21388 */
 -              glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
 +      double dx = fabs(x - wx * fx / fw);
 +      if (dx == 0) dx = fabs(y - wy * fy / fw);
  
 +      x += wx;
 +      y += wy;
  
 -              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 */
 -              }
 +      /* 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 */
  
 -              /* 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);
 -              }
 +      glLineWidth(1.0f);
  
 -              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);
 -              }
 +#if 0 /* TODO: write to UI/widget depth buffer, not scene depth */
 +      glDepthMask(GL_FALSE);  /* disable write in zbuffer */
 +#endif
  
 -              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);
 -              }
 +      Gwn_VertFormat *format = immVertexFormat();
 +      unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
 +      unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
  
 -              
 -              v3d->xray = false;
 -              v3d->transp = false;
 +      immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
  
 -              glDepthMask(mask_orig);
 -      }
 -}
 +      unsigned char col[3], col2[3];
 +      UI_GetThemeColor3ubv(TH_GRID, col);
  
 -void ED_view3d_draw_depth(Scene *scene, ARegion *ar, View3D *v3d, bool alphaoverride)
 -{
 -      struct bThemeState theme_state;
 -      RegionView3D *rv3d = ar->regiondata;
 -      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;
 -      
 -      /* Tools may request depth outside of regular drawing code. */
 -      UI_Theme_Store(&theme_state);
 -      UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
 +      if (unit->system) {
 +              const void *usys;
 +              int len;
  
 -      /* Setup view matrix. */
 -      ED_view3d_draw_setup_view(NULL, scene, ar, v3d, rv3d->viewmat, rv3d->winmat, NULL);
 -      
 -      glClear(GL_DEPTH_BUFFER_BIT);
 -      
 -      if (rv3d->rflag & RV3D_CLIPPING) {
 -              ED_view3d_clipping_set(rv3d);
 -      }
 -      /* get surface depth without bias */
 -      rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
 +              bUnit_GetSystem(unit->system, B_UNIT_LENGTH, &usys, &len);
 +
 +              bool first = true;
 +
 +              if (usys) {
 +                      int i = len;
 +                      while (i--) {
 +                              double scalar = bUnit_GetScaler(usys, i);
  
 -      v3d->zbuf = true;
 -      glEnable(GL_DEPTH_TEST);
 +                              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;
 +                              }
  
 -      view3d_draw_depth_loop(scene, ar, v3d);
 +                              if (first) {
 +                                      first = false;
  
 -      if (rv3d->rflag & RV3D_CLIPPING) {
 -              ED_view3d_clipping_disable();
 -      }
 -      rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
 -      
 -      v3d->zbuf = zbuf;
 -      if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
 +                                      /* 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);
  
 -      U.glalphaclip = glalphaclip;
 -      v3d->flag = flag;
 -      U.obcenter_dia = obcenter_dia;
 +                                      int gridline_ct = gridline_count(ar, x, y, dx_scalar);
 +                                      if (gridline_ct == 0)
 +                                              goto drawgrid_cleanup; /* nothing to draw */
  
 -      UI_Theme_Restore(&theme_state);
 -}
 +                                      immBegin(GWN_PRIM_LINES, gridline_ct * 2);
 +                              }
  
 -void ED_view3d_draw_select_loop(
 -        ViewContext *vc, Scene *scene, View3D *v3d, ARegion *ar,
 -        bool use_obedit_skip, bool use_nearest)
 -{
 -      short code = 1;
 -      const short dflag = DRAW_PICKING | DRAW_CONSTCOLOR;
 +                              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 (vc->obedit && vc->obedit->type == OB_MBALL) {
 -              draw_object(scene, ar, v3d, BASACT, dflag);
 -      }
 -      else if ((vc->obedit && vc->obedit->type == OB_ARMATURE)) {
 -              /* if not drawing sketch, draw bones */
 -              if (!BDR_drawSketchNames(vc)) {
 -                      draw_object(scene, ar, v3d, BASACT, dflag);
 +                              UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, blend_fac, col2);
 +
 +                              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 {
index 244f833e6b3027d1386dae9b9d953cafdb19c1c4,7e7314cc0c8a9e1183ce47dd5c5707fa6a326683..f3864f7ed975f757468a55181e71a9825ef87a42
@@@ -264,6 -263,50 +264,55 @@@ static void wm_notifier_clear(wmNotifie
        memset(((char *)note) + sizeof(Link), 0, sizeof(*note) - sizeof(Link));
  }
  
 -              win_combine_v3d_datamask |= ED_view3d_screen_datamask(win->screen);
+ /**
+  * Was part of #wm_event_do_notifiers, split out so it can be called once before entering the #WM_main loop.
+  * This ensures operators don't run before the UI and depsgraph are initialized.
+  */
+ void wm_event_do_refresh_wm_and_depsgraph(bContext *C)
+ {
+       wmWindowManager *wm = CTX_wm_manager(C);
+       uint64_t win_combine_v3d_datamask = 0;
+       /* combine datamasks so 1 win doesn't disable UV's in another [#26448] */
+       for (wmWindow *win = wm->windows.first; win; win = win->next) {
 -              for (sa = win->screen->areabase.first; sa; sa = sa->next) {
++              const Scene *scene = WM_window_get_active_scene(win);
++              const bScreen *screen = WM_window_get_active_screen(win);
++
++              win_combine_v3d_datamask |= ED_view3d_screen_datamask(scene, screen);
+       }
+       /* cached: editor refresh callbacks now, they get context */
+       for (wmWindow *win = wm->windows.first; win; win = win->next) {
++              const bScreen *screen = WM_window_get_active_screen(win);
++              Scene *scene = WM_window_get_active_scene(win);
+               ScrArea *sa;
+               CTX_wm_window_set(C, win);
 -                      win->screen->scene->customdata_mask = win_combine_v3d_datamask;
++              for (sa = screen->areabase.first; sa; sa = sa->next) {
+                       if (sa->do_refresh) {
+                               CTX_wm_area_set(C, sa);
+                               ED_area_do_refresh(C, sa);
+                       }
+               }
+               /* XXX make lock in future, or separated derivedmesh users in scene */
+               if (G.is_rendering == false) {
+                       /* depsgraph & animation: update tagged datablocks */
+                       Main *bmain = CTX_data_main(C);
+                       /* copied to set's in scene_update_tagged_recursive() */
 -                      win->screen->scene->customdata_mask |= win->screen->scene->customdata_mask_modal;
++                      scene->customdata_mask = win_combine_v3d_datamask;
+                       /* XXX, hack so operators can enforce datamasks [#26482], gl render */
 -                      BKE_scene_update_tagged(bmain->eval_ctx, bmain, win->screen->scene);
++                      scene->customdata_mask |= scene->customdata_mask_modal;
++                      BKE_scene_update_tagged(bmain->eval_ctx, bmain, scene);
+               }
+       }
+       CTX_wm_window_set(C, NULL);
+ }
  /* called in mainloop */
  void wm_event_do_notifiers(bContext *C)
  {
                
                MEM_freeN(note);
        }
 -      
 +
-       /* combine datamasks so 1 win doesn't disable UV's in another [#26448] */
-       for (win = wm->windows.first; win; win = win->next) {
-               const Scene *scene = WM_window_get_active_scene(win);
-               const bScreen *screen = WM_window_get_active_screen(win);
-               win_combine_v3d_datamask |= ED_view3d_screen_datamask(scene, screen);
-       }
-       /* cached: editor refresh callbacks now, they get context */
-       for (win = wm->windows.first; win; win = win->next) {
-               const bScreen *screen = WM_window_get_active_screen(win);
-               Scene *scene = WM_window_get_active_scene(win);
-               ScrArea *sa;
-               
-               CTX_wm_window_set(C, win);
-               for (sa = screen->areabase.first; sa; sa = sa->next) {
-                       if (sa->do_refresh) {
-                               CTX_wm_area_set(C, sa);
-                               ED_area_do_refresh(C, sa);
-                       }
-               }
-               
-               /* XXX make lock in future, or separated derivedmesh users in scene */
-               if (G.is_rendering == false) {
-                       /* depsgraph & animation: update tagged datablocks */
-                       Main *bmain = CTX_data_main(C);
-                       /* copied to set's in scene_update_tagged_recursive() */
-                       scene->customdata_mask = win_combine_v3d_datamask;
-                       /* XXX, hack so operators can enforce datamasks [#26482], gl render */
-                       scene->customdata_mask |= scene->customdata_mask_modal;
-                       BKE_scene_update_tagged(bmain->eval_ctx, bmain, scene);
-               }
-       }
-       CTX_wm_window_set(C, NULL);
+       wm_event_do_refresh_wm_and_depsgraph(C);
  }
  
  static int wm_event_always_pass(const wmEvent *event)