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