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