Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / space_view3d / view3d_draw_legacy.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/space_view3d/view3d_draw_legacy.c
28  *  \ingroup spview3d
29  */
30
31 #include <string.h>
32 #include <stdio.h>
33 #include <math.h>
34
35 #include "DNA_armature_types.h"
36 #include "DNA_camera_types.h"
37 #include "DNA_customdata_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_group_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_key_types.h"
42 #include "DNA_lamp_types.h"
43 #include "DNA_scene_types.h"
44 #include "DNA_world_types.h"
45 #include "DNA_brush_types.h"
46
47 #include "MEM_guardedalloc.h"
48
49 #include "BLI_blenlib.h"
50 #include "BLI_math.h"
51 #include "BLI_jitter.h"
52 #include "BLI_utildefines.h"
53 #include "BLI_endian_switch.h"
54 #include "BLI_threads.h"
55
56 #include "BKE_anim.h"
57 #include "BKE_camera.h"
58 #include "BKE_context.h"
59 #include "BKE_customdata.h"
60 #include "BKE_DerivedMesh.h"
61 #include "BKE_image.h"
62 #include "BKE_key.h"
63 #include "BKE_layer.h"
64 #include "BKE_main.h"
65 #include "BKE_object.h"
66 #include "BKE_global.h"
67 #include "BKE_paint.h"
68 #include "BKE_scene.h"
69 #include "BKE_screen.h"
70 #include "BKE_unit.h"
71 #include "BKE_movieclip.h"
72
73 #include "DEG_depsgraph.h"
74
75 #include "RE_engine.h"
76
77 #include "IMB_imbuf_types.h"
78 #include "IMB_imbuf.h"
79 #include "IMB_colormanagement.h"
80
81 #include "BIF_glutil.h"
82
83 #include "WM_api.h"
84 #include "WM_types.h"
85
86 #include "BLF_api.h"
87 #include "BLT_translation.h"
88
89 #include "ED_armature.h"
90 #include "ED_keyframing.h"
91 #include "ED_gpencil.h"
92 #include "ED_screen.h"
93 #include "ED_space_api.h"
94 #include "ED_screen_types.h"
95 #include "ED_transform.h"
96
97 #include "UI_interface.h"
98 #include "UI_interface_icons.h"
99 #include "UI_resources.h"
100
101 #include "GPU_draw.h"
102 #include "GPU_framebuffer.h"
103 #include "GPU_lamp.h"
104 #include "GPU_material.h"
105 #include "GPU_compositing.h"
106 #include "GPU_extensions.h"
107 #include "GPU_immediate.h"
108 #include "GPU_immediate_util.h"
109 #include "GPU_select.h"
110 #include "GPU_matrix.h"
111
112 #include "RE_engine.h"
113
114 #include "DRW_engine.h"
115
116 #include "view3d_intern.h"  /* own include */
117
118 /* ********* custom clipping *********** */
119
120 static void view3d_draw_clipping(RegionView3D *rv3d)
121 {
122         BoundBox *bb = rv3d->clipbb;
123
124         if (bb) {
125                 const unsigned int clipping_index[6][4] = {
126                         {0, 1, 2, 3},
127                         {0, 4, 5, 1},
128                         {4, 7, 6, 5},
129                         {7, 3, 2, 6},
130                         {1, 5, 6, 2},
131                         {7, 4, 0, 3}
132                 };
133
134                 /* fill in zero alpha for rendering & re-projection [#31530] */
135                 unsigned char col[4];
136                 UI_GetThemeColor4ubv(TH_V3D_CLIPPING_BORDER, col);
137                 glColor4ubv(col);
138
139                 glEnable(GL_BLEND);
140                 glEnableClientState(GL_VERTEX_ARRAY);
141                 glVertexPointer(3, GL_FLOAT, 0, bb->vec);
142                 glDrawElements(GL_QUADS, sizeof(clipping_index) / sizeof(unsigned int), GL_UNSIGNED_INT, clipping_index);
143                 glDisableClientState(GL_VERTEX_ARRAY);
144                 glDisable(GL_BLEND);
145         }
146 }
147
148 void ED_view3d_clipping_set(RegionView3D *rv3d)
149 {
150         double plane[4];
151         const unsigned int tot = (rv3d->viewlock & RV3D_BOXCLIP) ? 4 : 6;
152
153         for (unsigned a = 0; a < tot; a++) {
154                 copy_v4db_v4fl(plane, rv3d->clip[a]);
155                 glClipPlane(GL_CLIP_PLANE0 + a, plane);
156                 glEnable(GL_CLIP_PLANE0 + a);
157         }
158 }
159
160 /* use these to temp disable/enable clipping when 'rv3d->rflag & RV3D_CLIPPING' is set */
161 void ED_view3d_clipping_disable(void)
162 {
163         for (unsigned a = 0; a < 6; a++) {
164                 glDisable(GL_CLIP_PLANE0 + a);
165         }
166 }
167 void ED_view3d_clipping_enable(void)
168 {
169         for (unsigned a = 0; a < 6; a++) {
170                 glEnable(GL_CLIP_PLANE0 + a);
171         }
172 }
173
174 static bool view3d_clipping_test(const float co[3], const float clip[6][4])
175 {
176         if (plane_point_side_v3(clip[0], co) > 0.0f)
177                 if (plane_point_side_v3(clip[1], co) > 0.0f)
178                         if (plane_point_side_v3(clip[2], co) > 0.0f)
179                                 if (plane_point_side_v3(clip[3], co) > 0.0f)
180                                         return false;
181
182         return true;
183 }
184
185 /* for 'local' ED_view3d_clipping_local must run first
186  * then all comparisons can be done in localspace */
187 bool ED_view3d_clipping_test(const RegionView3D *rv3d, const float co[3], const bool is_local)
188 {
189         return view3d_clipping_test(co, is_local ? rv3d->clip_local : rv3d->clip);
190 }
191
192 /* ********* end custom clipping *********** */
193
194 static void draw_view_icon(RegionView3D *rv3d, rcti *rect)
195 {
196         BIFIconID icon;
197         
198         if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM))
199                 icon = ICON_AXIS_TOP;
200         else if (ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK))
201                 icon = ICON_AXIS_FRONT;
202         else if (ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT))
203                 icon = ICON_AXIS_SIDE;
204         else return;
205         
206         glEnable(GL_BLEND);
207         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
208         
209         UI_icon_draw(5.0 + rect->xmin, 5.0 + rect->ymin, icon);
210         
211         glDisable(GL_BLEND);
212 }
213
214 /* *********************** backdraw for selection *************** */
215
216 static void backdrawview3d(const struct EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, wmWindow *win, ARegion *ar, View3D *v3d)
217 {
218         RegionView3D *rv3d = ar->regiondata;
219         struct Base *base = sl->basact;
220         int multisample_enabled;
221
222         BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
223
224         if (base && (base->object->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
225                      BKE_paint_select_face_test(base->object)))
226         {
227                 /* do nothing */
228         }
229         /* texture paint mode sampling */
230         else if (base && (base->object->mode & OB_MODE_TEXTURE_PAINT) &&
231                  (v3d->drawtype > OB_WIRE))
232         {
233                 /* do nothing */
234         }
235         else if ((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) &&
236                  V3D_IS_ZBUF(v3d))
237         {
238                 /* do nothing */
239         }
240         else if (scene->obedit &&
241                  V3D_IS_ZBUF(v3d))
242         {
243                 /* do nothing */
244         }
245         else {
246                 v3d->flag &= ~V3D_INVALID_BACKBUF;
247                 return;
248         }
249
250         if (!(v3d->flag & V3D_INVALID_BACKBUF))
251                 return;
252
253 #if 0
254         if (test) {
255                 if (qtest()) {
256                         addafterqueue(ar->win, BACKBUFDRAW, 1);
257                         return;
258                 }
259         }
260 #endif
261
262         if (v3d->drawtype > OB_WIRE) v3d->zbuf = true;
263         
264         /* dithering and AA break color coding, so disable */
265         glDisable(GL_DITHER);
266
267         multisample_enabled = glIsEnabled(GL_MULTISAMPLE);
268         if (multisample_enabled)
269                 glDisable(GL_MULTISAMPLE);
270
271         if (win->multisamples != USER_MULTISAMPLE_NONE) {
272                 /* for multisample we use an offscreen FBO. multisample drawing can fail
273                  * with color coded selection drawing, and reading back depths from such
274                  * a buffer can also cause a few seconds freeze on OS X / NVidia. */
275                 int w = BLI_rcti_size_x(&ar->winrct);
276                 int h = BLI_rcti_size_y(&ar->winrct);
277                 char error[256];
278
279                 if (rv3d->gpuoffscreen) {
280                         if (GPU_offscreen_width(rv3d->gpuoffscreen)  != w ||
281                             GPU_offscreen_height(rv3d->gpuoffscreen) != h)
282                         {
283                                 GPU_offscreen_free(rv3d->gpuoffscreen);
284                                 rv3d->gpuoffscreen = NULL;
285                         }
286                 }
287
288                 if (!rv3d->gpuoffscreen) {
289                         rv3d->gpuoffscreen = GPU_offscreen_create(w, h, 0, error);
290
291                         if (!rv3d->gpuoffscreen)
292                                 fprintf(stderr, "Failed to create offscreen selection buffer for multisample: %s\n", error);
293                 }
294         }
295
296         if (rv3d->gpuoffscreen)
297                 GPU_offscreen_bind(rv3d->gpuoffscreen, true);
298         else
299                 glScissor(ar->winrct.xmin, ar->winrct.ymin, BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
300
301         glClearColor(0.0, 0.0, 0.0, 0.0);
302         if (v3d->zbuf) {
303                 glEnable(GL_DEPTH_TEST);
304                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
305         }
306         else {
307                 glClear(GL_COLOR_BUFFER_BIT);
308                 glDisable(GL_DEPTH_TEST);
309         }
310         
311         if (rv3d->rflag & RV3D_CLIPPING)
312                 ED_view3d_clipping_set(rv3d);
313         
314         G.f |= G_BACKBUFSEL;
315         
316         if (base && ((base->flag & BASE_VISIBLED) != 0))
317                 draw_object_backbufsel(eval_ctx, scene, v3d, rv3d, base->object);
318         
319         if (rv3d->gpuoffscreen)
320                 GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
321         else
322                 ar->swap = 0; /* mark invalid backbuf for wm draw */
323
324         v3d->flag &= ~V3D_INVALID_BACKBUF;
325
326         G.f &= ~G_BACKBUFSEL;
327         v3d->zbuf = false;
328         glDisable(GL_DEPTH_TEST);
329         glEnable(GL_DITHER);
330         if (multisample_enabled)
331                 glEnable(GL_MULTISAMPLE);
332
333         if (rv3d->rflag & RV3D_CLIPPING)
334                 ED_view3d_clipping_disable();
335 }
336
337 void view3d_opengl_read_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
338 {
339         RegionView3D *rv3d = ar->regiondata;
340
341         if (rv3d->gpuoffscreen) {
342                 GPU_offscreen_bind(rv3d->gpuoffscreen, true);
343                 glReadBuffer(GL_COLOR_ATTACHMENT0);
344                 glReadPixels(x, y, w, h, format, type, data);
345                 GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
346         }
347         else {
348                 glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
349         }
350 }
351
352 /* XXX depth reading exception, for code not using gpu offscreen */
353 static void view3d_opengl_read_Z_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
354 {
355         glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
356 }
357
358 void ED_view3d_backbuf_validate(const struct EvaluationContext *eval_ctx, ViewContext *vc)
359 {
360         if (vc->v3d->flag & V3D_INVALID_BACKBUF) {
361                 backdrawview3d(eval_ctx, vc->scene, vc->scene_layer, vc->win, vc->ar, vc->v3d);
362         }
363 }
364
365 /**
366  * allow for small values [0.5 - 2.5],
367  * and large values, FLT_MAX by clamping by the area size
368  */
369 int ED_view3d_backbuf_sample_size_clamp(ARegion *ar, const float dist)
370 {
371         return (int)min_ff(ceilf(dist), (float)max_ii(ar->winx, ar->winx));
372 }
373
374 /* samples a single pixel (copied from vpaint) */
375 unsigned int ED_view3d_backbuf_sample(
376         const EvaluationContext *eval_ctx, ViewContext *vc, int x, int y)
377 {
378         if (x >= vc->ar->winx || y >= vc->ar->winy) {
379                 return 0;
380         }
381
382         ED_view3d_backbuf_validate(eval_ctx, vc);
383
384         unsigned int col;
385         view3d_opengl_read_pixels(vc->ar, x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &col);
386         glReadBuffer(GL_BACK);
387
388         if (ENDIAN_ORDER == B_ENDIAN) {
389                 BLI_endian_switch_uint32(&col);
390         }
391
392         return GPU_select_to_index(col);
393 }
394
395 /* reads full rect, converts indices */
396 ImBuf *ED_view3d_backbuf_read(
397         const EvaluationContext *eval_ctx, ViewContext *vc, int xmin, int ymin, int xmax, int ymax)
398 {
399         /* clip */
400         const rcti clip = {
401             max_ii(xmin, 0), min_ii(xmax, vc->ar->winx - 1),
402             max_ii(ymin, 0), min_ii(ymax, vc->ar->winy - 1)};
403         const int size_clip[2] = {
404             BLI_rcti_size_x(&clip) + 1,
405             BLI_rcti_size_y(&clip) + 1};
406
407         if (UNLIKELY((clip.xmin > clip.xmax) ||
408                      (clip.ymin > clip.ymax)))
409         {
410                 return NULL;
411         }
412
413         ImBuf *ibuf_clip = IMB_allocImBuf(size_clip[0], size_clip[1], 32, IB_rect);
414
415         ED_view3d_backbuf_validate(eval_ctx, vc);
416
417         view3d_opengl_read_pixels(vc->ar, clip.xmin, clip.ymin, size_clip[0], size_clip[1], GL_RGBA, GL_UNSIGNED_BYTE, ibuf_clip->rect);
418
419         glReadBuffer(GL_BACK);
420
421         if (ENDIAN_ORDER == B_ENDIAN) {
422                 IMB_convert_rgba_to_abgr(ibuf_clip);
423         }
424
425         GPU_select_to_index_array(ibuf_clip->rect, size_clip[0] * size_clip[1]);
426         
427         if ((clip.xmin == xmin) &&
428             (clip.xmax == xmax) &&
429             (clip.ymin == ymin) &&
430             (clip.ymax == ymax))
431         {
432                 return ibuf_clip;
433         }
434         else {
435                 /* put clipped result into a non-clipped buffer */
436                 const int size[2] = {
437                     (xmax - xmin + 1),
438                     (ymax - ymin + 1)};
439
440                 ImBuf *ibuf_full = IMB_allocImBuf(size[0], size[1], 32, IB_rect);
441
442                 IMB_rectcpy(
443                         ibuf_full, ibuf_clip,
444                         clip.xmin - xmin, clip.ymin - ymin,
445                         0, 0,
446                         size_clip[0], size_clip[1]);
447                 IMB_freeImBuf(ibuf_clip);
448                 return ibuf_full;
449         }
450 }
451
452 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
453 unsigned int ED_view3d_backbuf_sample_rect(
454         const EvaluationContext *eval_ctx, ViewContext *vc, const int mval[2], int size,
455         unsigned int min, unsigned int max, float *r_dist)
456 {
457         int dirvec[4][2];
458
459         const int amount = (size - 1) / 2;
460
461         const int minx = mval[0] - (amount + 1);
462         const int miny = mval[1] - (amount + 1);
463         ImBuf *buf = ED_view3d_backbuf_read(eval_ctx, vc, minx, miny, minx + size - 1, miny + size - 1);
464         if (!buf) return 0;
465
466         unsigned index = 0;
467         int rc = 0;
468         
469         dirvec[0][0] = 1; dirvec[0][1] = 0;
470         dirvec[1][0] = 0; dirvec[1][1] = -size;
471         dirvec[2][0] = -1; dirvec[2][1] = 0;
472         dirvec[3][0] = 0; dirvec[3][1] = size;
473         
474         const unsigned *bufmin = buf->rect;
475         const unsigned *tbuf = buf->rect;
476         const unsigned *bufmax = buf->rect + size * size;
477         tbuf += amount * size + amount;
478         
479         for (int nr = 1; nr <= size; nr++) {
480                 for (int a = 0; a < 2; a++) {
481                         for (int b = 0; b < nr; b++) {
482                                 if (*tbuf && *tbuf >= min && *tbuf < max) {
483                                         /* we got a hit */
484
485                                         /* get x,y pixel coords from the offset
486                                          * (manhatten distance in keeping with other screen-based selection) */
487                                         *r_dist = (float)(
488                                                 abs(((int)(tbuf - buf->rect) % size) - (size / 2)) +
489                                                 abs(((int)(tbuf - buf->rect) / size) - (size / 2)));
490
491                                         /* indices start at 1 here */
492                                         index = (*tbuf - min) + 1;
493                                         goto exit;
494                                 }
495                                 
496                                 tbuf += (dirvec[rc][0] + dirvec[rc][1]);
497                                 
498                                 if (tbuf < bufmin || tbuf >= bufmax) {
499                                         goto exit;
500                                 }
501                         }
502                         rc++;
503                         rc &= 3;
504                 }
505         }
506
507 exit:
508         IMB_freeImBuf(buf);
509         return index;
510 }
511
512
513 /* ************************************************************* */
514
515 static void view3d_stereo_bgpic_setup(Scene *scene, View3D *v3d, Image *ima, ImageUser *iuser)
516 {
517         if (BKE_image_is_stereo(ima)) {
518                 iuser->flag |= IMA_SHOW_STEREO;
519
520                 if ((scene->r.scemode & R_MULTIVIEW) == 0) {
521                         iuser->multiview_eye = STEREO_LEFT_ID;
522                 }
523                 else if (v3d->stereo3d_camera != STEREO_3D_ID) {
524                         /* show only left or right camera */
525                         iuser->multiview_eye = v3d->stereo3d_camera;
526                 }
527
528                 BKE_image_multiview_index(ima, iuser);
529         }
530         else {
531                 iuser->flag &= ~IMA_SHOW_STEREO;
532         }
533 }
534
535 static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
536                               const bool do_foreground, const bool do_camera_frame)
537 {
538         RegionView3D *rv3d = ar->regiondata;
539         int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
540
541         for (BGpic *bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
542                 bgpic->iuser.scene = scene;  /* Needed for render results. */
543
544                 if ((bgpic->flag & V3D_BGPIC_FOREGROUND) != fg_flag)
545                         continue;
546
547                 if ((bgpic->view == 0) || /* zero for any */
548                     (bgpic->view & (1 << rv3d->view)) || /* check agaist flags */
549                     (rv3d->persp == RV3D_CAMOB && bgpic->view == (1 << RV3D_VIEW_CAMERA)))
550                 {
551                         float image_aspect[2];
552                         float x1, y1, x2, y2, centx, centy;
553
554                         void *lock;
555
556                         Image *ima = NULL;
557
558                         /* disable individual images */
559                         if ((bgpic->flag & V3D_BGPIC_DISABLED))
560                                 continue;
561
562                         ImBuf *ibuf = NULL;
563                         ImBuf *freeibuf = NULL;
564                         ImBuf *releaseibuf = NULL;
565                         if (bgpic->source == V3D_BGPIC_IMAGE) {
566                                 ima = bgpic->ima;
567                                 if (ima == NULL)
568                                         continue;
569                                 BKE_image_user_frame_calc(&bgpic->iuser, CFRA, 0);
570                                 if (ima->source == IMA_SRC_SEQUENCE && !(bgpic->iuser.flag & IMA_USER_FRAME_IN_RANGE)) {
571                                         ibuf = NULL; /* frame is out of range, dont show */
572                                 }
573                                 else {
574                                         view3d_stereo_bgpic_setup(scene, v3d, ima, &bgpic->iuser);
575                                         ibuf = BKE_image_acquire_ibuf(ima, &bgpic->iuser, &lock);
576                                         releaseibuf = ibuf;
577                                 }
578
579                                 image_aspect[0] = ima->aspx;
580                                 image_aspect[1] = ima->aspy;
581                         }
582                         else if (bgpic->source == V3D_BGPIC_MOVIE) {
583                                 /* TODO: skip drawing when out of frame range (as image sequences do above) */
584                                 MovieClip *clip = NULL;
585
586                                 if (bgpic->flag & V3D_BGPIC_CAMERACLIP) {
587                                         if (scene->camera)
588                                                 clip = BKE_object_movieclip_get(scene, scene->camera, true);
589                                 }
590                                 else {
591                                         clip = bgpic->clip;
592                                 }
593
594                                 if (clip == NULL)
595                                         continue;
596
597                                 BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
598                                 ibuf = BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
599
600                                 image_aspect[0] = clip->aspx;
601                                 image_aspect[1] = clip->aspy;
602
603                                 /* working with ibuf from image and clip has got different workflow now.
604                                  * ibuf acquired from clip is referenced by cache system and should
605                                  * be dereferenced after usage. */
606                                 freeibuf = ibuf;
607                         }
608                         else {
609                                 /* perhaps when loading future files... */
610                                 BLI_assert(0);
611                                 copy_v2_fl(image_aspect, 1.0f);
612                         }
613
614                         if (ibuf == NULL)
615                                 continue;
616
617                         if ((ibuf->rect == NULL && ibuf->rect_float == NULL) || ibuf->channels != 4) { /* invalid image format */
618                                 if (freeibuf)
619                                         IMB_freeImBuf(freeibuf);
620                                 if (releaseibuf)
621                                         BKE_image_release_ibuf(ima, releaseibuf, lock);
622
623                                 continue;
624                         }
625
626                         if (ibuf->rect == NULL)
627                                 IMB_rect_from_float(ibuf);
628
629                         if (rv3d->persp == RV3D_CAMOB) {
630
631                                 if (do_camera_frame) {
632                                         rctf vb;
633                                         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, false);
634                                         x1 = vb.xmin;
635                                         y1 = vb.ymin;
636                                         x2 = vb.xmax;
637                                         y2 = vb.ymax;
638                                 }
639                                 else {
640                                         x1 = ar->winrct.xmin;
641                                         y1 = ar->winrct.ymin;
642                                         x2 = ar->winrct.xmax;
643                                         y2 = ar->winrct.ymax;
644                                 }
645
646                                 /* apply offset last - camera offset is different to offset in blender units */
647                                 /* so this has some sane way of working - this matches camera's shift _exactly_ */
648                                 {
649                                         const float max_dim = max_ff(x2 - x1, y2 - y1);
650                                         const float xof_scale = bgpic->xof * max_dim;
651                                         const float yof_scale = bgpic->yof * max_dim;
652
653                                         x1 += xof_scale;
654                                         y1 += yof_scale;
655                                         x2 += xof_scale;
656                                         y2 += yof_scale;
657                                 }
658
659                                 centx = (x1 + x2) * 0.5f;
660                                 centy = (y1 + y2) * 0.5f;
661
662                                 /* aspect correction */
663                                 if (bgpic->flag & V3D_BGPIC_CAMERA_ASPECT) {
664                                         /* apply aspect from clip */
665                                         const float w_src = ibuf->x * image_aspect[0];
666                                         const float h_src = ibuf->y * image_aspect[1];
667
668                                         /* destination aspect is already applied from the camera frame */
669                                         const float w_dst = x1 - x2;
670                                         const float h_dst = y1 - y2;
671
672                                         const float asp_src = w_src / h_src;
673                                         const float asp_dst = w_dst / h_dst;
674
675                                         if (fabsf(asp_src - asp_dst) >= FLT_EPSILON) {
676                                                 if ((asp_src > asp_dst) == ((bgpic->flag & V3D_BGPIC_CAMERA_CROP) != 0)) {
677                                                         /* fit X */
678                                                         const float div = asp_src / asp_dst;
679                                                         x1 = ((x1 - centx) * div) + centx;
680                                                         x2 = ((x2 - centx) * div) + centx;
681                                                 }
682                                                 else {
683                                                         /* fit Y */
684                                                         const float div = asp_dst / asp_src;
685                                                         y1 = ((y1 - centy) * div) + centy;
686                                                         y2 = ((y2 - centy) * div) + centy;
687                                                 }
688                                         }
689                                 }
690                         }
691                         else {
692                                 float tvec[3];
693                                 float sco[2];
694                                 const float mval_f[2] = {1.0f, 0.0f};
695                                 const float co_zero[3] = {0};
696
697                                 /* calc window coord */
698                                 float zfac = ED_view3d_calc_zfac(rv3d, co_zero, NULL);
699                                 ED_view3d_win_to_delta(ar, mval_f, tvec, zfac);
700                                 float fac = 1.0f / max_ff(fabsf(tvec[0]), max_ff(fabsf(tvec[1]), fabsf(tvec[2]))); /* largest abs axis */
701                                 float asp = (float)ibuf->y / (float)ibuf->x;
702
703                                 zero_v3(tvec);
704                                 ED_view3d_project_float_v2_m4(ar, tvec, sco, rv3d->persmat);
705
706                                 x1 =  sco[0] + fac * (bgpic->xof - bgpic->size);
707                                 y1 =  sco[1] + asp * fac * (bgpic->yof - bgpic->size);
708                                 x2 =  sco[0] + fac * (bgpic->xof + bgpic->size);
709                                 y2 =  sco[1] + asp * fac * (bgpic->yof + bgpic->size);
710
711                                 centx = (x1 + x2) / 2.0f;
712                                 centy = (y1 + y2) / 2.0f;
713                         }
714
715                         /* complete clip? */
716                         rctf clip_rect;
717                         BLI_rctf_init(&clip_rect, x1, x2, y1, y2);
718                         if (bgpic->rotation) {
719                                 BLI_rctf_rotate_expand(&clip_rect, &clip_rect, bgpic->rotation);
720                         }
721
722                         if (clip_rect.xmax < 0 || clip_rect.ymax < 0 || clip_rect.xmin > ar->winx || clip_rect.ymin > ar->winy) {
723                                 if (freeibuf)
724                                         IMB_freeImBuf(freeibuf);
725                                 if (releaseibuf)
726                                         BKE_image_release_ibuf(ima, releaseibuf, lock);
727
728                                 continue;
729                         }
730
731                         float zoomx = (x2 - x1) / ibuf->x;
732                         float zoomy = (y2 - y1) / ibuf->y;
733
734                         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
735                         if (zoomx < 1.0f || zoomy < 1.0f) {
736                                 float tzoom = min_ff(zoomx, zoomy);
737                                 int mip = 0;
738
739                                 if ((ibuf->userflags & IB_MIPMAP_INVALID) != 0) {
740                                         IMB_remakemipmap(ibuf, 0);
741                                         ibuf->userflags &= ~IB_MIPMAP_INVALID;
742                                 }
743                                 else if (ibuf->mipmap[0] == NULL)
744                                         IMB_makemipmap(ibuf, 0);
745
746                                 while (tzoom < 1.0f && mip < 8 && ibuf->mipmap[mip]) {
747                                         tzoom *= 2.0f;
748                                         zoomx *= 2.0f;
749                                         zoomy *= 2.0f;
750                                         mip++;
751                                 }
752                                 if (mip > 0)
753                                         ibuf = ibuf->mipmap[mip - 1];
754                         }
755
756                         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
757                         glDepthMask(GL_FALSE);
758
759                         glEnable(GL_BLEND);
760                         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
761
762                         gpuPushProjectionMatrix();
763                         gpuPushMatrix();
764                         ED_region_pixelspace(ar);
765
766                         gpuTranslate2f(centx, centy);
767                         gpuRotate2D(RAD2DEGF(-bgpic->rotation));
768
769                         if (bgpic->flag & V3D_BGPIC_FLIP_X) {
770                                 zoomx *= -1.0f;
771                                 x1 = x2;
772                         }
773                         if (bgpic->flag & V3D_BGPIC_FLIP_Y) {
774                                 zoomy *= -1.0f;
775                                 y1 = y2;
776                         }
777
778                         float col[4] = {1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend};
779                         IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR);
780                         immDrawPixelsTex(&state, x1 - centx, y1 - centy, ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR, ibuf->rect,
781                                          zoomx, zoomy, col);
782
783                         gpuPopProjectionMatrix();
784                         gpuPopMatrix();
785
786                         glDisable(GL_BLEND);
787
788                         glDepthMask(GL_TRUE);
789                         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
790
791                         if (freeibuf)
792                                 IMB_freeImBuf(freeibuf);
793                         if (releaseibuf)
794                                 BKE_image_release_ibuf(ima, releaseibuf, lock);
795                 }
796         }
797 }
798
799 static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
800                                    const bool do_foreground, const bool do_camera_frame)
801 {
802         RegionView3D *rv3d = ar->regiondata;
803
804         if ((v3d->flag & V3D_DISPBGPICS) == 0)
805                 return;
806
807         /* disabled - mango request, since footage /w only render is quite useful
808          * and this option is easy to disable all background images at once */
809 #if 0
810         if (v3d->flag2 & V3D_RENDER_OVERRIDE)
811                 return;
812 #endif
813
814         if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
815                 if (rv3d->persp == RV3D_CAMOB) {
816                         view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
817                 }
818         }
819         else {
820                 view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
821         }
822 }
823
824 /* ****************** View3d afterdraw *************** */
825
826 typedef struct View3DAfter {
827         struct View3DAfter *next, *prev;
828         struct BaseLegacy *base;
829         short dflag;
830 } View3DAfter;
831
832 /* temp storage of Objects that need to be drawn as last */
833 void ED_view3d_after_add(ListBase *lb, BaseLegacy *base, const short dflag)
834 {
835         View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
836         BLI_assert((base->flag_legacy & OB_FROMDUPLI) == 0);
837         BLI_addtail(lb, v3da);
838         v3da->base = base;
839         v3da->dflag = dflag;
840 }
841
842 /* disables write in zbuffer and draws it over */
843 static void view3d_draw_transp(
844         const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d)
845 {
846         View3DAfter *v3da;
847         
848         glDepthMask(GL_FALSE);
849         v3d->transp = true;
850         
851         while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
852                 draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, v3da->dflag);
853                 MEM_freeN(v3da);
854         }
855         v3d->transp = false;
856         
857         glDepthMask(GL_TRUE);
858         
859 }
860
861 /* clears zbuffer and draws it over */
862 static void view3d_draw_xray(
863         const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, bool *clear)
864 {
865         if (*clear && v3d->zbuf) {
866                 glClear(GL_DEPTH_BUFFER_BIT);
867                 *clear = false;
868         }
869
870         v3d->xray = true;
871         View3DAfter *v3da;
872         while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
873                 draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, v3da->dflag);
874                 MEM_freeN(v3da);
875         }
876         v3d->xray = false;
877 }
878
879
880 /* clears zbuffer and draws it over */
881 static void view3d_draw_xraytransp(
882         const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, const bool clear)
883 {
884         if (clear && v3d->zbuf)
885                 glClear(GL_DEPTH_BUFFER_BIT);
886
887         v3d->xray = true;
888         v3d->transp = true;
889         
890         glDepthMask(GL_FALSE);
891
892         View3DAfter *v3da;
893         while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
894                 draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, v3da->dflag);
895                 MEM_freeN(v3da);
896         }
897
898         v3d->transp = false;
899         v3d->xray = false;
900
901         glDepthMask(GL_TRUE);
902 }
903
904 /* clears zbuffer and draws it over,
905  * note that in the select version we don't care about transparent flag as with regular drawing */
906 static void view3d_draw_xray_select(
907         const struct EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, bool *clear)
908 {
909         /* Not ideal, but we need to read from the previous depths before clearing
910          * otherwise we could have a function to load the depths after drawing.
911          *
912          * Clearing the depth buffer isn't all that common between drawing objects so accept this for now.
913          */
914         if (U.gpu_select_pick_deph) {
915                 GPU_select_load_id(-1);
916         }
917
918         View3DAfter *v3da;
919         if (*clear && v3d->zbuf) {
920                 glClear(GL_DEPTH_BUFFER_BIT);
921                 *clear = false;
922         }
923
924         v3d->xray = true;
925         while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
926                 if (GPU_select_load_id(v3da->base->object->select_color)) {
927                         draw_object_select(eval_ctx, scene, sl, ar, v3d, v3da->base, v3da->dflag);
928                 }
929                 MEM_freeN(v3da);
930         }
931         v3d->xray = false;
932 }
933
934 /* *********************** */
935
936 /*
937  * In most cases call draw_dupli_objects,
938  * draw_dupli_objects_color was added because when drawing set dupli's
939  * we need to force the color
940  */
941
942 #if 0
943 int dupli_ob_sort(void *arg1, void *arg2)
944 {
945         void *p1 = ((DupliObject *)arg1)->ob;
946         void *p2 = ((DupliObject *)arg2)->ob;
947         int val = 0;
948         if (p1 < p2) val = -1;
949         else if (p1 > p2) val = 1;
950         return val;
951 }
952 #endif
953
954
955 static DupliObject *dupli_step(DupliObject *dob)
956 {
957         while (dob && dob->no_draw)
958                 dob = dob->next;
959         return dob;
960 }
961
962 static void draw_dupli_objects_color(
963         const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, BaseLegacy *base,
964         const short dflag, const int color)
965 {
966         RegionView3D *rv3d = ar->regiondata;
967         ListBase *lb;
968         LodLevel *savedlod;
969         Base tbase = {NULL};
970         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
971         unsigned char color_rgb[3];
972         const short dflag_dupli = dflag | DRAW_CONSTCOLOR;
973         short transflag;
974         char dt;
975         short dtx;
976         DupliApplyData *apply_data;
977
978         if ((base->flag & BASE_VISIBLED) == 0) return;
979         if ((base->object->restrictflag & OB_RESTRICT_RENDER) && (v3d->flag2 & V3D_RENDER_OVERRIDE)) return;
980
981         if (dflag & DRAW_CONSTCOLOR) {
982                 BLI_assert(color == TH_UNDEFINED);
983         }
984         else {
985                 UI_GetThemeColorBlend3ubv(color, TH_BACK, 0.5f, color_rgb);
986         }
987
988         tbase.flag_legacy = OB_FROMDUPLI | base->flag_legacy;
989         tbase.flag = base->flag;
990         lb = object_duplilist(eval_ctx, scene, base->object);
991         // BLI_listbase_sort(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
992
993         apply_data = duplilist_apply(eval_ctx, base->object, scene, lb);
994
995         DupliObject *dob_next = NULL;
996         DupliObject *dob = dupli_step(lb->first);
997         if (dob) dob_next = dupli_step(dob->next);
998
999         for (; dob; dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
1000                 bool testbb = false;
1001
1002                 tbase.object = dob->ob;
1003
1004                 /* Make sure lod is updated from dupli's position */
1005                 savedlod = dob->ob->currentlod;
1006
1007 #ifdef WITH_GAMEENGINE
1008                 if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
1009                         BKE_object_lod_update(dob->ob, rv3d->viewinv[3]);
1010                 }
1011 #endif
1012
1013                 /* extra service: draw the duplicator in drawtype of parent, minimum taken
1014                  * to allow e.g. boundbox box objects in groups for LOD */
1015                 dt = tbase.object->dt;
1016                 tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
1017
1018                 /* inherit draw extra, but not if a boundbox under the assumption that this
1019                  * is intended to speed up drawing, and drawing extra (especially wire) can
1020                  * slow it down too much */
1021                 dtx = tbase.object->dtx;
1022                 if (tbase.object->dt != OB_BOUNDBOX)
1023                         tbase.object->dtx = base->object->dtx;
1024
1025                 /* negative scale flag has to propagate */
1026                 transflag = tbase.object->transflag;
1027
1028                 if (is_negative_m4(dob->mat))
1029                         tbase.object->transflag |= OB_NEG_SCALE;
1030                 else
1031                         tbase.object->transflag &= ~OB_NEG_SCALE;
1032                 
1033                 /* should move outside the loop but possible color is set in draw_object still */
1034                 if ((dflag & DRAW_CONSTCOLOR) == 0) {
1035                         glColor3ubv(color_rgb);
1036                 }
1037                 
1038                 if ((bb_tmp = BKE_object_boundbox_get(dob->ob))) {
1039                         bb = *bb_tmp; /* must make a copy  */
1040                         testbb = true;
1041                 }
1042
1043                 if (!testbb || ED_view3d_boundbox_clip_ex(rv3d, &bb, dob->mat)) {
1044                         copy_m4_m4(dob->ob->obmat, dob->mat);
1045                         GPU_begin_dupli_object(dob);
1046                         draw_object(eval_ctx, scene, sl, ar, v3d, &tbase, dflag_dupli);
1047                         GPU_end_dupli_object();
1048                 }
1049                 
1050                 tbase.object->dt = dt;
1051                 tbase.object->dtx = dtx;
1052                 tbase.object->transflag = transflag;
1053                 tbase.object->currentlod = savedlod;
1054         }
1055
1056         if (apply_data) {
1057                 duplilist_restore(lb, apply_data);
1058                 duplilist_free_apply_data(apply_data);
1059         }
1060
1061         free_object_duplilist(lb);
1062 }
1063
1064 void draw_dupli_objects(const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, BaseLegacy *base)
1065 {
1066         /* define the color here so draw_dupli_objects_color can be called
1067          * from the set loop */
1068         
1069         int color = (base->flag & BASE_SELECTED) ? TH_SELECT : TH_WIRE;
1070         /* debug */
1071         if (base->object->dup_group && base->object->dup_group->id.us < 1)
1072                 color = TH_REDALERT;
1073         
1074         draw_dupli_objects_color(eval_ctx, scene, sl, ar, v3d, base, 0, color);
1075 }
1076
1077 /* XXX warning, not using gpu offscreen here */
1078 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
1079 {
1080         /* clamp rect by region */
1081         rcti r = {
1082                 .xmin = 0,
1083                 .xmax = ar->winx - 1,
1084                 .ymin = 0,
1085                 .ymax = ar->winy - 1
1086         };
1087
1088         /* Constrain rect to depth bounds */
1089         BLI_rcti_isect(&r, rect, rect);
1090
1091         /* assign values to compare with the ViewDepths */
1092         int x = rect->xmin;
1093         int y = rect->ymin;
1094
1095         int w = BLI_rcti_size_x(rect);
1096         int h = BLI_rcti_size_y(rect);
1097
1098         if (w <= 0 || h <= 0) {
1099                 if (d->depths)
1100                         MEM_freeN(d->depths);
1101                 d->depths = NULL;
1102
1103                 d->damaged = false;
1104         }
1105         else if (d->w != w ||
1106                  d->h != h ||
1107                  d->x != x ||
1108                  d->y != y ||
1109                  d->depths == NULL
1110                  )
1111         {
1112                 d->x = x;
1113                 d->y = y;
1114                 d->w = w;
1115                 d->h = h;
1116
1117                 if (d->depths)
1118                         MEM_freeN(d->depths);
1119
1120                 d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
1121                 
1122                 d->damaged = true;
1123         }
1124
1125         if (d->damaged) {
1126                 /* XXX using special function here, it doesn't use the gpu offscreen system */
1127                 view3d_opengl_read_Z_pixels(ar, d->x, d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
1128                 glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
1129                 d->damaged = false;
1130         }
1131 }
1132
1133 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
1134 void ED_view3d_depth_update(ARegion *ar)
1135 {
1136         RegionView3D *rv3d = ar->regiondata;
1137         
1138         /* Create storage for, and, if necessary, copy depth buffer */
1139         if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
1140         if (rv3d->depths) {
1141                 ViewDepths *d = rv3d->depths;
1142                 if (d->w != ar->winx ||
1143                     d->h != ar->winy ||
1144                     !d->depths)
1145                 {
1146                         d->w = ar->winx;
1147                         d->h = ar->winy;
1148                         if (d->depths)
1149                                 MEM_freeN(d->depths);
1150                         d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
1151                         d->damaged = true;
1152                 }
1153                 
1154                 if (d->damaged) {
1155                         view3d_opengl_read_pixels(ar, 0, 0, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
1156                         glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
1157                         
1158                         d->damaged = false;
1159                 }
1160         }
1161 }
1162
1163 /* utility function to find the closest Z value, use for autodepth */
1164 float view3d_depth_near(ViewDepths *d)
1165 {
1166         /* convert to float for comparisons */
1167         const float near = (float)d->depth_range[0];
1168         const float far_real = (float)d->depth_range[1];
1169         float far = far_real;
1170
1171         const float *depths = d->depths;
1172         float depth = FLT_MAX;
1173         int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
1174
1175         /* far is both the starting 'far' value
1176          * and the closest value found. */
1177         while (i--) {
1178                 depth = *depths++;
1179                 if ((depth < far) && (depth > near)) {
1180                         far = depth;
1181                 }
1182         }
1183
1184         return far == far_real ? FLT_MAX : far;
1185 }
1186
1187 void ED_view3d_draw_depth_gpencil(
1188         const EvaluationContext *eval_ctx, Scene *scene, ARegion *ar, View3D *v3d)
1189 {
1190         bool zbuf = v3d->zbuf;
1191
1192         /* Setup view matrix. */
1193         ED_view3d_draw_setup_view(NULL, eval_ctx, scene, ar, v3d, NULL, NULL, NULL);
1194
1195         glClear(GL_DEPTH_BUFFER_BIT);
1196
1197         v3d->zbuf = true;
1198         glEnable(GL_DEPTH_TEST);
1199
1200         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
1201                 ED_gpencil_draw_view3d(NULL, scene, v3d, ar, true);
1202         }
1203
1204         v3d->zbuf = zbuf;
1205         if (!zbuf) glDisable(GL_DEPTH_TEST);
1206 }
1207
1208 void ED_view3d_draw_depth_loop(const EvaluationContext *eval_ctx, Scene *scene, ARegion *ar, View3D *v3d)
1209 {
1210         Base *base;
1211         SceneLayer *sl = eval_ctx->scene_layer;
1212         /* no need for color when drawing depth buffer */
1213         const short dflag_depth = DRAW_CONSTCOLOR;
1214
1215         /* draw set first */
1216         if (scene->set) {
1217                 Scene *sce_iter;
1218                 for (SETLOOPER(scene->set, sce_iter, base)) {
1219                         if ((base->flag & BASE_VISIBLED) != 0) {
1220                                 draw_object(eval_ctx, scene, sl, ar, v3d, base, 0);
1221                                 if (base->object->transflag & OB_DUPLI) {
1222                                         draw_dupli_objects_color(eval_ctx, scene, sl, ar, v3d, base, dflag_depth, TH_UNDEFINED);
1223                                 }
1224                         }
1225                 }
1226         }
1227         
1228         for (base = sl->object_bases.first; base; base = base->next) {
1229                 if ((base->flag & BASE_VISIBLED) != 0) {
1230                         /* dupli drawing */
1231                         if (base->object->transflag & OB_DUPLI) {
1232                                 draw_dupli_objects_color(eval_ctx, scene, sl, ar, v3d, base, dflag_depth, TH_UNDEFINED);
1233                         }
1234                         draw_object(eval_ctx, scene, sl, ar, v3d, base, dflag_depth);
1235                 }
1236         }
1237         
1238         /* this isn't that nice, draw xray objects as if they are normal */
1239         if (v3d->afterdraw_transp.first ||
1240             v3d->afterdraw_xray.first ||
1241             v3d->afterdraw_xraytransp.first)
1242         {
1243                 View3DAfter *v3da;
1244                 int mask_orig;
1245
1246                 v3d->xray = true;
1247                 
1248                 /* transp materials can change the depth mask, see #21388 */
1249                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
1250
1251
1252                 if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
1253                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
1254                         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = v3da->next) {
1255                                 draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, dflag_depth);
1256                         }
1257                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
1258                 }
1259
1260                 /* draw 3 passes, transp/xray/xraytransp */
1261                 v3d->xray = false;
1262                 v3d->transp = true;
1263                 while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
1264                         draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, dflag_depth);
1265                         MEM_freeN(v3da);
1266                 }
1267
1268                 v3d->xray = true;
1269                 v3d->transp = false;
1270                 while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
1271                         draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, dflag_depth);
1272                         MEM_freeN(v3da);
1273                 }
1274
1275                 v3d->xray = true;
1276                 v3d->transp = true;
1277                 while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
1278                         draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, dflag_depth);
1279                         MEM_freeN(v3da);
1280                 }
1281
1282                 
1283                 v3d->xray = false;
1284                 v3d->transp = false;
1285
1286                 glDepthMask(mask_orig);
1287         }
1288 }
1289
1290 void ED_view3d_draw_select_loop(
1291         const struct EvaluationContext *eval_ctx, ViewContext *vc, Scene *scene, SceneLayer *sl,
1292         View3D *v3d, ARegion *ar, bool use_obedit_skip, bool use_nearest)
1293 {
1294         short code = 1;
1295         const short dflag = DRAW_PICKING | DRAW_CONSTCOLOR;
1296
1297         if (vc->obedit && vc->obedit->type == OB_MBALL) {
1298                 draw_object(eval_ctx, scene, sl, ar, v3d, BASACT_NEW(sl), dflag);
1299         }
1300         else if ((vc->obedit && vc->obedit->type == OB_ARMATURE)) {
1301                 /* if not drawing sketch, draw bones */
1302                 if (!BDR_drawSketchNames(vc)) {
1303                         draw_object(eval_ctx, scene, sl, ar, v3d, BASACT_NEW(sl), dflag);
1304                 }
1305         }
1306         else {
1307                 Base *base;
1308
1309                 for (base = sl->object_bases.first; base; base = base->next) {
1310                         if ((base->flag & BASE_VISIBLED) != 0) {
1311                                 if (((base->flag & BASE_SELECTABLED) == 0) ||
1312                                     (use_obedit_skip && (scene->obedit->data == base->object->data)))
1313                                 {
1314                                         base->object->select_color = 0;
1315                                 }
1316                                 else {
1317                                         base->object->select_color = code;
1318
1319                                         if (use_nearest && (base->object->dtx & OB_DRAWXRAY)) {
1320                                                 ED_view3d_after_add(&v3d->afterdraw_xray, base, dflag);
1321                                         }
1322                                         else {
1323                                                 if (GPU_select_load_id(code)) {
1324                                                         draw_object(eval_ctx, scene, sl, ar, v3d, base, dflag);
1325                                                 }
1326                                         }
1327                                         code++;
1328                                 }
1329                         }
1330                 }
1331
1332                 if (use_nearest) {
1333                         bool xrayclear = true;
1334                         if (v3d->afterdraw_xray.first) {
1335                                 view3d_draw_xray_select(eval_ctx, scene, sl, ar, v3d, &xrayclear);
1336                         }
1337                 }
1338         }
1339 }
1340
1341 typedef struct View3DShadow {
1342         struct View3DShadow *next, *prev;
1343         GPULamp *lamp;
1344 } View3DShadow;
1345
1346 static void gpu_render_lamp_update(Scene *scene, View3D *v3d,
1347                                    Object *ob, Object *par,
1348                                    float obmat[4][4], unsigned int lay,
1349                                    ListBase *shadows, SceneRenderLayer *srl)
1350 {
1351         GPULamp *lamp = GPU_lamp_from_blender(scene, ob, par);
1352         
1353         if (lamp) {
1354                 Lamp *la = (Lamp *)ob->data;
1355
1356                 GPU_lamp_update(lamp, lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
1357                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
1358                 
1359                 unsigned int layers = lay & v3d->lay;
1360                 if (srl)
1361                         layers &= srl->lay;
1362
1363                 if (layers &&
1364                     GPU_lamp_has_shadow_buffer(lamp) &&
1365                     /* keep last, may do string lookup */
1366                     GPU_lamp_visible(lamp, srl, NULL))
1367                 {
1368                         View3DShadow *shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
1369                         shadow->lamp = lamp;
1370                         BLI_addtail(shadows, shadow);
1371                 }
1372         }
1373 }
1374
1375 static void gpu_update_lamps_shadows_world(const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d)
1376 {
1377         ListBase shadows;
1378         Scene *sce_iter;
1379         Base *base;
1380         World *world = scene->world;
1381         SceneRenderLayer *srl = v3d->scenelock ? BLI_findlink(&scene->r.layers, scene->r.actlay) : NULL;
1382         
1383         BLI_listbase_clear(&shadows);
1384         
1385         /* update lamp transform and gather shadow lamps */
1386         for (SETLOOPER(scene, sce_iter, base)) {
1387                 Object *ob = base->object;
1388                 
1389                 if (ob->type == OB_LAMP)
1390                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, ob->lay, &shadows, srl);
1391                 
1392                 if (ob->transflag & OB_DUPLI) {
1393                         DupliObject *dob;
1394                         ListBase *lb = object_duplilist(G.main->eval_ctx, scene, ob);
1395                         
1396                         for (dob = lb->first; dob; dob = dob->next)
1397                                 if (dob->ob->type == OB_LAMP)
1398                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, ob->lay, &shadows, srl);
1399                         
1400                         free_object_duplilist(lb);
1401                 }
1402         }
1403         
1404         /* render shadows after updating all lamps, nested object_duplilist
1405          * don't work correct since it's replacing object matrices */
1406         for (View3DShadow *shadow = shadows.first; shadow; shadow = shadow->next) {
1407                 /* this needs to be done better .. */
1408                 float viewmat[4][4], winmat[4][4];
1409                 ARegion ar = {NULL};
1410                 RegionView3D rv3d = {{{0}}};
1411
1412                 int drawtype = v3d->drawtype;
1413                 int lay = v3d->lay;
1414                 int flag2 = v3d->flag2;
1415
1416                 v3d->drawtype = OB_SOLID;
1417                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
1418                 v3d->flag2 &= ~(V3D_SOLID_TEX | V3D_SHOW_SOLID_MATCAP);
1419                 v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
1420                 
1421                 int winsize;
1422                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
1423
1424                 ar.regiondata = &rv3d;
1425                 ar.regiontype = RGN_TYPE_WINDOW;
1426                 rv3d.persp = RV3D_CAMOB;
1427                 copy_m4_m4(rv3d.winmat, winmat);
1428                 copy_m4_m4(rv3d.viewmat, viewmat);
1429                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
1430                 mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
1431                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
1432
1433                 /* no need to call ED_view3d_draw_offscreen_init since shadow buffers were already updated */
1434                 ED_view3d_draw_offscreen(
1435                             eval_ctx, scene, eval_ctx->scene_layer, v3d, &ar, winsize, winsize, viewmat, winmat,
1436                             false, false, true,
1437                             NULL, NULL, NULL, NULL);
1438                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
1439                 
1440                 v3d->drawtype = drawtype;
1441                 v3d->lay = lay;
1442                 v3d->flag2 = flag2;
1443         }
1444
1445         BLI_freelistN(&shadows);
1446
1447         /* update world values */
1448         if (world) {
1449                 GPU_mist_update_enable(world->mode & WO_MIST);
1450                 GPU_mist_update_values(world->mistype, world->miststa, world->mistdist, world->misi, &world->horr);
1451                 GPU_horizon_update_color(&world->horr);
1452                 GPU_ambient_update_color(&world->ambr);
1453                 GPU_zenith_update_color(&world->zenr);
1454         }
1455 }
1456
1457 /* *********************** customdata **************** */
1458
1459 CustomDataMask ED_view3d_datamask(const Scene *scene, const View3D *v3d)
1460 {
1461         CustomDataMask mask = 0;
1462         const int drawtype = view3d_effective_drawtype(v3d);
1463
1464         if (ELEM(drawtype, OB_TEXTURE, OB_MATERIAL) ||
1465             ((drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
1466         {
1467                 mask |= CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL;
1468
1469                 if (BKE_scene_use_new_shading_nodes(scene)) {
1470                         if (drawtype == OB_MATERIAL)
1471                                 mask |= CD_MASK_ORCO;
1472                 }
1473                 else {
1474                         if ((scene->gm.matmode == GAME_MAT_GLSL && drawtype == OB_TEXTURE) || 
1475                             (drawtype == OB_MATERIAL))
1476                         {
1477                                 mask |= CD_MASK_ORCO;
1478                         }
1479                 }
1480         }
1481
1482         return mask;
1483 }
1484
1485 /* goes over all modes and view3d settings */
1486 CustomDataMask ED_view3d_screen_datamask(const Scene *scene, const bScreen *screen)
1487 {
1488         CustomDataMask mask = CD_MASK_BAREMESH;
1489         
1490         /* check if we need tfaces & mcols due to view mode */
1491         for (const ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
1492                 if (sa->spacetype == SPACE_VIEW3D) {
1493                         mask |= ED_view3d_datamask(scene, sa->spacedata.first);
1494                 }
1495         }
1496
1497         return mask;
1498 }
1499
1500 /**
1501  * Shared by #ED_view3d_draw_offscreen and #view3d_main_region_draw_objects
1502  *
1503  * \note \a C and \a grid_unit will be NULL when \a draw_offscreen is set.
1504  * \note Drawing lamps and opengl render uses this, so dont do grease pencil or view widgets here.
1505  */
1506 static void view3d_draw_objects(
1507         const bContext *C,
1508         const EvaluationContext *eval_ctx,
1509         Scene *scene, View3D *v3d, ARegion *ar,
1510         const char **grid_unit,
1511         const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
1512 {
1513         SceneLayer *sl = C ? CTX_data_scene_layer(C) : BKE_scene_layer_from_scene_get(scene);
1514         RegionView3D *rv3d = ar->regiondata;
1515         Base *base;
1516         const bool do_camera_frame = !draw_offscreen;
1517         const bool draw_grids = !draw_offscreen && (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0;
1518         const bool draw_floor = (rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO);
1519         /* only draw grids after in solid modes, else it hovers over mesh wires */
1520         const bool draw_grids_after = draw_grids && draw_floor && (v3d->drawtype > OB_WIRE) && fx;
1521         bool do_composite_xray = false;
1522         bool xrayclear = true;
1523
1524         if (!draw_offscreen) {
1525                 ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
1526         }
1527
1528         if (rv3d->rflag & RV3D_CLIPPING)
1529                 view3d_draw_clipping(rv3d);
1530
1531         /* set zbuffer after we draw clipping region */
1532         v3d->zbuf = VP_legacy_use_depth(scene, v3d);
1533
1534         if (v3d->zbuf) {
1535                 glEnable(GL_DEPTH_TEST);
1536         }
1537
1538         /* ortho grid goes first, does not write to depth buffer and doesn't need depth test so it will override
1539          * objects if done last */
1540         if (draw_grids) {
1541                 /* needs to be done always, gridview is adjusted in drawgrid() now, but only for ortho views. */
1542                 rv3d->gridview = ED_view3d_grid_scale(scene, v3d, grid_unit);
1543
1544                 if (!draw_floor) {
1545                         ED_region_pixelspace(ar);
1546                         *grid_unit = NULL;  /* drawgrid need this to detect/affect smallest valid unit... */
1547                         VP_legacy_drawgrid(&scene->unit, ar, v3d, grid_unit);
1548                         gpuLoadProjectionMatrix(rv3d->winmat);
1549                         gpuLoadMatrix(rv3d->viewmat);
1550                 }
1551                 else if (!draw_grids_after) {
1552                         VP_legacy_drawfloor(scene, v3d, grid_unit, true);
1553                 }
1554         }
1555
1556         /* important to do before clipping */
1557         if (do_bgpic) {
1558                 view3d_draw_bgpic_test(scene, ar, v3d, false, do_camera_frame);
1559         }
1560
1561         if (rv3d->rflag & RV3D_CLIPPING) {
1562                 ED_view3d_clipping_set(rv3d);
1563         }
1564
1565         /* draw set first */
1566         if (scene->set) {
1567                 const short dflag = DRAW_CONSTCOLOR | DRAW_SCENESET;
1568                 Scene *sce_iter;
1569                 for (SETLOOPER(scene->set, sce_iter, base)) {
1570                         if ((base->flag & BASE_VISIBLED) != 0) {
1571                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
1572                                 draw_object(eval_ctx, scene, sl, ar, v3d, base, dflag);
1573
1574                                 if (base->object->transflag & OB_DUPLI) {
1575                                         draw_dupli_objects_color(eval_ctx, scene, sl, ar, v3d, base, dflag, TH_UNDEFINED);
1576                                 }
1577                         }
1578                 }
1579
1580                 /* Transp and X-ray afterdraw stuff for sets is done later */
1581         }
1582
1583         if (draw_offscreen) {
1584                 for (base = sl->object_bases.first; base; base = base->next) {
1585                         if ((base->flag & BASE_VISIBLED) != 0) {
1586                                 /* dupli drawing */
1587                                 if (base->object->transflag & OB_DUPLI) {
1588                                         draw_dupli_objects(eval_ctx, scene, sl, ar, v3d, base);
1589                                 }
1590
1591                                 draw_object(eval_ctx, scene, sl, ar, v3d, base, 0);
1592                         }
1593                 }
1594         }
1595         else {
1596                 unsigned int lay_used = 0;
1597
1598                 /* then draw not selected and the duplis, but skip editmode object */
1599                 for (base = sl->object_bases.first; base; base = base->next) {
1600                         lay_used |= base->lay;
1601
1602                         if ((base->flag & BASE_VISIBLED) != 0) {
1603
1604                                 /* dupli drawing */
1605                                 if (base->object->transflag & OB_DUPLI) {
1606                                         draw_dupli_objects(eval_ctx, scene, sl, ar, v3d, base);
1607                                 }
1608                                 if ((base->flag & BASE_SELECTED) == 0) {
1609                                         if (base->object != scene->obedit)
1610                                                 draw_object(eval_ctx, scene, sl, ar, v3d, base, 0);
1611                                 }
1612                         }
1613                 }
1614
1615                 /* mask out localview */
1616                 v3d->lay_used = lay_used & ((1 << 20) - 1);
1617
1618                 /* draw selected and editmode */
1619                 for (base = sl->object_bases.first; base; base = base->next) {
1620                         if ((base->flag & BASE_VISIBLED) != 0) {
1621                                 if (base->object == scene->obedit || (base->flag & BASE_SELECTED)) {
1622                                         draw_object(eval_ctx, scene, sl, ar, v3d, base, 0);
1623                                 }
1624                         }
1625                 }
1626         }
1627
1628         /* perspective floor goes last to use scene depth and avoid writing to depth buffer */
1629         if (draw_grids_after) {
1630                 VP_legacy_drawfloor(scene, v3d, grid_unit, false);
1631         }
1632
1633         /* must be before xray draw which clears the depth buffer */
1634         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
1635                 wmWindowManager *wm = (C != NULL) ? CTX_wm_manager(C) : NULL;
1636                 
1637                 /* must be before xray draw which clears the depth buffer */
1638                 if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
1639                 ED_gpencil_draw_view3d(wm, scene, v3d, ar, true);
1640                 if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1641         }
1642
1643         /* transp and X-ray afterdraw stuff */
1644         if (v3d->afterdraw_transp.first)     view3d_draw_transp(eval_ctx, scene, sl, ar, v3d);
1645
1646         /* always do that here to cleanup depth buffers if none needed */
1647         if (fx) {
1648                 do_composite_xray = v3d->zbuf && (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first);
1649                 GPU_fx_compositor_setup_XRay_pass(fx, do_composite_xray);
1650         }
1651
1652         if (v3d->afterdraw_xray.first)       view3d_draw_xray(eval_ctx, scene, sl, ar, v3d, &xrayclear);
1653         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(eval_ctx, scene, sl, ar, v3d, xrayclear);
1654
1655         if (fx && do_composite_xray) {
1656                 GPU_fx_compositor_XRay_resolve(fx);
1657         }
1658
1659         if (!draw_offscreen) {
1660                 ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
1661         }
1662
1663         if (rv3d->rflag & RV3D_CLIPPING)
1664                 ED_view3d_clipping_disable();
1665
1666         /* important to do after clipping */
1667         if (do_bgpic) {
1668                 view3d_draw_bgpic_test(scene, ar, v3d, true, do_camera_frame);
1669         }
1670
1671         /* cleanup */
1672         if (v3d->zbuf) {
1673                 v3d->zbuf = false;
1674                 glDisable(GL_DEPTH_TEST);
1675         }
1676
1677         if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
1678                 GPU_free_images_old();
1679         }
1680 }
1681
1682 /**
1683  * Store values from #RegionView3D, set when drawing.
1684  * This is needed when we draw with to a viewport using a different matrix (offscreen drawing for example).
1685  *
1686  * Values set by #ED_view3d_update_viewmat should be handled here.
1687  */
1688 struct RV3DMatrixStore {
1689         float winmat[4][4];
1690         float viewmat[4][4];
1691         float viewinv[4][4];
1692         float persmat[4][4];
1693         float persinv[4][4];
1694         float viewcamtexcofac[4];
1695         float pixsize;
1696 };
1697
1698 struct RV3DMatrixStore *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
1699 {
1700         struct RV3DMatrixStore *rv3dmat = MEM_mallocN(sizeof(*rv3dmat), __func__);
1701         copy_m4_m4(rv3dmat->winmat, rv3d->winmat);
1702         copy_m4_m4(rv3dmat->viewmat, rv3d->viewmat);
1703         copy_m4_m4(rv3dmat->persmat, rv3d->persmat);
1704         copy_m4_m4(rv3dmat->persinv, rv3d->persinv);
1705         copy_m4_m4(rv3dmat->viewinv, rv3d->viewinv);
1706         copy_v4_v4(rv3dmat->viewcamtexcofac, rv3d->viewcamtexcofac);
1707         rv3dmat->pixsize = rv3d->pixsize;
1708         return (void *)rv3dmat;
1709 }
1710
1711 void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, struct RV3DMatrixStore *rv3dmat_pt)
1712 {
1713         struct RV3DMatrixStore *rv3dmat = rv3dmat_pt;
1714         copy_m4_m4(rv3d->winmat, rv3dmat->winmat);
1715         copy_m4_m4(rv3d->viewmat, rv3dmat->viewmat);
1716         copy_m4_m4(rv3d->persmat, rv3dmat->persmat);
1717         copy_m4_m4(rv3d->persinv, rv3dmat->persinv);
1718         copy_m4_m4(rv3d->viewinv, rv3dmat->viewinv);
1719         copy_v4_v4(rv3d->viewcamtexcofac, rv3dmat->viewcamtexcofac);
1720         rv3d->pixsize = rv3dmat->pixsize;
1721 }
1722
1723 /**
1724  * \note The info that this uses is updated in #ED_refresh_viewport_fps,
1725  * which currently gets called during #SCREEN_OT_animation_step.
1726  */
1727 void ED_scene_draw_fps(Scene *scene, const rcti *rect)
1728 {
1729         ScreenFrameRateInfo *fpsi = scene->fps_info;
1730         char printable[16];
1731         
1732         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
1733                 return;
1734         
1735         printable[0] = '\0';
1736         
1737 #if 0
1738         /* this is too simple, better do an average */
1739         fps = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime))
1740 #else
1741         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime));
1742         
1743         float fps = 0.0f;
1744         int tot = 0;
1745         for (int i = 0; i < REDRAW_FRAME_AVERAGE; i++) {
1746                 if (fpsi->redrawtimes_fps[i]) {
1747                         fps += fpsi->redrawtimes_fps[i];
1748                         tot++;
1749                 }
1750         }
1751         if (tot) {
1752                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
1753                 
1754                 //fpsi->redrawtime_index++;
1755                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
1756                 //      fpsi->redrawtime = 0;
1757                 
1758                 fps = fps / tot;
1759         }
1760 #endif
1761
1762         const int font_id = BLF_default();
1763
1764         /* is this more than half a frame behind? */
1765         if (fps + 0.5f < (float)(FPS)) {
1766                 UI_FontThemeColor(font_id, TH_REDALERT);
1767                 BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %.2f"), fps);
1768         }
1769         else {
1770                 UI_FontThemeColor(font_id, TH_TEXT_HI);
1771                 BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %i"), (int)(fps + 0.5f));
1772         }
1773
1774 #ifdef WITH_INTERNATIONAL
1775         BLF_draw_default(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
1776 #else
1777         BLF_draw_default_ascii(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
1778 #endif
1779 }
1780
1781 static bool view3d_main_region_do_render_draw(const Scene *scene)
1782 {
1783         RenderEngineType *type = RE_engines_find(scene->r.engine);
1784
1785         return (type && type->view_update && type->render_to_view);
1786 }
1787
1788 bool ED_view3d_calc_render_border(const Scene *scene, View3D *v3d, ARegion *ar, rcti *rect)
1789 {
1790         RegionView3D *rv3d = ar->regiondata;
1791         bool use_border;
1792
1793         /* test if there is a 3d view rendering */
1794         if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene))
1795                 return false;
1796
1797         /* test if there is a border render */
1798         if (rv3d->persp == RV3D_CAMOB)
1799                 use_border = (scene->r.mode & R_BORDER) != 0;
1800         else
1801                 use_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
1802         
1803         if (!use_border)
1804                 return false;
1805
1806         /* compute border */
1807         if (rv3d->persp == RV3D_CAMOB) {
1808                 rctf viewborder;
1809                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
1810
1811                 rect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
1812                 rect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
1813                 rect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
1814                 rect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
1815         }
1816         else {
1817                 rect->xmin = v3d->render_border.xmin * ar->winx;
1818                 rect->xmax = v3d->render_border.xmax * ar->winx;
1819                 rect->ymin = v3d->render_border.ymin * ar->winy;
1820                 rect->ymax = v3d->render_border.ymax * ar->winy;
1821         }
1822
1823         BLI_rcti_translate(rect, ar->winrct.xmin, ar->winrct.ymin);
1824         BLI_rcti_isect(&ar->winrct, rect, rect);
1825
1826         return true;
1827 }
1828
1829 /**
1830   * IMPORTANT: this is deprecated, any changes made in this function should
1831   * be mirrored in view3d_draw_render_draw() in view3d_draw.c
1832   */
1833 static bool view3d_main_region_draw_engine(
1834         const bContext *C, const EvaluationContext *eval_ctx, Scene *scene,
1835         ARegion *ar, View3D *v3d,
1836         bool clip_border, const rcti *border_rect)
1837 {
1838         RegionView3D *rv3d = ar->regiondata;
1839         RenderEngineType *type;
1840         GLint scissor[4];
1841
1842
1843         /* create render engine */
1844         if (!rv3d->render_engine) {
1845                 RenderEngine *engine;
1846
1847                 type = RE_engines_find(scene->r.engine);
1848
1849                 if (!(type->view_update && type->render_to_view))
1850                         return false;
1851
1852                 engine = RE_engine_create_ex(type, true);
1853
1854                 engine->tile_x = scene->r.tilex;
1855                 engine->tile_y = scene->r.tiley;
1856
1857                 type->view_update(engine, C);
1858
1859                 rv3d->render_engine = engine;
1860         }
1861
1862         /* setup view matrices */
1863         VP_legacy_view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, NULL, NULL);
1864
1865         /* background draw */
1866         ED_region_pixelspace(ar);
1867
1868         if (clip_border) {
1869                 /* for border draw, we only need to clear a subset of the 3d view */
1870                 if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
1871                         glGetIntegerv(GL_SCISSOR_BOX, scissor);
1872                         glScissor(border_rect->xmin, border_rect->ymin,
1873                                   BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
1874                 }
1875                 else {
1876                         return false;
1877                 }
1878         }
1879
1880         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
1881         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1882
1883         if (v3d->flag & V3D_DISPBGPICS)
1884                 view3d_draw_bgpic_test(scene, ar, v3d, false, true);
1885         else
1886                 imm_draw_checker_box(0, 0, ar->winx, ar->winy);
1887
1888         /* render result draw */
1889         type = rv3d->render_engine->type;
1890         type->render_to_view(rv3d->render_engine, C);
1891
1892         if (v3d->flag & V3D_DISPBGPICS)
1893                 view3d_draw_bgpic_test(scene, ar, v3d, true, true);
1894
1895         if (clip_border) {
1896                 /* restore scissor as it was before */
1897                 glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
1898         }
1899
1900         return true;
1901 }
1902
1903 static void view3d_main_region_draw_engine_info(View3D *v3d, RegionView3D *rv3d, ARegion *ar, bool render_border)
1904 {
1905         float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
1906
1907         if (!rv3d->render_engine || !rv3d->render_engine->text[0])
1908                 return;
1909         
1910         if (render_border) {
1911                 /* draw darkened background color. no alpha because border render does
1912                  * partial redraw and will not redraw the region behind this info bar */
1913                 float alpha = 1.0f - fill_color[3];
1914                 Camera *camera = ED_view3d_camera_data_get(v3d, rv3d);
1915
1916                 if (camera) {
1917                         if (camera->flag & CAM_SHOWPASSEPARTOUT) {
1918                                 alpha *= (1.0f - camera->passepartalpha);
1919                         }
1920                 }
1921
1922                 UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
1923                 mul_v3_fl(fill_color, alpha);
1924                 fill_color[3] = 1.0f;
1925         }
1926
1927         ED_region_info_draw(ar, rv3d->render_engine->text, fill_color, true);
1928 }
1929
1930 #ifdef WITH_GAMEENGINE
1931 static void update_lods(Scene *scene, float camera_pos[3])
1932 {
1933         Scene *sce_iter;
1934         Base *base;
1935
1936         for (SETLOOPER(scene, sce_iter, base)) {
1937                 Object *ob = base->object;
1938                 BKE_object_lod_update(ob, camera_pos);
1939         }
1940 }
1941 #endif
1942
1943 static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, SceneLayer *sl, View3D *v3d,
1944                                           ARegion *ar, const char **grid_unit)
1945 {
1946         wmWindow *win = CTX_wm_window(C);
1947         EvaluationContext eval_ctx;
1948         RegionView3D *rv3d = ar->regiondata;
1949         unsigned int lay_used = v3d->lay_used;
1950         
1951         CTX_data_eval_ctx(C, &eval_ctx);
1952
1953         /* post processing */
1954         bool do_compositing = false;
1955         
1956         /* shadow buffers, before we setup matrices */
1957         if (draw_glsl_material(scene, sl, NULL, v3d, v3d->drawtype))
1958                 gpu_update_lamps_shadows_world(&eval_ctx, scene, v3d);
1959
1960         /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
1961         if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
1962                 rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
1963                 GPU_default_lights();
1964         }
1965
1966         /* setup the view matrix */
1967         if (VP_legacy_view3d_stereo3d_active(win, scene, v3d, rv3d)) {
1968                 VP_legacy_view3d_stereo3d_setup(&eval_ctx, scene, v3d, ar);
1969         }
1970         else {
1971                 VP_legacy_view3d_main_region_setup_view(&eval_ctx, scene, v3d, ar, NULL, NULL);
1972         }
1973
1974         rv3d->rflag &= ~RV3D_IS_GAME_ENGINE;
1975 #ifdef WITH_GAMEENGINE
1976         if (STREQ(scene->r.engine, RE_engine_id_BLENDER_GAME)) {
1977                 rv3d->rflag |= RV3D_IS_GAME_ENGINE;
1978
1979                 /* Make sure LoDs are up to date */
1980                 update_lods(scene, rv3d->viewinv[3]);
1981         }
1982 #endif
1983
1984         /* framebuffer fx needed, we need to draw offscreen first */
1985         if (v3d->fx_settings.fx_flag && v3d->drawtype >= OB_SOLID) {
1986                 BKE_screen_gpu_fx_validate(&v3d->fx_settings);
1987                 GPUFXSettings fx_settings = v3d->fx_settings;
1988                 if (!rv3d->compositor)
1989                         rv3d->compositor = GPU_fx_compositor_create();
1990                 
1991                 if (rv3d->persp == RV3D_CAMOB && v3d->camera)
1992                         BKE_camera_to_gpu_dof(v3d->camera, &fx_settings);
1993                 else {
1994                         fx_settings.dof = NULL;
1995                 }
1996
1997                 do_compositing = GPU_fx_compositor_initialize_passes(rv3d->compositor, &ar->winrct, &ar->drawrct, &fx_settings);
1998         }
1999         
2000         /* enables anti-aliasing for 3D view drawing */
2001         if (win->multisamples != USER_MULTISAMPLE_NONE) {
2002                 glEnable(GL_MULTISAMPLE);
2003         }
2004
2005         /* main drawing call */
2006         view3d_draw_objects(C, &eval_ctx, scene, v3d, ar, grid_unit, true, false, do_compositing ? rv3d->compositor : NULL);
2007
2008         /* draw depth culled manipulators - manipulators need to be updated *after* view matrix was set up */
2009         /* TODO depth culling manipulators is not yet supported, just drawing _3D here, should
2010          * later become _IN_SCENE (and draw _3D separate) */
2011         WM_manipulatormap_draw(ar->manipulator_map, C, WM_MANIPULATORMAP_DRAWSTEP_3D);
2012
2013         /* post process */
2014         if (do_compositing) {
2015                 GPU_fx_do_composite_pass(rv3d->compositor, rv3d->winmat, rv3d->is_persp, scene, NULL);
2016         }
2017
2018         /* Disable back anti-aliasing */
2019         if (win->multisamples != USER_MULTISAMPLE_NONE) {
2020                 glDisable(GL_MULTISAMPLE);
2021         }
2022
2023         if (v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
2024                 /* find header and force tag redraw */
2025                 ScrArea *sa = CTX_wm_area(C);
2026                 ARegion *ar_header = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
2027                 ED_region_tag_redraw(ar_header); /* can be NULL */
2028         }
2029
2030         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2031                 BDR_drawSketch(C);
2032         }
2033 }
2034
2035 static void view3d_main_region_draw_info(const bContext *C, Scene *scene,
2036                                        ARegion *ar, View3D *v3d,
2037                                        const char *grid_unit, bool render_border)
2038 {
2039         SceneLayer *sl = CTX_data_scene_layer(C);
2040         wmWindowManager *wm = CTX_wm_manager(C);
2041         RegionView3D *rv3d = ar->regiondata;
2042         rcti rect;
2043         
2044         /* local coordinate visible rect inside region, to accomodate overlapping ui */
2045         ED_region_visible_rect(ar, &rect);
2046
2047         if (rv3d->persp == RV3D_CAMOB) {
2048                 VP_drawviewborder(scene, ar, v3d);
2049         }
2050         else if (v3d->flag2 & V3D_RENDER_BORDER) {
2051                 VP_drawrenderborder(ar, v3d);
2052         }
2053
2054         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2055                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2056                 ED_gpencil_draw_view3d(wm, scene, v3d, ar, false);
2057         }
2058
2059         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2060                 VP_legacy_drawcursor(scene, sl, ar, v3d); /* 3D cursor */
2061
2062                 if (U.uiflag & USER_SHOW_ROTVIEWICON)
2063                         VP_legacy_draw_view_axis(rv3d, &rect);
2064                 else
2065                         draw_view_icon(rv3d, &rect);
2066
2067                 if (U.uiflag & USER_DRAWVIEWINFO) {
2068                         Object *ob = OBACT_NEW(sl);
2069                         VP_legacy_draw_selected_name(scene, ob, &rect);
2070                 }
2071         }
2072
2073         if (rv3d->render_engine) {
2074                 view3d_main_region_draw_engine_info(v3d, rv3d, ar, render_border);
2075                 return;
2076         }
2077
2078         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2079                 if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_no_scrub(wm)) {
2080                         ED_scene_draw_fps(scene, &rect);
2081                 }
2082                 else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
2083                         VP_legacy_draw_viewport_name(ar, v3d, &rect);
2084                 }
2085
2086                 if (grid_unit) { /* draw below the viewport name */
2087                         char numstr[32] = "";
2088
2089                         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
2090                         if (v3d->grid != 1.0f) {
2091                                 BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
2092                         }
2093
2094                         BLF_draw_default_ascii(rect.xmin + U.widget_unit,
2095                                                rect.ymax - (USER_SHOW_VIEWPORTNAME ? 2 * U.widget_unit : U.widget_unit), 0.0f,
2096                                                numstr[0] ? numstr : grid_unit, sizeof(numstr));
2097                 }
2098         }
2099 }
2100
2101 void view3d_main_region_draw_legacy(const bContext *C, ARegion *ar)
2102 {
2103         EvaluationContext eval_ctx;
2104         Scene *scene = CTX_data_scene(C);
2105         SceneLayer *sl = CTX_data_scene_layer(C);
2106         View3D *v3d = CTX_wm_view3d(C);
2107         const char *grid_unit = NULL;
2108         rcti border_rect;
2109
2110         /* if we only redraw render border area, skip opengl draw and also
2111          * don't do scissor because it's already set */
2112         bool render_border = ED_view3d_calc_render_border(scene, v3d, ar, &border_rect);
2113         bool clip_border = (render_border && !BLI_rcti_compare(&ar->drawrct, &border_rect));
2114
2115         gpuPushProjectionMatrix();
2116         gpuLoadIdentityProjectionMatrix();
2117         gpuPushMatrix();
2118         gpuLoadIdentity();
2119
2120         CTX_data_eval_ctx(C, &eval_ctx);
2121
2122         /* draw viewport using opengl */
2123         if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene) || clip_border) {
2124                 VP_view3d_main_region_clear(scene, v3d, ar); /* background */
2125                 view3d_main_region_draw_objects(C, scene, sl, v3d, ar, &grid_unit);
2126
2127                 if (G.debug & G_DEBUG_SIMDATA)
2128                         draw_sim_debug_data(scene, v3d, ar);
2129
2130                 glDisable(GL_DEPTH_TEST);
2131                 ED_region_pixelspace(ar);
2132         }
2133
2134         /* draw viewport using external renderer */
2135         if (v3d->drawtype == OB_RENDER) {
2136                 view3d_main_region_draw_engine(C, &eval_ctx, scene, ar, v3d, clip_border, &border_rect);
2137         }
2138
2139         VP_legacy_view3d_main_region_setup_view(&eval_ctx, scene, v3d, ar, NULL, NULL);
2140         glClear(GL_DEPTH_BUFFER_BIT);
2141
2142         ED_region_pixelspace(ar);
2143
2144         WM_manipulatormap_draw(ar->manipulator_map, C, WM_MANIPULATORMAP_DRAWSTEP_2D);
2145
2146         view3d_main_region_draw_info(C, scene, ar, v3d, grid_unit, render_border);
2147
2148         gpuPopProjectionMatrix();
2149         gpuPopMatrix();
2150
2151         v3d->flag |= V3D_INVALID_BACKBUF;
2152
2153         BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_transp));
2154         BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xray));
2155         BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xraytransp));
2156 }
2157
2158
2159 /* -------------------------------------------------------------------- */
2160
2161 /** \name Deprecated Interface
2162  *
2163  * New viewport sometimes has a check for new/old viewport code.
2164  * Use these functions so new viewport can *optionally* call.
2165  *
2166  * \{ */
2167
2168
2169 void VP_deprecated_view3d_draw_objects(
2170         const bContext *C,
2171         const EvaluationContext *eval_ctx,
2172         Scene *scene, View3D *v3d, ARegion *ar,
2173         const char **grid_unit,
2174         const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
2175 {
2176         view3d_draw_objects(C, eval_ctx, scene, v3d, ar, grid_unit, do_bgpic, draw_offscreen, fx);
2177 }
2178
2179 void VP_deprecated_gpu_update_lamps_shadows_world(const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d)
2180 {
2181         gpu_update_lamps_shadows_world(eval_ctx, scene, v3d);
2182 }
2183
2184 /** \} */