Merge commit 'origin/master (9395646c2c44cdf568ca950700d71fe966f2d80f)' into blender2.8
[blender.git] / source / blender / editors / space_view3d / view3d_draw_legacy.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/space_view3d/view3d_draw_legacy.c
28  *  \ingroup spview3d
29  */
30
31 #include <string.h>
32 #include <stdio.h>
33 #include <math.h>
34
35 #include "DNA_armature_types.h"
36 #include "DNA_camera_types.h"
37 #include "DNA_customdata_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_group_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_key_types.h"
42 #include "DNA_lamp_types.h"
43 #include "DNA_scene_types.h"
44 #include "DNA_world_types.h"
45 #include "DNA_brush_types.h"
46
47 #include "MEM_guardedalloc.h"
48
49 #include "BLI_blenlib.h"
50 #include "BLI_math.h"
51 #include "BLI_jitter.h"
52 #include "BLI_utildefines.h"
53 #include "BLI_endian_switch.h"
54 #include "BLI_threads.h"
55
56 #include "BKE_anim.h"
57 #include "BKE_camera.h"
58 #include "BKE_context.h"
59 #include "BKE_customdata.h"
60 #include "BKE_DerivedMesh.h"
61 #include "BKE_image.h"
62 #include "BKE_key.h"
63 #include "BKE_layer.h"
64 #include "BKE_main.h"
65 #include "BKE_object.h"
66 #include "BKE_global.h"
67 #include "BKE_paint.h"
68 #include "BKE_scene.h"
69 #include "BKE_screen.h"
70 #include "BKE_unit.h"
71 #include "BKE_movieclip.h"
72
73 #include "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 "RE_engine.h"
111
112 #include "DRW_engine.h"
113
114 #include "view3d_intern.h"  /* own include */
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                         gpuPushProjectionMatrix();
758                         gpuPushMatrix();
759                         ED_region_pixelspace(ar);
760
761                         gpuTranslate2f(centx, centy);
762                         gpuRotate2D(RAD2DEGF(-bgpic->rotation));
763
764                         if (bgpic->flag & V3D_BGPIC_FLIP_X) {
765                                 zoomx *= -1.0f;
766                                 x1 = x2;
767                         }
768                         if (bgpic->flag & V3D_BGPIC_FLIP_Y) {
769                                 zoomy *= -1.0f;
770                                 y1 = y2;
771                         }
772
773                         float col[4] = {1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend};
774                         IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR);
775                         immDrawPixelsTex(&state, x1 - centx, y1 - centy, ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR, ibuf->rect,
776                                          zoomx, zoomy, col);
777
778                         gpuPopProjectionMatrix();
779                         gpuPopMatrix();
780
781                         glDisable(GL_BLEND);
782
783                         glDepthMask(GL_TRUE);
784                         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
785
786                         if (freeibuf)
787                                 IMB_freeImBuf(freeibuf);
788                         if (releaseibuf)
789                                 BKE_image_release_ibuf(ima, releaseibuf, lock);
790                 }
791         }
792 }
793
794 static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
795                                    const bool do_foreground, const bool do_camera_frame)
796 {
797         RegionView3D *rv3d = ar->regiondata;
798
799         if ((v3d->flag & V3D_DISPBGPICS) == 0)
800                 return;
801
802         /* disabled - mango request, since footage /w only render is quite useful
803          * and this option is easy to disable all background images at once */
804 #if 0
805         if (v3d->flag2 & V3D_RENDER_OVERRIDE)
806                 return;
807 #endif
808
809         if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
810                 if (rv3d->persp == RV3D_CAMOB) {
811                         view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
812                 }
813         }
814         else {
815                 view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
816         }
817 }
818
819 /* ****************** View3d afterdraw *************** */
820
821 typedef struct View3DAfter {
822         struct View3DAfter *next, *prev;
823         struct BaseLegacy *base;
824         short dflag;
825 } View3DAfter;
826
827 /* temp storage of Objects that need to be drawn as last */
828 void ED_view3d_after_add(ListBase *lb, BaseLegacy *base, const short dflag)
829 {
830         View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
831         BLI_assert((base->flag_legacy & OB_FROMDUPLI) == 0);
832         BLI_addtail(lb, v3da);
833         v3da->base = base;
834         v3da->dflag = dflag;
835 }
836
837 /* disables write in zbuffer and draws it over */
838 static void view3d_draw_transp(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d)
839 {
840         View3DAfter *v3da;
841         
842         glDepthMask(GL_FALSE);
843         v3d->transp = true;
844         
845         while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
846                 draw_object(scene, sl, ar, v3d, v3da->base, v3da->dflag);
847                 MEM_freeN(v3da);
848         }
849         v3d->transp = false;
850         
851         glDepthMask(GL_TRUE);
852         
853 }
854
855 /* clears zbuffer and draws it over */
856 static void view3d_draw_xray(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, bool *clear)
857 {
858         if (*clear && v3d->zbuf) {
859                 glClear(GL_DEPTH_BUFFER_BIT);
860                 *clear = false;
861         }
862
863         v3d->xray = true;
864         View3DAfter *v3da;
865         while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
866                 draw_object(scene, sl, ar, v3d, v3da->base, v3da->dflag);
867                 MEM_freeN(v3da);
868         }
869         v3d->xray = false;
870 }
871
872
873 /* clears zbuffer and draws it over */
874 static void view3d_draw_xraytransp(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, const bool clear)
875 {
876         if (clear && v3d->zbuf)
877                 glClear(GL_DEPTH_BUFFER_BIT);
878
879         v3d->xray = true;
880         v3d->transp = true;
881         
882         glDepthMask(GL_FALSE);
883
884         View3DAfter *v3da;
885         while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
886                 draw_object(scene, sl, ar, v3d, v3da->base, v3da->dflag);
887                 MEM_freeN(v3da);
888         }
889
890         v3d->transp = false;
891         v3d->xray = false;
892
893         glDepthMask(GL_TRUE);
894 }
895
896 /* clears zbuffer and draws it over,
897  * note that in the select version we don't care about transparent flag as with regular drawing */
898 static void view3d_draw_xray_select(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, bool *clear)
899 {
900         /* Not ideal, but we need to read from the previous depths before clearing
901          * otherwise we could have a function to load the depths after drawing.
902          *
903          * Clearing the depth buffer isn't all that common between drawing objects so accept this for now.
904          */
905         if (U.gpu_select_pick_deph) {
906                 GPU_select_load_id(-1);
907         }
908
909         View3DAfter *v3da;
910         if (*clear && v3d->zbuf) {
911                 glClear(GL_DEPTH_BUFFER_BIT);
912                 *clear = false;
913         }
914
915         v3d->xray = true;
916         while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
917                 if (GPU_select_load_id(v3da->base->selcol)) {
918                         draw_object_select(scene, sl, ar, v3d, v3da->base, v3da->dflag);
919                 }
920                 MEM_freeN(v3da);
921         }
922         v3d->xray = false;
923 }
924
925 /* *********************** */
926
927 /*
928  * In most cases call draw_dupli_objects,
929  * draw_dupli_objects_color was added because when drawing set dupli's
930  * we need to force the color
931  */
932
933 #if 0
934 int dupli_ob_sort(void *arg1, void *arg2)
935 {
936         void *p1 = ((DupliObject *)arg1)->ob;
937         void *p2 = ((DupliObject *)arg2)->ob;
938         int val = 0;
939         if (p1 < p2) val = -1;
940         else if (p1 > p2) val = 1;
941         return val;
942 }
943 #endif
944
945
946 static DupliObject *dupli_step(DupliObject *dob)
947 {
948         while (dob && dob->no_draw)
949                 dob = dob->next;
950         return dob;
951 }
952
953 static void draw_dupli_objects_color(
954         Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, BaseLegacy *base,
955         const short dflag, const int color)
956 {
957         RegionView3D *rv3d = ar->regiondata;
958         ListBase *lb;
959         LodLevel *savedlod;
960         Base tbase = {NULL};
961         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
962         unsigned char color_rgb[3];
963         const short dflag_dupli = dflag | DRAW_CONSTCOLOR;
964         short transflag;
965         char dt;
966         short dtx;
967         DupliApplyData *apply_data;
968
969         if ((base->flag & BASE_VISIBLED) == 0) return;
970         if ((base->object->restrictflag & OB_RESTRICT_RENDER) && (v3d->flag2 & V3D_RENDER_OVERRIDE)) return;
971
972         if (dflag & DRAW_CONSTCOLOR) {
973                 BLI_assert(color == TH_UNDEFINED);
974         }
975         else {
976                 UI_GetThemeColorBlend3ubv(color, TH_BACK, 0.5f, color_rgb);
977         }
978
979         tbase.flag_legacy = OB_FROMDUPLI | base->flag_legacy;
980         tbase.flag = base->flag;
981         lb = object_duplilist(G.main->eval_ctx, scene, base->object);
982         // BLI_listbase_sort(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
983
984         apply_data = duplilist_apply(base->object, scene, lb);
985
986         DupliObject *dob_next = NULL;
987         DupliObject *dob = dupli_step(lb->first);
988         if (dob) dob_next = dupli_step(dob->next);
989
990         for (; dob; dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
991                 bool testbb = false;
992
993                 tbase.object = dob->ob;
994
995                 /* Make sure lod is updated from dupli's position */
996                 savedlod = dob->ob->currentlod;
997
998 #ifdef WITH_GAMEENGINE
999                 if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
1000                         BKE_object_lod_update(dob->ob, rv3d->viewinv[3]);
1001                 }
1002 #endif
1003
1004                 /* extra service: draw the duplicator in drawtype of parent, minimum taken
1005                  * to allow e.g. boundbox box objects in groups for LOD */
1006                 dt = tbase.object->dt;
1007                 tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
1008
1009                 /* inherit draw extra, but not if a boundbox under the assumption that this
1010                  * is intended to speed up drawing, and drawing extra (especially wire) can
1011                  * slow it down too much */
1012                 dtx = tbase.object->dtx;
1013                 if (tbase.object->dt != OB_BOUNDBOX)
1014                         tbase.object->dtx = base->object->dtx;
1015
1016                 /* negative scale flag has to propagate */
1017                 transflag = tbase.object->transflag;
1018
1019                 if (is_negative_m4(dob->mat))
1020                         tbase.object->transflag |= OB_NEG_SCALE;
1021                 else
1022                         tbase.object->transflag &= ~OB_NEG_SCALE;
1023                 
1024                 /* should move outside the loop but possible color is set in draw_object still */
1025                 if ((dflag & DRAW_CONSTCOLOR) == 0) {
1026                         glColor3ubv(color_rgb);
1027                 }
1028                 
1029                 if ((bb_tmp = BKE_object_boundbox_get(dob->ob))) {
1030                         bb = *bb_tmp; /* must make a copy  */
1031                         testbb = true;
1032                 }
1033
1034                 if (!testbb || ED_view3d_boundbox_clip_ex(rv3d, &bb, dob->mat)) {
1035                         copy_m4_m4(dob->ob->obmat, dob->mat);
1036                         GPU_begin_dupli_object(dob);
1037                         draw_object(scene, sl, ar, v3d, &tbase, dflag_dupli);
1038                         GPU_end_dupli_object();
1039                 }
1040                 
1041                 tbase.object->dt = dt;
1042                 tbase.object->dtx = dtx;
1043                 tbase.object->transflag = transflag;
1044                 tbase.object->currentlod = savedlod;
1045         }
1046
1047         if (apply_data) {
1048                 duplilist_restore(lb, apply_data);
1049                 duplilist_free_apply_data(apply_data);
1050         }
1051
1052         free_object_duplilist(lb);
1053 }
1054
1055 void draw_dupli_objects(Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, BaseLegacy *base)
1056 {
1057         /* define the color here so draw_dupli_objects_color can be called
1058          * from the set loop */
1059         
1060         int color = (base->flag & BASE_SELECTED) ? TH_SELECT : TH_WIRE;
1061         /* debug */
1062         if (base->object->dup_group && base->object->dup_group->id.us < 1)
1063                 color = TH_REDALERT;
1064         
1065         draw_dupli_objects_color(scene, sl, ar, v3d, base, 0, color);
1066 }
1067
1068 /* XXX warning, not using gpu offscreen here */
1069 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
1070 {
1071         /* clamp rect by region */
1072         rcti r = {
1073                 .xmin = 0,
1074                 .xmax = ar->winx - 1,
1075                 .ymin = 0,
1076                 .ymax = ar->winy - 1
1077         };
1078
1079         /* Constrain rect to depth bounds */
1080         BLI_rcti_isect(&r, rect, rect);
1081
1082         /* assign values to compare with the ViewDepths */
1083         int x = rect->xmin;
1084         int y = rect->ymin;
1085
1086         int w = BLI_rcti_size_x(rect);
1087         int h = BLI_rcti_size_y(rect);
1088
1089         if (w <= 0 || h <= 0) {
1090                 if (d->depths)
1091                         MEM_freeN(d->depths);
1092                 d->depths = NULL;
1093
1094                 d->damaged = false;
1095         }
1096         else if (d->w != w ||
1097                  d->h != h ||
1098                  d->x != x ||
1099                  d->y != y ||
1100                  d->depths == NULL
1101                  )
1102         {
1103                 d->x = x;
1104                 d->y = y;
1105                 d->w = w;
1106                 d->h = h;
1107
1108                 if (d->depths)
1109                         MEM_freeN(d->depths);
1110
1111                 d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
1112                 
1113                 d->damaged = true;
1114         }
1115
1116         if (d->damaged) {
1117                 /* XXX using special function here, it doesn't use the gpu offscreen system */
1118                 view3d_opengl_read_Z_pixels(ar, d->x, d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
1119                 glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
1120                 d->damaged = false;
1121         }
1122 }
1123
1124 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
1125 void ED_view3d_depth_update(ARegion *ar)
1126 {
1127         RegionView3D *rv3d = ar->regiondata;
1128         
1129         /* Create storage for, and, if necessary, copy depth buffer */
1130         if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
1131         if (rv3d->depths) {
1132                 ViewDepths *d = rv3d->depths;
1133                 if (d->w != ar->winx ||
1134                     d->h != ar->winy ||
1135                     !d->depths)
1136                 {
1137                         d->w = ar->winx;
1138                         d->h = ar->winy;
1139                         if (d->depths)
1140                                 MEM_freeN(d->depths);
1141                         d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
1142                         d->damaged = true;
1143                 }
1144                 
1145                 if (d->damaged) {
1146                         view3d_opengl_read_pixels(ar, 0, 0, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
1147                         glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
1148                         
1149                         d->damaged = false;
1150                 }
1151         }
1152 }
1153
1154 /* utility function to find the closest Z value, use for autodepth */
1155 float view3d_depth_near(ViewDepths *d)
1156 {
1157         /* convert to float for comparisons */
1158         const float near = (float)d->depth_range[0];
1159         const float far_real = (float)d->depth_range[1];
1160         float far = far_real;
1161
1162         const float *depths = d->depths;
1163         float depth = FLT_MAX;
1164         int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
1165
1166         /* far is both the starting 'far' value
1167          * and the closest value found. */
1168         while (i--) {
1169                 depth = *depths++;
1170                 if ((depth < far) && (depth > near)) {
1171                         far = depth;
1172                 }
1173         }
1174
1175         return far == far_real ? FLT_MAX : far;
1176 }
1177
1178 void ED_view3d_draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
1179 {
1180         bool zbuf = v3d->zbuf;
1181         RegionView3D *rv3d = ar->regiondata;
1182
1183         view3d_winmatrix_set(ar, v3d, NULL);
1184         view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
1185
1186         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
1187         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1188         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1189
1190         glClear(GL_DEPTH_BUFFER_BIT);
1191
1192         gpuLoadMatrix(rv3d->viewmat);
1193
1194         v3d->zbuf = true;
1195         glEnable(GL_DEPTH_TEST);
1196
1197         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
1198                 ED_gpencil_draw_view3d(NULL, scene, v3d, ar, true);
1199         }
1200
1201         v3d->zbuf = zbuf;
1202         if (!zbuf) glDisable(GL_DEPTH_TEST);
1203 }
1204
1205 void ED_view3d_draw_depth_loop(Scene *scene, ARegion *ar, View3D *v3d)
1206 {
1207         Base *base;
1208         SceneLayer *sl = BKE_scene_layer_context_active(scene);
1209         /* no need for color when drawing depth buffer */
1210         const short dflag_depth = DRAW_CONSTCOLOR;
1211
1212         /* draw set first */
1213         if (scene->set) {
1214                 Scene *sce_iter;
1215                 for (SETLOOPER(scene->set, sce_iter, base)) {
1216                         if ((base->flag & BASE_VISIBLED) != 0) {
1217                                 draw_object(scene, sl, ar, v3d, base, 0);
1218                                 if (base->object->transflag & OB_DUPLI) {
1219                                         draw_dupli_objects_color(scene, sl, ar, v3d, base, dflag_depth, TH_UNDEFINED);
1220                                 }
1221                         }
1222                 }
1223         }
1224         
1225         for (base = sl->object_bases.first; base; base = base->next) {
1226                 if ((base->flag & BASE_VISIBLED) != 0) {
1227                         /* dupli drawing */
1228                         if (base->object->transflag & OB_DUPLI) {
1229                                 draw_dupli_objects_color(scene, sl, ar, v3d, base, dflag_depth, TH_UNDEFINED);
1230                         }
1231                         draw_object(scene, sl, ar, v3d, base, dflag_depth);
1232                 }
1233         }
1234         
1235         /* this isn't that nice, draw xray objects as if they are normal */
1236         if (v3d->afterdraw_transp.first ||
1237             v3d->afterdraw_xray.first ||
1238             v3d->afterdraw_xraytransp.first)
1239         {
1240                 View3DAfter *v3da;
1241                 int mask_orig;
1242
1243                 v3d->xray = true;
1244                 
1245                 /* transp materials can change the depth mask, see #21388 */
1246                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
1247
1248
1249                 if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
1250                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
1251                         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = v3da->next) {
1252                                 draw_object(scene, sl, ar, v3d, v3da->base, dflag_depth);
1253                         }
1254                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
1255                 }
1256
1257                 /* draw 3 passes, transp/xray/xraytransp */
1258                 v3d->xray = false;
1259                 v3d->transp = true;
1260                 while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
1261                         draw_object(scene, sl, ar, v3d, v3da->base, dflag_depth);
1262                         MEM_freeN(v3da);
1263                 }
1264
1265                 v3d->xray = true;
1266                 v3d->transp = false;
1267                 while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
1268                         draw_object(scene, sl, ar, v3d, v3da->base, dflag_depth);
1269                         MEM_freeN(v3da);
1270                 }
1271
1272                 v3d->xray = true;
1273                 v3d->transp = true;
1274                 while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
1275                         draw_object(scene, sl, ar, v3d, v3da->base, dflag_depth);
1276                         MEM_freeN(v3da);
1277                 }
1278
1279                 
1280                 v3d->xray = false;
1281                 v3d->transp = false;
1282
1283                 glDepthMask(mask_orig);
1284         }
1285 }
1286
1287 void ED_view3d_draw_select_loop(
1288         ViewContext *vc, Scene *scene, SceneLayer *sl, View3D *v3d, ARegion *ar,
1289         bool use_obedit_skip, bool use_nearest)
1290 {
1291         short code = 1;
1292         const short dflag = DRAW_PICKING | DRAW_CONSTCOLOR;
1293
1294         if (vc->obedit && vc->obedit->type == OB_MBALL) {
1295                 draw_object(scene, sl, ar, v3d, BASACT_NEW, dflag);
1296         }
1297         else if ((vc->obedit && vc->obedit->type == OB_ARMATURE)) {
1298                 /* if not drawing sketch, draw bones */
1299                 if (!BDR_drawSketchNames(vc)) {
1300                         draw_object(scene, sl, ar, v3d, BASACT_NEW, dflag);
1301                 }
1302         }
1303         else {
1304                 Base *base;
1305
1306                 for (base = sl->object_bases.first; base; base = base->next) {
1307                         if ((base->flag & BASE_VISIBLED) != 0) {
1308                                 if (((base->flag & BASE_SELECTABLED) == 0) ||
1309                                     (use_obedit_skip && (scene->obedit->data == base->object->data)))
1310                                 {
1311                                         base->selcol = 0;
1312                                 }
1313                                 else {
1314                                         base->selcol = code;
1315
1316                                         if (use_nearest && (base->object->dtx & OB_DRAWXRAY)) {
1317                                                 ED_view3d_after_add(&v3d->afterdraw_xray, base, dflag);
1318                                         }
1319                                         else {
1320                                                 if (GPU_select_load_id(code)) {
1321                                                         draw_object(scene, sl, ar, v3d, base, dflag);
1322                                                 }
1323                                         }
1324                                         code++;
1325                                 }
1326                         }
1327                 }
1328
1329                 if (use_nearest) {
1330                         bool xrayclear = true;
1331                         if (v3d->afterdraw_xray.first) {
1332                                 view3d_draw_xray_select(scene, sl, ar, v3d, &xrayclear);
1333                         }
1334                 }
1335         }
1336 }
1337
1338 typedef struct View3DShadow {
1339         struct View3DShadow *next, *prev;
1340         GPULamp *lamp;
1341 } View3DShadow;
1342
1343 static void gpu_render_lamp_update(Scene *scene, View3D *v3d,
1344                                    Object *ob, Object *par,
1345                                    float obmat[4][4], unsigned int lay,
1346                                    ListBase *shadows, SceneRenderLayer *srl)
1347 {
1348         GPULamp *lamp = GPU_lamp_from_blender(scene, ob, par);
1349         
1350         if (lamp) {
1351                 Lamp *la = (Lamp *)ob->data;
1352
1353                 GPU_lamp_update(lamp, lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
1354                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
1355                 
1356                 unsigned int layers = lay & v3d->lay;
1357                 if (srl)
1358                         layers &= srl->lay;
1359
1360                 if (layers &&
1361                     GPU_lamp_has_shadow_buffer(lamp) &&
1362                     /* keep last, may do string lookup */
1363                     GPU_lamp_override_visible(lamp, srl, NULL))
1364                 {
1365                         View3DShadow *shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
1366                         shadow->lamp = lamp;
1367                         BLI_addtail(shadows, shadow);
1368                 }
1369         }
1370 }
1371
1372 static void gpu_update_lamps_shadows_world(Scene *scene, View3D *v3d)
1373 {
1374         ListBase shadows;
1375         Scene *sce_iter;
1376         Base *base;
1377         World *world = scene->world;
1378         SceneRenderLayer *srl = v3d->scenelock ? BLI_findlink(&scene->r.layers, scene->r.actlay) : NULL;
1379         
1380         BLI_listbase_clear(&shadows);
1381         
1382         /* update lamp transform and gather shadow lamps */
1383         for (SETLOOPER(scene, sce_iter, base)) {
1384                 Object *ob = base->object;
1385                 
1386                 if (ob->type == OB_LAMP)
1387                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, ob->lay, &shadows, srl);
1388                 
1389                 if (ob->transflag & OB_DUPLI) {
1390                         DupliObject *dob;
1391                         ListBase *lb = object_duplilist(G.main->eval_ctx, scene, ob);
1392                         
1393                         for (dob = lb->first; dob; dob = dob->next)
1394                                 if (dob->ob->type == OB_LAMP)
1395                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, ob->lay, &shadows, srl);
1396                         
1397                         free_object_duplilist(lb);
1398                 }
1399         }
1400         
1401         /* render shadows after updating all lamps, nested object_duplilist
1402          * don't work correct since it's replacing object matrices */
1403         for (View3DShadow *shadow = shadows.first; shadow; shadow = shadow->next) {
1404                 /* this needs to be done better .. */
1405                 float viewmat[4][4], winmat[4][4];
1406                 ARegion ar = {NULL};
1407                 RegionView3D rv3d = {{{0}}};
1408
1409                 int drawtype = v3d->drawtype;
1410                 int lay = v3d->lay;
1411                 int flag2 = v3d->flag2;
1412
1413                 v3d->drawtype = OB_SOLID;
1414                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
1415                 v3d->flag2 &= ~(V3D_SOLID_TEX | V3D_SHOW_SOLID_MATCAP);
1416                 v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
1417                 
1418                 int winsize;
1419                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
1420
1421                 ar.regiondata = &rv3d;
1422                 ar.regiontype = RGN_TYPE_WINDOW;
1423                 rv3d.persp = RV3D_CAMOB;
1424                 copy_m4_m4(rv3d.winmat, winmat);
1425                 copy_m4_m4(rv3d.viewmat, viewmat);
1426                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
1427                 mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
1428                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
1429
1430                 /* no need to call ED_view3d_draw_offscreen_init since shadow buffers were already updated */
1431                 ED_view3d_draw_offscreen(
1432                             scene, v3d, &ar, winsize, winsize, viewmat, winmat,
1433                             false, false, true,
1434                             NULL, NULL, NULL, NULL);
1435                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
1436                 
1437                 v3d->drawtype = drawtype;
1438                 v3d->lay = lay;
1439                 v3d->flag2 = flag2;
1440         }
1441
1442         BLI_freelistN(&shadows);
1443
1444         /* update world values */
1445         if (world) {
1446                 GPU_mist_update_enable(world->mode & WO_MIST);
1447                 GPU_mist_update_values(world->mistype, world->miststa, world->mistdist, world->misi, &world->horr);
1448                 GPU_horizon_update_color(&world->horr);
1449                 GPU_ambient_update_color(&world->ambr);
1450                 GPU_zenith_update_color(&world->zenr);
1451         }
1452 }
1453
1454 /* *********************** customdata **************** */
1455
1456 CustomDataMask ED_view3d_datamask(const Scene *scene, const View3D *v3d)
1457 {
1458         CustomDataMask mask = 0;
1459         const int drawtype = view3d_effective_drawtype(v3d);
1460
1461         if (ELEM(drawtype, OB_TEXTURE, OB_MATERIAL) ||
1462             ((drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
1463         {
1464                 mask |= CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL;
1465
1466                 if (BKE_scene_use_new_shading_nodes(scene)) {
1467                         if (drawtype == OB_MATERIAL)
1468                                 mask |= CD_MASK_ORCO;
1469                 }
1470                 else {
1471                         if ((scene->gm.matmode == GAME_MAT_GLSL && drawtype == OB_TEXTURE) || 
1472                             (drawtype == OB_MATERIAL))
1473                         {
1474                                 mask |= CD_MASK_ORCO;
1475                         }
1476                 }
1477         }
1478
1479         return mask;
1480 }
1481
1482 /* goes over all modes and view3d settings */
1483 CustomDataMask ED_view3d_screen_datamask(const bScreen *screen)
1484 {
1485         const Scene *scene = screen->scene;
1486         CustomDataMask mask = CD_MASK_BAREMESH;
1487         
1488         /* check if we need tfaces & mcols due to view mode */
1489         for (const ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
1490                 if (sa->spacetype == SPACE_VIEW3D) {
1491                         mask |= ED_view3d_datamask(scene, sa->spacedata.first);
1492                 }
1493         }
1494
1495         return mask;
1496 }
1497
1498 /**
1499  * Shared by #ED_view3d_draw_offscreen and #view3d_main_region_draw_objects
1500  *
1501  * \note \a C and \a grid_unit will be NULL when \a draw_offscreen is set.
1502  * \note Drawing lamps and opengl render uses this, so dont do grease pencil or view widgets here.
1503  */
1504 static void view3d_draw_objects(
1505         const bContext *C,
1506         Scene *scene, View3D *v3d, ARegion *ar,
1507         const char **grid_unit,
1508         const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
1509 {
1510         SceneLayer *sl = C ? CTX_data_scene_layer(C) : BKE_scene_layer_render_active(scene);
1511         RegionView3D *rv3d = ar->regiondata;
1512         Base *base;
1513         const bool do_camera_frame = !draw_offscreen;
1514         const bool draw_grids = !draw_offscreen && (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0;
1515         const bool draw_floor = (rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO);
1516         /* only draw grids after in solid modes, else it hovers over mesh wires */
1517         const bool draw_grids_after = draw_grids && draw_floor && (v3d->drawtype > OB_WIRE) && fx;
1518         bool do_composite_xray = false;
1519         bool xrayclear = true;
1520
1521         if (!draw_offscreen) {
1522                 ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
1523         }
1524
1525         if (rv3d->rflag & RV3D_CLIPPING)
1526                 view3d_draw_clipping(rv3d);
1527
1528         /* set zbuffer after we draw clipping region */
1529         v3d->zbuf = VP_legacy_use_depth(scene, v3d);
1530
1531         if (v3d->zbuf) {
1532                 glEnable(GL_DEPTH_TEST);
1533         }
1534
1535         /* ortho grid goes first, does not write to depth buffer and doesn't need depth test so it will override
1536          * objects if done last */
1537         if (draw_grids) {
1538                 /* needs to be done always, gridview is adjusted in drawgrid() now, but only for ortho views. */
1539                 rv3d->gridview = ED_view3d_grid_scale(scene, v3d, grid_unit);
1540
1541                 if (!draw_floor) {
1542                         ED_region_pixelspace(ar);
1543                         *grid_unit = NULL;  /* drawgrid need this to detect/affect smallest valid unit... */
1544                         VP_legacy_drawgrid(&scene->unit, ar, v3d, grid_unit);
1545                         gpuLoadProjectionMatrix(rv3d->winmat);
1546                         gpuLoadMatrix(rv3d->viewmat);
1547                 }
1548                 else if (!draw_grids_after) {
1549                         VP_legacy_drawfloor(scene, v3d, grid_unit, true);
1550                 }
1551         }
1552
1553         /* important to do before clipping */
1554         if (do_bgpic) {
1555                 view3d_draw_bgpic_test(scene, ar, v3d, false, do_camera_frame);
1556         }
1557
1558         if (rv3d->rflag & RV3D_CLIPPING) {
1559                 ED_view3d_clipping_set(rv3d);
1560         }
1561
1562         /* draw set first */
1563         if (scene->set) {
1564                 const short dflag = DRAW_CONSTCOLOR | DRAW_SCENESET;
1565                 Scene *sce_iter;
1566                 for (SETLOOPER(scene->set, sce_iter, base)) {
1567                         if ((base->flag & BASE_VISIBLED) != 0) {
1568                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
1569                                 draw_object(scene, sl, ar, v3d, base, dflag);
1570
1571                                 if (base->object->transflag & OB_DUPLI) {
1572                                         draw_dupli_objects_color(scene, sl, ar, v3d, base, dflag, TH_UNDEFINED);
1573                                 }
1574                         }
1575                 }
1576
1577                 /* Transp and X-ray afterdraw stuff for sets is done later */
1578         }
1579
1580         if (draw_offscreen) {
1581                 for (base = sl->object_bases.first; base; base = base->next) {
1582                         if ((base->flag & BASE_VISIBLED) != 0) {
1583                                 /* dupli drawing */
1584                                 if (base->object->transflag & OB_DUPLI)
1585                                         draw_dupli_objects(scene, sl, ar, v3d, base);
1586
1587                                 draw_object(scene, sl, ar, v3d, base, 0);
1588                         }
1589                 }
1590         }
1591         else {
1592                 unsigned int lay_used = 0;
1593
1594                 /* then draw not selected and the duplis, but skip editmode object */
1595                 for (base = sl->object_bases.first; base; base = base->next) {
1596                         lay_used |= base->lay;
1597
1598                         if ((base->flag & BASE_VISIBLED) != 0) {
1599
1600                                 /* dupli drawing */
1601                                 if (base->object->transflag & OB_DUPLI) {
1602                                         draw_dupli_objects(scene, sl, ar, v3d, base);
1603                                 }
1604                                 if ((base->flag & BASE_SELECTED) == 0) {
1605                                         if (base->object != scene->obedit)
1606                                                 draw_object(scene, sl, ar, v3d, base, 0);
1607                                 }
1608                         }
1609                 }
1610
1611                 /* mask out localview */
1612                 v3d->lay_used = lay_used & ((1 << 20) - 1);
1613
1614                 /* draw selected and editmode */
1615                 for (base = sl->object_bases.first; base; base = base->next) {
1616                         if ((base->flag & BASE_VISIBLED) != 0) {
1617                                 if (base->object == scene->obedit || (base->flag & BASE_SELECTED)) {
1618                                         draw_object(scene, sl, ar, v3d, base, 0);
1619                                 }
1620                         }
1621                 }
1622         }
1623
1624         /* perspective floor goes last to use scene depth and avoid writing to depth buffer */
1625         if (draw_grids_after) {
1626                 VP_legacy_drawfloor(scene, v3d, grid_unit, false);
1627         }
1628
1629         /* must be before xray draw which clears the depth buffer */
1630         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
1631                 wmWindowManager *wm = (C != NULL) ? CTX_wm_manager(C) : NULL;
1632                 
1633                 /* must be before xray draw which clears the depth buffer */
1634                 if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
1635                 ED_gpencil_draw_view3d(wm, scene, v3d, ar, true);
1636                 if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1637         }
1638
1639         /* transp and X-ray afterdraw stuff */
1640         if (v3d->afterdraw_transp.first)     view3d_draw_transp(scene, sl, ar, v3d);
1641
1642         /* always do that here to cleanup depth buffers if none needed */
1643         if (fx) {
1644                 do_composite_xray = v3d->zbuf && (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first);
1645                 GPU_fx_compositor_setup_XRay_pass(fx, do_composite_xray);
1646         }
1647
1648         if (v3d->afterdraw_xray.first)       view3d_draw_xray(scene, sl, ar, v3d, &xrayclear);
1649         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(scene, sl, ar, v3d, xrayclear);
1650
1651         if (fx && do_composite_xray) {
1652                 GPU_fx_compositor_XRay_resolve(fx);
1653         }
1654
1655         if (!draw_offscreen) {
1656                 ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
1657         }
1658
1659         if (rv3d->rflag & RV3D_CLIPPING)
1660                 ED_view3d_clipping_disable();
1661
1662         /* important to do after clipping */
1663         if (do_bgpic) {
1664                 view3d_draw_bgpic_test(scene, ar, v3d, true, do_camera_frame);
1665         }
1666
1667         /* cleanup */
1668         if (v3d->zbuf) {
1669                 v3d->zbuf = false;
1670                 glDisable(GL_DEPTH_TEST);
1671         }
1672
1673         if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
1674                 GPU_free_images_old();
1675         }
1676 }
1677
1678 /**
1679  * Store values from #RegionView3D, set when drawing.
1680  * This is needed when we draw with to a viewport using a different matrix (offscreen drawing for example).
1681  *
1682  * Values set by #ED_view3d_update_viewmat should be handled here.
1683  */
1684 struct RV3DMatrixStore {
1685         float winmat[4][4];
1686         float viewmat[4][4];
1687         float viewinv[4][4];
1688         float persmat[4][4];
1689         float persinv[4][4];
1690         float viewcamtexcofac[4];
1691         float pixsize;
1692 };
1693
1694 struct RV3DMatrixStore *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
1695 {
1696         struct RV3DMatrixStore *rv3dmat = MEM_mallocN(sizeof(*rv3dmat), __func__);
1697         copy_m4_m4(rv3dmat->winmat, rv3d->winmat);
1698         copy_m4_m4(rv3dmat->viewmat, rv3d->viewmat);
1699         copy_m4_m4(rv3dmat->persmat, rv3d->persmat);
1700         copy_m4_m4(rv3dmat->persinv, rv3d->persinv);
1701         copy_m4_m4(rv3dmat->viewinv, rv3d->viewinv);
1702         copy_v4_v4(rv3dmat->viewcamtexcofac, rv3d->viewcamtexcofac);
1703         rv3dmat->pixsize = rv3d->pixsize;
1704         return (void *)rv3dmat;
1705 }
1706
1707 void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, struct RV3DMatrixStore *rv3dmat_pt)
1708 {
1709         struct RV3DMatrixStore *rv3dmat = rv3dmat_pt;
1710         copy_m4_m4(rv3d->winmat, rv3dmat->winmat);
1711         copy_m4_m4(rv3d->viewmat, rv3dmat->viewmat);
1712         copy_m4_m4(rv3d->persmat, rv3dmat->persmat);
1713         copy_m4_m4(rv3d->persinv, rv3dmat->persinv);
1714         copy_m4_m4(rv3d->viewinv, rv3dmat->viewinv);
1715         copy_v4_v4(rv3d->viewcamtexcofac, rv3dmat->viewcamtexcofac);
1716         rv3d->pixsize = rv3dmat->pixsize;
1717 }
1718
1719 /**
1720  * \note The info that this uses is updated in #ED_refresh_viewport_fps,
1721  * which currently gets called during #SCREEN_OT_animation_step.
1722  */
1723 void ED_scene_draw_fps(Scene *scene, const rcti *rect)
1724 {
1725         ScreenFrameRateInfo *fpsi = scene->fps_info;
1726         char printable[16];
1727         
1728         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
1729                 return;
1730         
1731         printable[0] = '\0';
1732         
1733 #if 0
1734         /* this is too simple, better do an average */
1735         fps = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime))
1736 #else
1737         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime));
1738         
1739         float fps = 0.0f;
1740         int tot = 0;
1741         for (int i = 0; i < REDRAW_FRAME_AVERAGE; i++) {
1742                 if (fpsi->redrawtimes_fps[i]) {
1743                         fps += fpsi->redrawtimes_fps[i];
1744                         tot++;
1745                 }
1746         }
1747         if (tot) {
1748                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
1749                 
1750                 //fpsi->redrawtime_index++;
1751                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
1752                 //      fpsi->redrawtime = 0;
1753                 
1754                 fps = fps / tot;
1755         }
1756 #endif
1757
1758         const int font_id = BLF_default();
1759
1760         /* is this more than half a frame behind? */
1761         if (fps + 0.5f < (float)(FPS)) {
1762                 UI_FontThemeColor(font_id, TH_REDALERT);
1763                 BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %.2f"), fps);
1764         }
1765         else {
1766                 UI_FontThemeColor(font_id, TH_TEXT_HI);
1767                 BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %i"), (int)(fps + 0.5f));
1768         }
1769
1770 #ifdef WITH_INTERNATIONAL
1771         BLF_draw_default(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
1772 #else
1773         BLF_draw_default_ascii(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
1774 #endif
1775 }
1776
1777 static bool view3d_main_region_do_render_draw(Scene *scene)
1778 {
1779         RenderEngineType *type = RE_engines_find(scene->r.engine);
1780
1781         return (type && type->view_update && type->render_to_view);
1782 }
1783
1784 bool ED_view3d_calc_render_border(Scene *scene, View3D *v3d, ARegion *ar, rcti *rect)
1785 {
1786         RegionView3D *rv3d = ar->regiondata;
1787         bool use_border;
1788
1789         /* test if there is a 3d view rendering */
1790         if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene))
1791                 return false;
1792
1793         /* test if there is a border render */
1794         if (rv3d->persp == RV3D_CAMOB)
1795                 use_border = (scene->r.mode & R_BORDER) != 0;
1796         else
1797                 use_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
1798         
1799         if (!use_border)
1800                 return false;
1801
1802         /* compute border */
1803         if (rv3d->persp == RV3D_CAMOB) {
1804                 rctf viewborder;
1805                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
1806
1807                 rect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
1808                 rect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
1809                 rect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
1810                 rect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
1811         }
1812         else {
1813                 rect->xmin = v3d->render_border.xmin * ar->winx;
1814                 rect->xmax = v3d->render_border.xmax * ar->winx;
1815                 rect->ymin = v3d->render_border.ymin * ar->winy;
1816                 rect->ymax = v3d->render_border.ymax * ar->winy;
1817         }
1818
1819         BLI_rcti_translate(rect, ar->winrct.xmin, ar->winrct.ymin);
1820         BLI_rcti_isect(&ar->winrct, rect, rect);
1821
1822         return true;
1823 }
1824
1825 /**
1826   * IMPORTANT: this is deprecated, any changes made in this function should
1827   * be mirrored in view3d_draw_render_draw() in view3d_draw.c
1828   */
1829 static bool view3d_main_region_draw_engine(const bContext *C, Scene *scene,
1830                                          ARegion *ar, View3D *v3d,
1831                                          bool clip_border, const rcti *border_rect)
1832 {
1833         RegionView3D *rv3d = ar->regiondata;
1834         RenderEngineType *type;
1835         GLint scissor[4];
1836
1837         /* create render engine */
1838         if (!rv3d->render_engine) {
1839                 RenderEngine *engine;
1840
1841                 type = RE_engines_find(scene->r.engine);
1842
1843                 if (!(type->view_update && type->render_to_view))
1844                         return false;
1845
1846                 engine = RE_engine_create_ex(type, true);
1847
1848                 engine->tile_x = scene->r.tilex;
1849                 engine->tile_y = scene->r.tiley;
1850
1851                 type->view_update(engine, C);
1852
1853                 rv3d->render_engine = engine;
1854         }
1855
1856         /* setup view matrices */
1857         VP_legacy_view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
1858
1859         /* background draw */
1860         ED_region_pixelspace(ar);
1861
1862         if (clip_border) {
1863                 /* for border draw, we only need to clear a subset of the 3d view */
1864                 if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
1865                         glGetIntegerv(GL_SCISSOR_BOX, scissor);
1866                         glScissor(border_rect->xmin, border_rect->ymin,
1867                                   BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
1868                 }
1869                 else {
1870                         return false;
1871                 }
1872         }
1873
1874         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
1875         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1876
1877         if (v3d->flag & V3D_DISPBGPICS)
1878                 view3d_draw_bgpic_test(scene, ar, v3d, false, true);
1879         else
1880                 imm_draw_checker_box(0, 0, ar->winx, ar->winy);
1881
1882         /* render result draw */
1883         type = rv3d->render_engine->type;
1884         type->render_to_view(rv3d->render_engine, C);
1885
1886         if (v3d->flag & V3D_DISPBGPICS)
1887                 view3d_draw_bgpic_test(scene, ar, v3d, true, true);
1888
1889         if (clip_border) {
1890                 /* restore scissor as it was before */
1891                 glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
1892         }
1893
1894         return true;
1895 }
1896
1897 static void view3d_main_region_draw_engine_info(View3D *v3d, RegionView3D *rv3d, ARegion *ar, bool render_border)
1898 {
1899         float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
1900
1901         if (!rv3d->render_engine || !rv3d->render_engine->text[0])
1902                 return;
1903         
1904         if (render_border) {
1905                 /* draw darkened background color. no alpha because border render does
1906                  * partial redraw and will not redraw the region behind this info bar */
1907                 float alpha = 1.0f - fill_color[3];
1908                 Camera *camera = ED_view3d_camera_data_get(v3d, rv3d);
1909
1910                 if (camera) {
1911                         if (camera->flag & CAM_SHOWPASSEPARTOUT) {
1912                                 alpha *= (1.0f - camera->passepartalpha);
1913                         }
1914                 }
1915
1916                 UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
1917                 mul_v3_fl(fill_color, alpha);
1918                 fill_color[3] = 1.0f;
1919         }
1920
1921         ED_region_info_draw(ar, rv3d->render_engine->text, fill_color, true);
1922 }
1923
1924 #ifdef WITH_GAMEENGINE
1925 static void update_lods(Scene *scene, float camera_pos[3])
1926 {
1927         Scene *sce_iter;
1928         Base *base;
1929
1930         for (SETLOOPER(scene, sce_iter, base)) {
1931                 Object *ob = base->object;
1932                 BKE_object_lod_update(ob, camera_pos);
1933         }
1934 }
1935 #endif
1936
1937 static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, SceneLayer *sl, View3D *v3d,
1938                                           ARegion *ar, const char **grid_unit)
1939 {
1940         wmWindow *win = CTX_wm_window(C);
1941         RegionView3D *rv3d = ar->regiondata;
1942         unsigned int lay_used = v3d->lay_used;
1943         
1944         /* post processing */
1945         bool do_compositing = false;
1946         
1947         /* shadow buffers, before we setup matrices */
1948         if (draw_glsl_material(scene, sl, NULL, v3d, v3d->drawtype))
1949                 gpu_update_lamps_shadows_world(scene, v3d);
1950
1951         /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
1952         if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
1953                 rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
1954                 GPU_default_lights();
1955         }
1956
1957         /* setup the view matrix */
1958         if (VP_legacy_view3d_stereo3d_active(C, scene, v3d, rv3d))
1959                 VP_legacy_view3d_stereo3d_setup(scene, v3d, ar);
1960         else
1961                 VP_legacy_view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
1962
1963         rv3d->rflag &= ~RV3D_IS_GAME_ENGINE;
1964 #ifdef WITH_GAMEENGINE
1965         if (STREQ(scene->r.engine, RE_engine_id_BLENDER_GAME)) {
1966                 rv3d->rflag |= RV3D_IS_GAME_ENGINE;
1967
1968                 /* Make sure LoDs are up to date */
1969                 update_lods(scene, rv3d->viewinv[3]);
1970         }
1971 #endif
1972
1973         /* framebuffer fx needed, we need to draw offscreen first */
1974         if (v3d->fx_settings.fx_flag && v3d->drawtype >= OB_SOLID) {
1975                 BKE_screen_gpu_fx_validate(&v3d->fx_settings);
1976                 GPUFXSettings fx_settings = v3d->fx_settings;
1977                 if (!rv3d->compositor)
1978                         rv3d->compositor = GPU_fx_compositor_create();
1979                 
1980                 if (rv3d->persp == RV3D_CAMOB && v3d->camera)
1981                         BKE_camera_to_gpu_dof(v3d->camera, &fx_settings);
1982                 else {
1983                         fx_settings.dof = NULL;
1984                 }
1985
1986                 do_compositing = GPU_fx_compositor_initialize_passes(rv3d->compositor, &ar->winrct, &ar->drawrct, &fx_settings);
1987         }
1988         
1989         /* enables anti-aliasing for 3D view drawing */
1990         if (win->multisamples != USER_MULTISAMPLE_NONE) {
1991                 glEnable(GL_MULTISAMPLE);
1992         }
1993
1994         /* main drawing call */
1995         view3d_draw_objects(C, scene, v3d, ar, grid_unit, true, false, do_compositing ? rv3d->compositor : NULL);
1996
1997         /* draw depth culled manipulators - manipulators need to be updated *after* view matrix was set up */
1998         /* TODO depth culling manipulators is not yet supported, just drawing _3D here, should
1999          * later become _IN_SCENE (and draw _3D separate) */
2000         WM_manipulatormap_draw(ar->manipulator_map, C, WM_MANIPULATORMAP_DRAWSTEP_3D);
2001
2002         /* post process */
2003         if (do_compositing) {
2004                 GPU_fx_do_composite_pass(rv3d->compositor, rv3d->winmat, rv3d->is_persp, scene, NULL);
2005         }
2006
2007         /* Disable back anti-aliasing */
2008         if (win->multisamples != USER_MULTISAMPLE_NONE) {
2009                 glDisable(GL_MULTISAMPLE);
2010         }
2011
2012         if (v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
2013                 /* find header and force tag redraw */
2014                 ScrArea *sa = CTX_wm_area(C);
2015                 ARegion *ar_header = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
2016                 ED_region_tag_redraw(ar_header); /* can be NULL */
2017         }
2018
2019         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2020                 BDR_drawSketch(C);
2021         }
2022 }
2023
2024 static void view3d_main_region_draw_info(const bContext *C, Scene *scene,
2025                                        ARegion *ar, View3D *v3d,
2026                                        const char *grid_unit, bool render_border)
2027 {
2028         SceneLayer *sl = CTX_data_scene_layer(C);
2029         wmWindowManager *wm = CTX_wm_manager(C);
2030         RegionView3D *rv3d = ar->regiondata;
2031         rcti rect;
2032         
2033         /* local coordinate visible rect inside region, to accomodate overlapping ui */
2034         ED_region_visible_rect(ar, &rect);
2035
2036         if (rv3d->persp == RV3D_CAMOB) {
2037                 VP_drawviewborder(scene, ar, v3d);
2038         }
2039         else if (v3d->flag2 & V3D_RENDER_BORDER) {
2040                 VP_drawrenderborder(ar, v3d);
2041         }
2042
2043         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2044                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2045                 ED_gpencil_draw_view3d(wm, scene, v3d, ar, false);
2046         }
2047
2048         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2049                 VP_legacy_drawcursor(scene, sl, ar, v3d); /* 3D cursor */
2050
2051                 if (U.uiflag & USER_SHOW_ROTVIEWICON)
2052                         VP_legacy_draw_view_axis(rv3d, &rect);
2053                 else
2054                         draw_view_icon(rv3d, &rect);
2055
2056                 if (U.uiflag & USER_DRAWVIEWINFO) {
2057                         Object *ob = OBACT_NEW;
2058                         VP_legacy_draw_selected_name(scene, ob, &rect);
2059                 }
2060         }
2061
2062         if (rv3d->render_engine) {
2063                 view3d_main_region_draw_engine_info(v3d, rv3d, ar, render_border);
2064                 return;
2065         }
2066
2067         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2068                 if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_no_scrub(wm)) {
2069                         ED_scene_draw_fps(scene, &rect);
2070                 }
2071                 else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
2072                         VP_legacy_draw_viewport_name(ar, v3d, &rect);
2073                 }
2074
2075                 if (grid_unit) { /* draw below the viewport name */
2076                         char numstr[32] = "";
2077
2078                         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
2079                         if (v3d->grid != 1.0f) {
2080                                 BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
2081                         }
2082
2083                         BLF_draw_default_ascii(rect.xmin + U.widget_unit,
2084                                                rect.ymax - (USER_SHOW_VIEWPORTNAME ? 2 * U.widget_unit : U.widget_unit), 0.0f,
2085                                                numstr[0] ? numstr : grid_unit, sizeof(numstr));
2086                 }
2087         }
2088 }
2089
2090 void view3d_main_region_draw_legacy(const bContext *C, ARegion *ar)
2091 {
2092         Scene *scene = CTX_data_scene(C);
2093         SceneLayer *sl = CTX_data_scene_layer(C);
2094         View3D *v3d = CTX_wm_view3d(C);
2095         const char *grid_unit = NULL;
2096         rcti border_rect;
2097
2098         /* if we only redraw render border area, skip opengl draw and also
2099          * don't do scissor because it's already set */
2100         bool render_border = ED_view3d_calc_render_border(scene, v3d, ar, &border_rect);
2101         bool clip_border = (render_border && !BLI_rcti_compare(&ar->drawrct, &border_rect));
2102
2103         gpuPushProjectionMatrix();
2104         gpuLoadIdentityProjectionMatrix();
2105         gpuPushMatrix();
2106         gpuLoadIdentity();
2107
2108         /* draw viewport using opengl */
2109         if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene) || clip_border) {
2110                 VP_view3d_main_region_clear(scene, v3d, ar); /* background */
2111                 view3d_main_region_draw_objects(C, scene, sl, v3d, ar, &grid_unit);
2112
2113                 if (G.debug & G_DEBUG_SIMDATA)
2114                         draw_sim_debug_data(scene, v3d, ar);
2115
2116                 glDisable(GL_DEPTH_TEST);
2117                 ED_region_pixelspace(ar);
2118         }
2119
2120         /* draw viewport using external renderer */
2121         if (v3d->drawtype == OB_RENDER)
2122                 view3d_main_region_draw_engine(C, scene, ar, v3d, clip_border, &border_rect);
2123
2124         VP_legacy_view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
2125         glClear(GL_DEPTH_BUFFER_BIT);
2126
2127         WM_manipulatormap_draw(ar->manipulator_map, C, WM_MANIPULATORMAP_DRAWSTEP_2D);
2128
2129         ED_region_pixelspace(ar);
2130
2131         view3d_main_region_draw_info(C, scene, ar, v3d, grid_unit, render_border);
2132
2133         gpuPopProjectionMatrix();
2134         gpuPopMatrix();
2135
2136         v3d->flag |= V3D_INVALID_BACKBUF;
2137
2138         BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_transp));
2139         BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xray));
2140         BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xraytransp));
2141 }
2142
2143
2144 /* -------------------------------------------------------------------- */
2145
2146 /** \name Deprecated Interface
2147  *
2148  * New viewport sometimes has a check for new/old viewport code.
2149  * Use these functions so new viewport can *optionally* call.
2150  *
2151  * \{ */
2152
2153
2154 void VP_deprecated_view3d_draw_objects(
2155         const bContext *C,
2156         Scene *scene, View3D *v3d, ARegion *ar,
2157         const char **grid_unit,
2158         const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
2159 {
2160         view3d_draw_objects(C, scene, v3d, ar, grid_unit, do_bgpic, draw_offscreen, fx);
2161 }
2162
2163 void VP_deprecated_gpu_update_lamps_shadows_world(Scene *scene, View3D *v3d)
2164 {
2165         gpu_update_lamps_shadows_world(scene, v3d);
2166 }
2167
2168 /** \} */