Merge branch 'blender2.7'
[blender.git] / source / blender / editors / render / render_opengl.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  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/editors/render/render_opengl.c
26  *  \ingroup edrend
27  */
28
29
30 #include <math.h>
31 #include <string.h>
32 #include <stddef.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_camera_types.h"
37 #include "BLI_math.h"
38 #include "BLI_math_color_blend.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_utildefines.h"
41 #include "BLI_threads.h"
42 #include "BLI_task.h"
43
44 #include "DNA_scene_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_gpencil_types.h"
47
48 #include "BKE_camera.h"
49 #include "BKE_context.h"
50 #include "BKE_global.h"
51 #include "BKE_image.h"
52 #include "BKE_main.h"
53 #include "BKE_report.h"
54 #include "BKE_scene.h"
55 #include "BKE_sequencer.h"
56 #include "BKE_writeavi.h"
57
58 #include "DEG_depsgraph.h"
59
60 #include "DRW_engine.h"
61
62 #include "WM_api.h"
63 #include "WM_types.h"
64
65 #include "ED_screen.h"
66 #include "ED_view3d.h"
67 #include "ED_gpencil.h"
68
69 #include "RE_pipeline.h"
70 #include "IMB_imbuf_types.h"
71 #include "IMB_imbuf.h"
72 #include "IMB_colormanagement.h"
73
74 #include "RNA_access.h"
75 #include "RNA_define.h"
76
77 #include "GPU_framebuffer.h"
78 #include "GPU_glew.h"
79 #include "GPU_matrix.h"
80
81 #include "render_intern.h"
82
83 /* Define this to get timing information. */
84 // #undef DEBUG_TIME
85
86 #ifdef DEBUG_TIME
87 #  include "PIL_time.h"
88 #endif
89
90 // TODO(sergey): Find better approximation of the scheduled frames.
91 // For really highres renders it might fail still.
92 #define MAX_SCHEDULED_FRAMES 8
93
94 typedef struct OGLRender {
95         Main *bmain;
96         Render *re;
97         Scene *scene;
98         WorkSpace *workspace;
99         ViewLayer *view_layer;
100         Depsgraph *depsgraph;
101
102         View3D *v3d;
103         RegionView3D *rv3d;
104         ARegion *ar;
105
106         ScrArea *prevsa;
107         ARegion *prevar;
108
109         int views_len;  /* multi-view views */
110
111         bool is_sequencer;
112         SpaceSeq *sseq;
113         struct {
114                 ImBuf **ibufs_arr;
115         } seq_data;
116
117
118         Image *ima;
119         ImageUser iuser;
120
121         GPUOffScreen *ofs;
122         int ofs_samples;
123         bool ofs_full_samples;
124         int sizex, sizey;
125         int write_still;
126
127         ReportList *reports;
128         bMovieHandle *mh;
129         int cfrao, nfra;
130
131         int totvideos;
132
133         /* quick lookup */
134         int view_id;
135
136         /* wm vars for timer and progress cursor */
137         wmWindowManager *wm;
138         wmWindow *win;
139
140         wmTimer *timer; /* use to check if running modal or not (invoke'd or exec'd)*/
141         void **movie_ctx_arr;
142
143         TaskScheduler *task_scheduler;
144         TaskPool *task_pool;
145         bool pool_ok;
146         bool is_animation;
147         SpinLock reports_lock;
148         unsigned int num_scheduled_frames;
149         ThreadMutex task_mutex;
150         ThreadCondition task_condition;
151
152 #ifdef DEBUG_TIME
153         double time_start;
154 #endif
155 } OGLRender;
156
157 static bool screen_opengl_is_multiview(OGLRender *oglrender)
158 {
159         View3D *v3d = oglrender->v3d;
160         RegionView3D *rv3d = oglrender->rv3d;
161         RenderData *rd = &oglrender->scene->r;
162
163         if ((rd == NULL) || ((!oglrender->is_sequencer) && ((rv3d == NULL) || (v3d == NULL))))
164                 return false;
165
166         return (rd->scemode & R_MULTIVIEW) && ((oglrender->is_sequencer) || (rv3d->persp == RV3D_CAMOB && v3d->camera));
167 }
168
169 static void screen_opengl_views_setup(OGLRender *oglrender)
170 {
171         RenderResult *rr;
172         RenderView *rv;
173         SceneRenderView *srv;
174         bool is_multiview;
175         Object *camera;
176         View3D *v3d = oglrender->v3d;
177
178         RenderData *rd = &oglrender->scene->r;
179
180         rr = RE_AcquireResultWrite(oglrender->re);
181
182         is_multiview = screen_opengl_is_multiview(oglrender);
183
184         if (!is_multiview) {
185                 /* we only have one view when multiview is off */
186                 rv = rr->views.first;
187
188                 if (rv == NULL) {
189                         rv = MEM_callocN(sizeof(RenderView), "new opengl render view");
190                         BLI_addtail(&rr->views, rv);
191                 }
192
193                 while (rv->next) {
194                         RenderView *rv_del = rv->next;
195                         BLI_remlink(&rr->views, rv_del);
196
197                         if (rv_del->rectf)
198                                 MEM_freeN(rv_del->rectf);
199
200                         if (rv_del->rectz)
201                                 MEM_freeN(rv_del->rectz);
202
203                         if (rv_del->rect32)
204                                 MEM_freeN(rv_del->rect32);
205
206                         MEM_freeN(rv_del);
207                 }
208         }
209         else {
210                 if (!oglrender->is_sequencer)
211                         RE_SetOverrideCamera(oglrender->re, V3D_CAMERA_SCENE(oglrender->scene, v3d));
212
213                 /* remove all the views that are not needed */
214                 rv = rr->views.last;
215                 while (rv) {
216                         srv = BLI_findstring(&rd->views, rv->name, offsetof(SceneRenderView, name));
217                         if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
218                                 rv = rv->prev;
219                         }
220                         else {
221                                 RenderView *rv_del = rv;
222                                 rv  = rv_del->prev;
223
224                                 BLI_remlink(&rr->views, rv_del);
225
226                                 if (rv_del->rectf)
227                                         MEM_freeN(rv_del->rectf);
228
229                                 if (rv_del->rectz)
230                                         MEM_freeN(rv_del->rectz);
231
232                                 if (rv_del->rect32)
233                                         MEM_freeN(rv_del->rect32);
234
235                                 MEM_freeN(rv_del);
236                         }
237                 }
238
239                 /* create all the views that are needed */
240                 for (srv = rd->views.first; srv; srv = srv->next) {
241                         if (BKE_scene_multiview_is_render_view_active(rd, srv) == false)
242                                 continue;
243
244                         rv = BLI_findstring(&rr->views, srv->name, offsetof(SceneRenderView, name));
245
246                         if (rv == NULL) {
247                                 rv = MEM_callocN(sizeof(RenderView), "new opengl render view");
248                                 BLI_strncpy(rv->name, srv->name, sizeof(rv->name));
249                                 BLI_addtail(&rr->views, rv);
250                         }
251                 }
252         }
253
254         if (!(is_multiview && BKE_scene_multiview_is_stereo3d(rd)))
255                 oglrender->iuser.flag &= ~IMA_SHOW_STEREO;
256
257         /* will only work for non multiview correctly */
258         if (v3d) {
259                 camera = BKE_camera_multiview_render(oglrender->scene, v3d->camera, "new opengl render view");
260                 BKE_render_result_stamp_info(oglrender->scene, camera, rr, false);
261         }
262         else {
263                 BKE_render_result_stamp_info(oglrender->scene, oglrender->scene->camera, rr, false);
264         }
265
266         RE_ReleaseResult(oglrender->re);
267 }
268
269 static void screen_opengl_render_doit(const bContext *C, OGLRender *oglrender, RenderResult *rr)
270 {
271         Depsgraph *depsgraph = CTX_data_depsgraph(C);
272         ViewLayer *view_layer = CTX_data_view_layer(C);
273         Scene *scene = oglrender->scene;
274         ARegion *ar = oglrender->ar;
275         View3D *v3d = oglrender->v3d;
276         RegionView3D *rv3d = oglrender->rv3d;
277         Object *camera = NULL;
278         int sizex = oglrender->sizex;
279         int sizey = oglrender->sizey;
280         const short view_context = (v3d != NULL);
281         bool draw_sky = (scene->r.alphamode == R_ADDSKY);
282         float *rectf = NULL;
283         const char *viewname = RE_GetActiveRenderView(oglrender->re);
284         ImBuf *ibuf_result = NULL;
285
286         if (oglrender->is_sequencer) {
287                 SpaceSeq *sseq = oglrender->sseq;
288                 struct bGPdata *gpd = (sseq && (sseq->flag & SEQ_SHOW_GPENCIL)) ? sseq->gpd : NULL;
289
290                 /* use pre-calculated ImBuf (avoids deadlock), see: */
291                 ImBuf *ibuf = oglrender->seq_data.ibufs_arr[oglrender->view_id];
292
293                 if (ibuf) {
294                         ImBuf *out = IMB_dupImBuf(ibuf);
295                         IMB_freeImBuf(ibuf);
296                         /* OpenGL render is considered to be preview and should be
297                          * as fast as possible. So currently we're making sure sequencer
298                          * result is always byte to simplify color management pipeline.
299                          *
300                          * TODO(sergey): In the case of output to float container (EXR)
301                          * it actually makes sense to keep float buffer instead.
302                          */
303                         if (out->rect_float != NULL) {
304                                 IMB_rect_from_float(out);
305                                 imb_freerectfloatImBuf(out);
306                         }
307                         BLI_assert((oglrender->sizex == ibuf->x) && (oglrender->sizey == ibuf->y));
308                         RE_render_result_rect_from_ibuf(rr, &scene->r, out, oglrender->view_id);
309                         IMB_freeImBuf(out);
310                 }
311                 else if (gpd) {
312                         /* If there are no strips, Grease Pencil still needs a buffer to draw on */
313                         ImBuf *out = IMB_allocImBuf(oglrender->sizex, oglrender->sizey, 32, IB_rect);
314                         RE_render_result_rect_from_ibuf(rr, &scene->r, out, oglrender->view_id);
315                         IMB_freeImBuf(out);
316                 }
317
318                 if (gpd) {
319                         int i;
320                         unsigned char *gp_rect;
321                         unsigned char *render_rect = (unsigned char *)RE_RenderViewGetById(rr, oglrender->view_id)->rect32;
322
323                         DRW_opengl_context_enable();
324                         GPU_offscreen_bind(oglrender->ofs, true);
325
326                         GPU_clear_color(0.0f, 0.0f, 0.0f, 0.0f);
327                         GPU_clear(GPU_COLOR_BIT | GPU_DEPTH_BIT);
328
329                         wmOrtho2(0, sizex, 0, sizey);
330                         GPU_matrix_translate_2f(sizex / 2, sizey / 2);
331
332                         G.f |= G_RENDER_OGL;
333                         ED_gpencil_draw_ex(
334                                 view_layer, rv3d, scene, gpd, sizex, sizey, scene->r.cfra, SPACE_SEQ);
335                         G.f &= ~G_RENDER_OGL;
336
337                         gp_rect = MEM_mallocN(sizex * sizey * sizeof(unsigned char) * 4, "offscreen rect");
338                         GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, gp_rect);
339
340                         for (i = 0; i < sizex * sizey * 4; i += 4) {
341                                 blend_color_mix_byte(&render_rect[i], &render_rect[i], &gp_rect[i]);
342                         }
343                         GPU_offscreen_unbind(oglrender->ofs, true);
344                         DRW_opengl_context_disable();
345
346                         MEM_freeN(gp_rect);
347                 }
348         }
349         else {
350                 /* shouldnt suddenly give errors mid-render but possible */
351                 char err_out[256] = "unknown";
352                 ImBuf *ibuf_view;
353                 const int alpha_mode = (draw_sky) ? R_ADDSKY : R_ALPHAPREMUL;
354
355                 unsigned int draw_flags = V3D_OFSDRAW_NONE;
356                 draw_flags |= (oglrender->ofs_full_samples) ? V3D_OFSDRAW_USE_FULL_SAMPLE : 0;
357
358                 if (view_context) {
359                         ibuf_view = ED_view3d_draw_offscreen_imbuf(
360                                depsgraph, scene, v3d->shading.type,
361                                v3d, ar, sizex, sizey,
362                                IB_rectfloat, draw_flags, alpha_mode, oglrender->ofs_samples, viewname,
363                                oglrender->ofs, err_out);
364
365                         /* for stamp only */
366                         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
367                                 camera = BKE_camera_multiview_render(oglrender->scene, v3d->camera, viewname);
368                         }
369                 }
370                 else {
371                         draw_flags |= V3D_OFSDRAW_USE_GPENCIL;
372                         ibuf_view = ED_view3d_draw_offscreen_imbuf_simple(
373                                 depsgraph, scene, OB_SOLID,
374                                 scene->camera, oglrender->sizex, oglrender->sizey,
375                                 IB_rectfloat, draw_flags,
376                                 alpha_mode, oglrender->ofs_samples, viewname,
377                                 oglrender->ofs, err_out);
378                         camera = scene->camera;
379                 }
380
381                 if (ibuf_view) {
382                         ibuf_result = ibuf_view;
383                         rectf = (float *)ibuf_view->rect_float;
384                 }
385                 else {
386                         fprintf(stderr, "%s: failed to get buffer, %s\n", __func__, err_out);
387                 }
388         }
389
390         if (ibuf_result != NULL) {
391                 if ((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW)) {
392                         BKE_image_stamp_buf(scene, camera, NULL, NULL, rectf, rr->rectx, rr->recty, 4);
393                 }
394                 RE_render_result_rect_from_ibuf(rr, &scene->r, ibuf_result, oglrender->view_id);
395                 IMB_freeImBuf(ibuf_result);
396         }
397 }
398
399 static void screen_opengl_render_write(OGLRender *oglrender)
400 {
401         Scene *scene = oglrender->scene;
402         RenderResult *rr;
403         bool ok;
404         char name[FILE_MAX];
405
406         rr = RE_AcquireResultRead(oglrender->re);
407
408         BKE_image_path_from_imformat(
409                 name, scene->r.pic, BKE_main_blendfile_path(oglrender->bmain), scene->r.cfra,
410                 &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, false, NULL);
411
412         /* write images as individual images or stereo */
413         BKE_render_result_stamp_info(scene, scene->camera, rr, false);
414         ok = RE_WriteRenderViewsImage(oglrender->reports, rr, scene, false, name);
415
416         RE_ReleaseResultImage(oglrender->re);
417
418         if (ok) printf("OpenGL Render written to '%s'\n", name);
419         else printf("OpenGL Render failed to write '%s'\n", name);
420 }
421
422 static void UNUSED_FUNCTION(addAlphaOverFloat)(float dest[4], const float source[4])
423 {
424         /* d = s + (1-alpha_s)d*/
425         float mul;
426
427         mul = 1.0f - source[3];
428
429         dest[0] = (mul * dest[0]) + source[0];
430         dest[1] = (mul * dest[1]) + source[1];
431         dest[2] = (mul * dest[2]) + source[2];
432         dest[3] = (mul * dest[3]) + source[3];
433
434 }
435
436 static void screen_opengl_render_apply(const bContext *C, OGLRender *oglrender)
437 {
438         RenderResult *rr;
439         RenderView *rv;
440         int view_id;
441         ImBuf *ibuf;
442         void *lock;
443
444         if (oglrender->is_sequencer) {
445                 Scene *scene = oglrender->scene;
446
447                 SeqRenderData context;
448                 SpaceSeq *sseq = oglrender->sseq;
449                 int chanshown = sseq ? sseq->chanshown : 0;
450
451                 BKE_sequencer_new_render_data(
452                         oglrender->bmain, oglrender->depsgraph, scene,
453                         oglrender->sizex, oglrender->sizey, 100.0f, false,
454                         &context);
455
456                 for (view_id = 0; view_id < oglrender->views_len; view_id++) {
457                         context.view_id = view_id;
458                         context.gpu_offscreen = oglrender->ofs;
459                         context.gpu_full_samples = oglrender->ofs_full_samples;
460
461                         oglrender->seq_data.ibufs_arr[view_id] = BKE_sequencer_give_ibuf(&context, CFRA, chanshown);
462                 }
463         }
464
465         rr = RE_AcquireResultRead(oglrender->re);
466         for (rv = rr->views.first, view_id = 0; rv; rv = rv->next, view_id++) {
467                 BLI_assert(view_id < oglrender->views_len);
468                 RE_SetActiveRenderView(oglrender->re, rv->name);
469                 oglrender->view_id = view_id;
470                 /* render composite */
471                 screen_opengl_render_doit(C, oglrender, rr);
472         }
473
474         RE_ReleaseResult(oglrender->re);
475
476         ibuf = BKE_image_acquire_ibuf(oglrender->ima, &oglrender->iuser, &lock);
477         if (ibuf) {
478                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
479         }
480         BKE_image_release_ibuf(oglrender->ima, ibuf, lock);
481
482         if (oglrender->write_still) {
483                 screen_opengl_render_write(oglrender);
484         }
485 }
486
487 static bool screen_opengl_fullsample_enabled(Scene *scene)
488 {
489         if (scene->r.scemode & R_FULL_SAMPLE) {
490                 return true;
491         }
492         else {
493                 /* XXX TODO:
494                  * Technically if the hardware supports MSAA we could keep using Blender 2.7x approach.
495                  * However anti-aliasing without full_sample is not playing well even in 2.7x.
496                  *
497                  * For example, if you enable depth of field, there is aliasing, even if the viewport is fine.
498                  * For 2.8x this is more complicated because so many things rely on shader.
499                  * So until we fix the gpu_framebuffer anti-aliasing suupport we need to force full sample.
500                  */
501                 return true;
502         }
503 }
504
505 static bool screen_opengl_render_init(bContext *C, wmOperator *op)
506 {
507         /* new render clears all callbacks */
508         wmWindowManager *wm = CTX_wm_manager(C);
509         wmWindow *win = CTX_wm_window(C);
510         WorkSpace *workspace = CTX_wm_workspace(C);
511
512         Scene *scene = CTX_data_scene(C);
513         ScrArea *prevsa = CTX_wm_area(C);
514         ARegion *prevar = CTX_wm_region(C);
515         GPUOffScreen *ofs;
516         OGLRender *oglrender;
517         int sizex, sizey;
518         const int samples = (scene->r.mode & R_OSA) ? scene->r.osa : 0;
519         const bool full_samples = (samples != 0) && screen_opengl_fullsample_enabled(scene);
520         bool is_view_context = RNA_boolean_get(op->ptr, "view_context");
521         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
522         const bool is_sequencer = RNA_boolean_get(op->ptr, "sequencer");
523         const bool is_write_still = RNA_boolean_get(op->ptr, "write_still");
524         char err_out[256] = "unknown";
525
526         if (G.background) {
527                 BKE_report(op->reports, RPT_ERROR, "Cannot use OpenGL render in background mode (no opengl context)");
528                 return false;
529         }
530
531         /* only one render job at a time */
532         if (WM_jobs_test(wm, scene, WM_JOB_TYPE_RENDER))
533                 return false;
534
535         if (is_sequencer) {
536                 is_view_context = false;
537         }
538         else {
539                 /* ensure we have a 3d view */
540                 if (!ED_view3d_context_activate(C)) {
541                         RNA_boolean_set(op->ptr, "view_context", false);
542                         is_view_context = false;
543                 }
544
545                 if (!is_view_context && scene->camera == NULL) {
546                         BKE_report(op->reports, RPT_ERROR, "Scene has no camera");
547                         return false;
548                 }
549         }
550
551         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
552                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
553                 return false;
554         }
555
556         /* stop all running jobs, except screen one. currently previews frustrate Render */
557         WM_jobs_kill_all_except(wm, CTX_wm_screen(C));
558
559         /* create offscreen buffer */
560         sizex = (scene->r.size * scene->r.xsch) / 100;
561         sizey = (scene->r.size * scene->r.ysch) / 100;
562
563         /* corrects render size with actual size, not every card supports non-power-of-two dimensions */
564         DRW_opengl_context_enable(); /* Offscreen creation needs to be done in DRW context. */
565         ofs = GPU_offscreen_create(sizex, sizey, full_samples ? 0 : samples, true, true, err_out);
566         DRW_opengl_context_disable();
567
568         if (!ofs) {
569                 BKE_reportf(op->reports, RPT_ERROR, "Failed to create OpenGL off-screen buffer, %s", err_out);
570                 return false;
571         }
572
573         /* allocate opengl render */
574         oglrender = MEM_callocN(sizeof(OGLRender), "OGLRender");
575         op->customdata = oglrender;
576
577         oglrender->ofs = ofs;
578         oglrender->ofs_samples = samples;
579         oglrender->ofs_full_samples = full_samples;
580         oglrender->sizex = sizex;
581         oglrender->sizey = sizey;
582         oglrender->bmain = CTX_data_main(C);
583         oglrender->scene = scene;
584         oglrender->workspace = workspace;
585         oglrender->view_layer = CTX_data_view_layer(C);
586         oglrender->depsgraph = CTX_data_depsgraph(C);
587         oglrender->cfrao = scene->r.cfra;
588
589         oglrender->write_still = is_write_still && !is_animation;
590         oglrender->is_animation = is_animation;
591
592         oglrender->views_len = BKE_scene_multiview_num_views_get(&scene->r);
593
594         oglrender->is_sequencer = is_sequencer;
595         if (is_sequencer) {
596                 oglrender->sseq = CTX_wm_space_seq(C);
597                 ImBuf **ibufs_arr = MEM_callocN(sizeof(*ibufs_arr) * oglrender->views_len, __func__);
598                 oglrender->seq_data.ibufs_arr = ibufs_arr;
599         }
600
601         oglrender->prevsa = prevsa;
602         oglrender->prevar = prevar;
603
604         if (is_view_context) {
605                 /* so quad view renders camera */
606                 ED_view3d_context_user_region(C, &oglrender->v3d, &oglrender->ar);
607
608                 oglrender->rv3d = oglrender->ar->regiondata;
609
610                 /* MUST be cleared on exit */
611                 oglrender->scene->customdata_mask_modal = ED_view3d_datamask(C, oglrender->scene, oglrender->v3d);
612
613                 /* apply immediately in case we're rendering from a script,
614                  * running notifiers again will overwrite */
615                 oglrender->scene->customdata_mask |= oglrender->scene->customdata_mask_modal;
616         }
617
618         /* create render */
619         oglrender->re = RE_NewSceneRender(scene);
620
621         /* create image and image user */
622         oglrender->ima = BKE_image_verify_viewer(oglrender->bmain, IMA_TYPE_R_RESULT, "Render Result");
623         BKE_image_signal(oglrender->bmain, oglrender->ima, NULL, IMA_SIGNAL_FREE);
624         BKE_image_backup_render(oglrender->scene, oglrender->ima, true);
625
626         oglrender->iuser.scene = scene;
627         oglrender->iuser.ok = 1;
628
629         /* create render result */
630         RE_InitState(oglrender->re, NULL, &scene->r, &scene->view_layers, NULL, sizex, sizey, NULL);
631
632         /* create render views */
633         screen_opengl_views_setup(oglrender);
634
635         /* wm vars */
636         oglrender->wm = wm;
637         oglrender->win = win;
638
639         oglrender->totvideos = 0;
640         oglrender->mh = NULL;
641         oglrender->movie_ctx_arr = NULL;
642
643         if (is_animation) {
644                 TaskScheduler *task_scheduler = BLI_task_scheduler_get();
645                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
646                         task_scheduler = BLI_task_scheduler_create(1);
647                         oglrender->task_scheduler = task_scheduler;
648                         oglrender->task_pool = BLI_task_pool_create_background(task_scheduler,
649                                                                                oglrender);
650                 }
651                 else {
652                         oglrender->task_scheduler = NULL;
653                         oglrender->task_pool = BLI_task_pool_create(task_scheduler,
654                                                                     oglrender);
655                 }
656                 oglrender->pool_ok = true;
657                 BLI_spin_init(&oglrender->reports_lock);
658         }
659         else {
660                 oglrender->task_scheduler = NULL;
661                 oglrender->task_pool = NULL;
662         }
663         oglrender->num_scheduled_frames = 0;
664         BLI_mutex_init(&oglrender->task_mutex);
665         BLI_condition_init(&oglrender->task_condition);
666
667 #ifdef DEBUG_TIME
668         oglrender->time_start = PIL_check_seconds_timer();
669 #endif
670
671         return true;
672 }
673
674 static void screen_opengl_render_end(bContext *C, OGLRender *oglrender)
675 {
676         Main *bmain = CTX_data_main(C);
677         Scene *scene = oglrender->scene;
678         int i;
679
680         if (oglrender->is_animation) {
681                 /* Trickery part for movie output:
682                  *
683                  * We MUST write frames in an exact order, so we only let background
684                  * thread to work on that, and main thread is simply waits for that
685                  * thread to do all the dirty work.
686                  *
687                  * After this loop is done work_and_wait() will have nothing to do,
688                  * so we don't run into wrong order of frames written to the stream.
689                  */
690                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
691                         BLI_mutex_lock(&oglrender->task_mutex);
692                         while (oglrender->num_scheduled_frames > 0) {
693                                 BLI_condition_wait(&oglrender->task_condition,
694                                                    &oglrender->task_mutex);
695                         }
696                         BLI_mutex_unlock(&oglrender->task_mutex);
697                 }
698                 BLI_task_pool_work_and_wait(oglrender->task_pool);
699                 BLI_task_pool_free(oglrender->task_pool);
700                 /* Depending on various things we might or might not use global scheduler. */
701                 if (oglrender->task_scheduler != NULL) {
702                         BLI_task_scheduler_free(oglrender->task_scheduler);
703                 }
704                 BLI_spin_end(&oglrender->reports_lock);
705         }
706         BLI_mutex_end(&oglrender->task_mutex);
707         BLI_condition_end(&oglrender->task_condition);
708
709 #ifdef DEBUG_TIME
710         printf("Total render time: %f\n", PIL_check_seconds_timer() - oglrender->time_start);
711 #endif
712
713         if (oglrender->mh) {
714                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
715                         for (i = 0; i < oglrender->totvideos; i++) {
716                                 oglrender->mh->end_movie(oglrender->movie_ctx_arr[i]);
717                                 oglrender->mh->context_free(oglrender->movie_ctx_arr[i]);
718                         }
719                 }
720
721                 if (oglrender->movie_ctx_arr) {
722                         MEM_freeN(oglrender->movie_ctx_arr);
723                 }
724         }
725
726         if (oglrender->timer) { /* exec will not have a timer */
727                 Depsgraph *depsgraph = oglrender->depsgraph;
728                 scene->r.cfra = oglrender->cfrao;
729                 BKE_scene_graph_update_for_newframe(depsgraph, bmain);
730
731                 WM_event_remove_timer(oglrender->wm, oglrender->win, oglrender->timer);
732         }
733
734         WM_cursor_modal_restore(oglrender->win);
735
736         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, oglrender->scene);
737
738         DRW_opengl_context_enable();
739         GPU_offscreen_free(oglrender->ofs);
740         DRW_opengl_context_disable();
741
742         if (oglrender->is_sequencer) {
743                 MEM_freeN(oglrender->seq_data.ibufs_arr);
744         }
745
746         oglrender->scene->customdata_mask_modal = 0;
747
748         CTX_wm_area_set(C, oglrender->prevsa);
749         CTX_wm_region_set(C, oglrender->prevar);
750
751         MEM_freeN(oglrender);
752 }
753
754 static void screen_opengl_render_cancel(bContext *C, wmOperator *op)
755 {
756         screen_opengl_render_end(C, op->customdata);
757 }
758
759 /* share between invoke and exec */
760 static bool screen_opengl_render_anim_initialize(bContext *C, wmOperator *op)
761 {
762         /* initialize animation */
763         OGLRender *oglrender;
764         Scene *scene;
765
766         oglrender = op->customdata;
767         scene = oglrender->scene;
768         oglrender->totvideos = BKE_scene_multiview_num_videos_get(&scene->r);
769
770         oglrender->reports = op->reports;
771
772         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
773                 size_t width, height;
774                 int i;
775
776                 BKE_scene_multiview_videos_dimensions_get(&scene->r, oglrender->sizex, oglrender->sizey, &width, &height);
777                 oglrender->mh = BKE_movie_handle_get(scene->r.im_format.imtype);
778
779                 if (oglrender->mh == NULL) {
780                         BKE_report(oglrender->reports, RPT_ERROR, "Movie format unsupported");
781                         screen_opengl_render_end(C, oglrender);
782                         return false;
783                 }
784
785                 oglrender->movie_ctx_arr = MEM_mallocN(sizeof(void *) * oglrender->totvideos, "Movies");
786
787                 for (i = 0; i < oglrender->totvideos; i++) {
788                         const char *suffix = BKE_scene_multiview_view_id_suffix_get(&scene->r, i);
789
790                         oglrender->movie_ctx_arr[i] = oglrender->mh->context_create();
791                         if (!oglrender->mh->start_movie(oglrender->movie_ctx_arr[i], scene, &scene->r, oglrender->sizex,
792                                                         oglrender->sizey, oglrender->reports, PRVRANGEON != 0, suffix))
793                         {
794                                 screen_opengl_render_end(C, oglrender);
795                                 return false;
796                         }
797                 }
798         }
799
800         oglrender->cfrao = scene->r.cfra;
801         oglrender->nfra = PSFRA;
802         scene->r.cfra = PSFRA;
803
804         return true;
805 }
806
807 typedef struct WriteTaskData {
808         RenderResult *rr;
809         Scene tmp_scene;
810 } WriteTaskData;
811
812 static void write_result_func(TaskPool * __restrict pool,
813                               void *task_data_v,
814                               int UNUSED(thread_id))
815 {
816         OGLRender *oglrender = (OGLRender *) BLI_task_pool_userdata(pool);
817         WriteTaskData *task_data = (WriteTaskData *) task_data_v;
818         Scene *scene = &task_data->tmp_scene;
819         RenderResult *rr = task_data->rr;
820         const bool is_movie = BKE_imtype_is_movie(scene->r.im_format.imtype);
821         const int cfra = scene->r.cfra;
822         bool ok;
823         /* Don't attempt to write if we've got an error. */
824         if (!oglrender->pool_ok) {
825                 RE_FreeRenderResult(rr);
826                 BLI_mutex_lock(&oglrender->task_mutex);
827                 oglrender->num_scheduled_frames--;
828                 BLI_condition_notify_all(&oglrender->task_condition);
829                 BLI_mutex_unlock(&oglrender->task_mutex);
830                 return;
831         }
832         /* Construct local thread0safe copy of reports structure which we can
833          * safely pass to the underlying functions.
834          */
835         ReportList reports;
836         BKE_reports_init(&reports, oglrender->reports->flag & ~RPT_PRINT);
837         /* Do actual save logic here, depending on the file format.
838          *
839          * NOTE: We have to construct temporary scene with proper scene->r.cfra.
840          * This is because underlying calls do not use r.cfra but use scene
841          * for that.
842          */
843         if (is_movie) {
844                 ok = RE_WriteRenderViewsMovie(&reports,
845                                               rr,
846                                               scene,
847                                               &scene->r,
848                                               oglrender->mh,
849                                               oglrender->movie_ctx_arr,
850                                               oglrender->totvideos,
851                                               PRVRANGEON != 0);
852         }
853         else {
854                 /* TODO(sergey): We can in theory save some CPU ticks here because we
855                  * calculate file name again here.
856                  */
857                 char name[FILE_MAX];
858                 BKE_image_path_from_imformat(name,
859                                              scene->r.pic,
860                                              BKE_main_blendfile_path(oglrender->bmain),
861                                              cfra,
862                                              &scene->r.im_format,
863                                              (scene->r.scemode & R_EXTENSION) != 0,
864                                              true,
865                                              NULL);
866
867                 BKE_render_result_stamp_info(scene, scene->camera, rr, false);
868                 ok = RE_WriteRenderViewsImage(NULL, rr, scene, true, name);
869                 if (!ok) {
870                         BKE_reportf(&reports,
871                                     RPT_ERROR,
872                                     "Write error: cannot save %s",
873                                     name);
874                 }
875         }
876         if (reports.list.first != NULL) {
877                 BLI_spin_lock(&oglrender->reports_lock);
878                 for (Report *report = reports.list.first;
879                      report != NULL;
880                      report = report->next)
881                 {
882                         BKE_report(oglrender->reports,
883                                    report->type,
884                                    report->message);
885                 }
886                 BLI_spin_unlock(&oglrender->reports_lock);
887         }
888         if (!ok) {
889                 oglrender->pool_ok = false;
890         }
891         RE_FreeRenderResult(rr);
892         BLI_mutex_lock(&oglrender->task_mutex);
893         oglrender->num_scheduled_frames--;
894         BLI_condition_notify_all(&oglrender->task_condition);
895         BLI_mutex_unlock(&oglrender->task_mutex);
896 }
897
898 static bool schedule_write_result(OGLRender *oglrender, RenderResult *rr)
899 {
900         if (!oglrender->pool_ok) {
901                 RE_FreeRenderResult(rr);
902                 return false;
903         }
904         Scene *scene = oglrender->scene;
905         WriteTaskData *task_data = MEM_mallocN(sizeof(WriteTaskData), "write task data");
906         task_data->rr = rr;
907         task_data->tmp_scene = *scene;
908         BLI_mutex_lock(&oglrender->task_mutex);
909         oglrender->num_scheduled_frames++;
910         if (oglrender->num_scheduled_frames > MAX_SCHEDULED_FRAMES) {
911                 BLI_condition_wait(&oglrender->task_condition,
912                                    &oglrender->task_mutex);
913         }
914         BLI_mutex_unlock(&oglrender->task_mutex);
915         BLI_task_pool_push(oglrender->task_pool,
916                            write_result_func,
917                            task_data,
918                            true,
919                            TASK_PRIORITY_LOW);
920         return true;
921 }
922
923 static bool screen_opengl_render_anim_step(bContext *C, wmOperator *op)
924 {
925         Main *bmain = CTX_data_main(C);
926         OGLRender *oglrender = op->customdata;
927         Scene *scene = oglrender->scene;
928         Depsgraph *depsgraph = oglrender->depsgraph;
929         char name[FILE_MAX];
930         bool ok = false;
931         const bool view_context = (oglrender->v3d != NULL);
932         bool is_movie;
933         RenderResult *rr;
934
935         /* go to next frame */
936         if (CFRA < oglrender->nfra)
937                 CFRA++;
938         while (CFRA < oglrender->nfra) {
939                 BKE_scene_graph_update_for_newframe(depsgraph, bmain);
940                 CFRA++;
941         }
942
943         is_movie = BKE_imtype_is_movie(scene->r.im_format.imtype);
944
945         if (!is_movie) {
946                 BKE_image_path_from_imformat(
947                         name, scene->r.pic, BKE_main_blendfile_path(oglrender->bmain), scene->r.cfra,
948                         &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, true, NULL);
949
950                 if ((scene->r.mode & R_NO_OVERWRITE) && BLI_exists(name)) {
951                         BLI_spin_lock(&oglrender->reports_lock);
952                         BKE_reportf(op->reports, RPT_INFO, "Skipping existing frame \"%s\"", name);
953                         BLI_spin_unlock(&oglrender->reports_lock);
954                         ok = true;
955                         goto finally;
956                 }
957         }
958
959         WM_cursor_time(oglrender->win, scene->r.cfra);
960
961         BKE_scene_graph_update_for_newframe(depsgraph, bmain);
962
963         if (view_context) {
964                 if (oglrender->rv3d->persp == RV3D_CAMOB && oglrender->v3d->camera && oglrender->v3d->scenelock) {
965                         /* since BKE_scene_graph_update_for_newframe() is used rather
966                          * then ED_update_for_newframe() the camera needs to be set */
967                         if (BKE_scene_camera_switch_update(scene)) {
968                                 oglrender->v3d->camera = scene->camera;
969                         }
970                 }
971         }
972         else {
973                 BKE_scene_camera_switch_update(scene);
974         }
975
976         /* render into offscreen buffer */
977         screen_opengl_render_apply(C, oglrender);
978
979         /* save to disk */
980         rr = RE_AcquireResultRead(oglrender->re);
981         RenderResult *new_rr = RE_DuplicateRenderResult(rr);
982         RE_ReleaseResult(oglrender->re);
983
984         ok = schedule_write_result(oglrender, new_rr);
985
986 finally:  /* Step the frame and bail early if needed */
987
988         /* go to next frame */
989         oglrender->nfra += scene->r.frame_step;
990
991         /* stop at the end or on error */
992         if (CFRA >= PEFRA || !ok) {
993                 screen_opengl_render_end(C, op->customdata);
994                 return 0;
995         }
996
997         return 1;
998 }
999
1000
1001 static int screen_opengl_render_modal(bContext *C, wmOperator *op, const wmEvent *event)
1002 {
1003         OGLRender *oglrender = op->customdata;
1004         const bool anim = RNA_boolean_get(op->ptr, "animation");
1005         bool ret;
1006
1007         switch (event->type) {
1008                 case ESCKEY:
1009                         /* cancel */
1010                         oglrender->pool_ok = false;  /* Flag pool for cancel. */
1011                         screen_opengl_render_end(C, op->customdata);
1012                         return OPERATOR_FINISHED;
1013                 case TIMER:
1014                         /* render frame? */
1015                         if (oglrender->timer == event->customdata)
1016                                 break;
1017                         ATTR_FALLTHROUGH;
1018                 default:
1019                         /* nothing to do */
1020                         return OPERATOR_RUNNING_MODAL;
1021         }
1022
1023         /* run first because screen_opengl_render_anim_step can free oglrender */
1024         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, oglrender->scene);
1025
1026         if (anim == 0) {
1027                 screen_opengl_render_apply(C, op->customdata);
1028                 screen_opengl_render_end(C, op->customdata);
1029                 return OPERATOR_FINISHED;
1030         }
1031         else {
1032                 ret = screen_opengl_render_anim_step(C, op);
1033         }
1034
1035         /* stop at the end or on error */
1036         if (ret == false) {
1037                 return OPERATOR_FINISHED;
1038         }
1039
1040         return OPERATOR_RUNNING_MODAL;
1041 }
1042
1043 static int screen_opengl_render_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1044 {
1045         OGLRender *oglrender;
1046         const bool anim = RNA_boolean_get(op->ptr, "animation");
1047
1048         if (!screen_opengl_render_init(C, op))
1049                 return OPERATOR_CANCELLED;
1050
1051         if (anim) {
1052                 if (!screen_opengl_render_anim_initialize(C, op))
1053                         return OPERATOR_CANCELLED;
1054         }
1055
1056         oglrender = op->customdata;
1057         render_view_open(C, event->x, event->y, op->reports);
1058
1059         /* view may be changed above (R_OUTPUT_WINDOW) */
1060         oglrender->win = CTX_wm_window(C);
1061
1062         WM_event_add_modal_handler(C, op);
1063         oglrender->timer = WM_event_add_timer(oglrender->wm, oglrender->win, TIMER, 0.01f);
1064
1065         return OPERATOR_RUNNING_MODAL;
1066 }
1067
1068 /* executes blocking render */
1069 static int screen_opengl_render_exec(bContext *C, wmOperator *op)
1070 {
1071         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
1072
1073         if (!screen_opengl_render_init(C, op))
1074                 return OPERATOR_CANCELLED;
1075
1076         if (!is_animation) { /* same as invoke */
1077                 /* render image */
1078                 screen_opengl_render_apply(C, op->customdata);
1079                 screen_opengl_render_end(C, op->customdata);
1080
1081                 return OPERATOR_FINISHED;
1082         }
1083         else {
1084                 bool ret = true;
1085
1086                 if (!screen_opengl_render_anim_initialize(C, op))
1087                         return OPERATOR_CANCELLED;
1088
1089                 while (ret) {
1090                         ret = screen_opengl_render_anim_step(C, op);
1091                 }
1092         }
1093
1094         /* no redraw needed, we leave state as we entered it */
1095 //      ED_update_for_newframe(C);
1096         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, CTX_data_scene(C));
1097
1098         return OPERATOR_FINISHED;
1099 }
1100
1101 void RENDER_OT_opengl(wmOperatorType *ot)
1102 {
1103         PropertyRNA *prop;
1104
1105         /* identifiers */
1106         ot->name = "Viewport Render";
1107         ot->description = "Take a snapshot of the active viewport";
1108         ot->idname = "RENDER_OT_opengl";
1109
1110         /* api callbacks */
1111         ot->invoke = screen_opengl_render_invoke;
1112         ot->exec = screen_opengl_render_exec; /* blocking */
1113         ot->modal = screen_opengl_render_modal;
1114         ot->cancel = screen_opengl_render_cancel;
1115
1116         ot->poll = ED_operator_screenactive;
1117
1118         prop = RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
1119         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1120         prop = RNA_def_boolean(ot->srna, "sequencer", 0, "Sequencer", "Render using the sequencer's OpenGL display");
1121         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1122         prop = RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
1123         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1124         prop = RNA_def_boolean(ot->srna, "view_context", 1, "View Context", "Use the current 3D view for rendering, else use scene settings");
1125         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1126
1127 }
1128
1129 /* function for getting an opengl buffer from a View3D, used by sequencer */
1130 // extern void *sequencer_view3d_cb;