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