a194178ef40b28763c9079cfa84c575cfea65f3d
[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_jitter.h"
42 #include "BLI_threads.h"
43
44 #include "DNA_scene_types.h"
45 #include "DNA_object_types.h"
46
47 #include "BKE_camera.h"
48 #include "BKE_context.h"
49 #include "BKE_global.h"
50 #include "BKE_image.h"
51 #include "BKE_main.h"
52 #include "BKE_report.h"
53 #include "BKE_scene.h"
54 #include "BKE_sequencer.h"
55 #include "BKE_writeavi.h"
56
57 #include "WM_api.h"
58 #include "WM_types.h"
59
60 #include "ED_screen.h"
61 #include "ED_view3d.h"
62 #include "ED_gpencil.h"
63
64 #include "RE_pipeline.h"
65 #include "IMB_imbuf_types.h"
66 #include "IMB_imbuf.h"
67 #include "IMB_colormanagement.h"
68
69 #include "RNA_access.h"
70 #include "RNA_define.h"
71
72 #include "GPU_extensions.h"
73 #include "GPU_glew.h"
74 #include "GPU_compositing.h"
75
76
77 #include "render_intern.h"
78
79 typedef struct OGLRender {
80         Main *bmain;
81         Render *re;
82         Scene *scene;
83
84         View3D *v3d;
85         RegionView3D *rv3d;
86         ARegion *ar;
87
88         ScrArea *prevsa;
89         ARegion *prevar;
90
91         bool is_sequencer;
92         SpaceSeq *sseq;
93
94
95         Image *ima;
96         ImageUser iuser;
97
98         GPUOffScreen *ofs;
99         int ofs_samples;
100         bool ofs_full_samples;
101         GPUFX *fx;
102         int sizex, sizey;
103         int write_still;
104
105         ReportList *reports;
106         bMovieHandle *mh;
107         int cfrao, nfra;
108
109         int totvideos;
110
111         /* quick lookup */
112         int view_id;
113
114         /* wm vars for timer and progress cursor */
115         wmWindowManager *wm;
116         wmWindow *win;
117
118         wmTimer *timer; /* use to check if running modal or not (invoke'd or exec'd)*/
119         void **movie_ctx_arr;
120 } OGLRender;
121
122 /* added because v3d is not always valid */
123 static unsigned int screen_opengl_layers(OGLRender *oglrender)
124 {
125         if (oglrender->v3d) {
126                 return oglrender->scene->lay | oglrender->v3d->lay;
127         }
128         else {
129                 return oglrender->scene->lay;
130         }
131 }
132
133 static bool screen_opengl_is_multiview(OGLRender *oglrender)
134 {
135         View3D *v3d = oglrender->v3d;
136         RegionView3D *rv3d = oglrender->rv3d;
137         RenderData *rd = &oglrender->scene->r;
138
139         if ((rd == NULL) || ((!oglrender->is_sequencer) && ((rv3d == NULL) || (v3d == NULL))))
140                 return false;
141
142         return (rd->scemode & R_MULTIVIEW) && ((oglrender->is_sequencer) || (rv3d->persp == RV3D_CAMOB && v3d->camera));
143 }
144
145 static void screen_opengl_views_setup(OGLRender *oglrender)
146 {
147         RenderResult *rr;
148         RenderView *rv;
149         SceneRenderView *srv;
150         bool is_multiview;
151         Object *camera;
152         View3D *v3d = oglrender->v3d;
153
154         RenderData *rd = &oglrender->scene->r;
155
156         rr = RE_AcquireResultWrite(oglrender->re);
157
158         is_multiview = screen_opengl_is_multiview(oglrender);
159
160         if (!is_multiview) {
161                 /* we only have one view when multiview is off */
162                 rv = rr->views.first;
163
164                 if (rv == NULL) {
165                         rv = MEM_callocN(sizeof(RenderView), "new opengl render view");
166                         BLI_addtail(&rr->views, rv);
167                 }
168
169                 while (rv->next) {
170                         RenderView *rv_del = rv->next;
171                         BLI_remlink(&rr->views, rv_del);
172
173                         if (rv_del->rectf)
174                                 MEM_freeN(rv_del->rectf);
175
176                         if (rv_del->rectz)
177                                 MEM_freeN(rv_del->rectz);
178
179                         MEM_freeN(rv_del);
180                 }
181         }
182         else {
183                 if (!oglrender->is_sequencer)
184                         RE_SetOverrideCamera(oglrender->re, V3D_CAMERA_SCENE(oglrender->scene, v3d));
185
186                 /* remove all the views that are not needed */
187                 rv = rr->views.last;
188                 while (rv) {
189                         srv = BLI_findstring(&rd->views, rv->name, offsetof(SceneRenderView, name));
190                         if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
191                                 if (rv->rectf == NULL)
192                                         rv->rectf = MEM_callocN(sizeof(float) * 4 * oglrender->sizex * oglrender->sizey, "screen_opengl_render_init rect");
193                                 rv = rv->prev;
194                         }
195                         else {
196                                 RenderView *rv_del = rv;
197                                 rv  = rv_del->prev;
198
199                                 BLI_remlink(&rr->views, rv_del);
200
201                                 if (rv_del->rectf)
202                                         MEM_freeN(rv_del->rectf);
203
204                                 if (rv_del->rectz)
205                                         MEM_freeN(rv_del->rectz);
206
207                                 MEM_freeN(rv_del);
208                         }
209                 }
210
211                 /* create all the views that are needed */
212                 for (srv = rd->views.first; srv; srv = srv->next) {
213                         if (BKE_scene_multiview_is_render_view_active(rd, srv) == false)
214                                 continue;
215
216                         rv = BLI_findstring(&rr->views, srv->name, offsetof(SceneRenderView, name));
217
218                         if (rv == NULL) {
219                                 rv = MEM_callocN(sizeof(RenderView), "new opengl render view");
220                                 BLI_strncpy(rv->name, srv->name, sizeof(rv->name));
221                                 BLI_addtail(&rr->views, rv);
222                         }
223                 }
224         }
225
226         for (rv = rr->views.first; rv; rv = rv->next) {
227                 if (rv->rectf == NULL) {
228                         rv->rectf = MEM_callocN(sizeof(float) * 4 * oglrender->sizex * oglrender->sizey, "screen_opengl_render_init rect");
229                 }
230         }
231
232         BLI_lock_thread(LOCK_DRAW_IMAGE);
233         if (!(is_multiview && BKE_scene_multiview_is_stereo3d(rd)))
234                 oglrender->iuser.flag &= ~IMA_SHOW_STEREO;
235         BLI_unlock_thread(LOCK_DRAW_IMAGE);
236
237         /* will only work for non multiview correctly */
238         if (v3d) {
239                 camera = BKE_camera_multiview_render(oglrender->scene, v3d->camera, "new opengl render view");
240                 BKE_render_result_stamp_info(oglrender->scene, camera, rr, false);
241         }
242         else {
243                 BKE_render_result_stamp_info(oglrender->scene, oglrender->scene->camera, rr, false);
244         }
245
246         RE_ReleaseResult(oglrender->re);
247 }
248
249 static void screen_opengl_render_doit(OGLRender *oglrender, RenderResult *rr)
250 {
251         Scene *scene = oglrender->scene;
252         ARegion *ar = oglrender->ar;
253         View3D *v3d = oglrender->v3d;
254         RegionView3D *rv3d = oglrender->rv3d;
255         Object *camera = NULL;
256         ImBuf *ibuf;
257         int sizex = oglrender->sizex;
258         int sizey = oglrender->sizey;
259         const short view_context = (v3d != NULL);
260         bool draw_bgpic = true;
261         bool draw_sky = (scene->r.alphamode == R_ADDSKY);
262         unsigned char *rect = NULL;
263         const char *viewname = RE_GetActiveRenderView(oglrender->re);
264
265         if (oglrender->is_sequencer) {
266                 SeqRenderData context;
267                 SpaceSeq *sseq = oglrender->sseq;
268                 int chanshown = sseq ? sseq->chanshown : 0;
269                 struct bGPdata *gpd = (sseq && (sseq->flag & SEQ_SHOW_GPENCIL)) ? sseq->gpd : NULL;
270
271                 BKE_sequencer_new_render_data(
272                         oglrender->bmain->eval_ctx, oglrender->bmain, scene,
273                         oglrender->sizex, oglrender->sizey, 100.0f,
274                         &context);
275
276                 context.view_id = BKE_scene_multiview_view_id_get(&scene->r, viewname);
277                 context.gpu_offscreen = oglrender->ofs;
278                 context.gpu_fx = oglrender->fx;
279                 context.gpu_full_samples = oglrender->ofs_full_samples;
280
281                 ibuf = BKE_sequencer_give_ibuf(&context, CFRA, chanshown);
282
283                 if (ibuf) {
284                         ImBuf *out = IMB_dupImBuf(ibuf);
285                         IMB_freeImBuf(ibuf);
286                         /* OpenGL render is considered to be preview and should be
287                          * as fast as possible. So currently we're making sure sequencer
288                          * result is always byte to simplify color management pipeline.
289                          *
290                          * TODO(sergey): In the case of output to float container (EXR)
291                          * it actually makes sense to keep float buffer instead.
292                          */
293                         if (out->rect_float != NULL) {
294                                 IMB_rect_from_float(out);
295                                 imb_freerectfloatImBuf(out);
296                         }
297                         BLI_assert((oglrender->sizex == ibuf->x) && (oglrender->sizey == ibuf->y));
298                         RE_render_result_rect_from_ibuf(rr, &scene->r, out, oglrender->view_id);
299                         IMB_freeImBuf(out);
300                 }
301
302                 if (gpd) {
303                         int i;
304                         unsigned char *gp_rect;
305                         unsigned char *rect = (unsigned char*)RE_RenderViewGetById(rr, oglrender->view_id)->rect32;
306
307                         GPU_offscreen_bind(oglrender->ofs, true);
308
309                         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
310                         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
311
312                         wmOrtho2(0, sizex, 0, sizey);
313                         glTranslatef(sizex / 2, sizey / 2, 0.0f);
314
315                         G.f |= G_RENDER_OGL;
316                         ED_gpencil_draw_ex(scene, gpd, sizex, sizey, scene->r.cfra, SPACE_SEQ);
317                         G.f &= ~G_RENDER_OGL;
318
319                         gp_rect = MEM_mallocN(sizex * sizey * sizeof(unsigned char) * 4, "offscreen rect");
320                         GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, gp_rect);
321
322                         for (i = 0; i < sizex * sizey * 4; i += 4) {
323                                 blend_color_mix_byte(&rect[i], &rect[i], &gp_rect[i]);
324                         }
325                         GPU_offscreen_unbind(oglrender->ofs, true);
326
327                         MEM_freeN(gp_rect);
328                 }
329         }
330         else {
331                 /* shouldnt suddenly give errors mid-render but possible */
332                 char err_out[256] = "unknown";
333                 ImBuf *ibuf_view;
334                 const int alpha_mode = (draw_sky) ? R_ADDSKY : R_ALPHAPREMUL;
335
336                 if (view_context) {
337                         ibuf_view = ED_view3d_draw_offscreen_imbuf(
338                                scene, v3d, ar, sizex, sizey,
339                                IB_rect, draw_bgpic,
340                                alpha_mode, oglrender->ofs_samples, oglrender->ofs_full_samples, viewname,
341                                oglrender->fx, oglrender->ofs, err_out);
342
343                         /* for stamp only */
344                         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
345                                 camera = BKE_camera_multiview_render(oglrender->scene, v3d->camera, viewname);
346                         }
347                 }
348                 else {
349                         ibuf_view = ED_view3d_draw_offscreen_imbuf_simple(
350                                 scene, scene->camera, oglrender->sizex, oglrender->sizey,
351                                 IB_rect, OB_SOLID, false, true, true,
352                                 alpha_mode, oglrender->ofs_samples, oglrender->ofs_full_samples, viewname,
353                                 oglrender->fx, oglrender->ofs, err_out);
354                         camera = scene->camera;
355                 }
356
357                 if (ibuf_view) {
358                         /* steal rect reference from ibuf */
359                         rect = (unsigned char *)ibuf_view->rect;
360                         ibuf_view->mall &= ~IB_rect;
361
362                         IMB_freeImBuf(ibuf_view);
363                 }
364                 else {
365                         fprintf(stderr, "%s: failed to get buffer, %s\n", __func__, err_out);
366                 }
367         }
368
369         /* note on color management:
370          *
371          * OpenGL renders into sRGB colors, but render buffers are expected to be
372          * linear So we convert to linear here, so the conversion back to bytes can make it
373          * sRGB (or other display space) again, and so that e.g. openexr saving also saves the
374          * correct linear float buffer.
375          */
376
377         if (rect) {
378                 int profile_to;
379                 float *rectf = RE_RenderViewGetById(rr, oglrender->view_id)->rectf;
380
381                 if (BKE_scene_check_color_management_enabled(scene))
382                         profile_to = IB_PROFILE_LINEAR_RGB;
383                 else
384                         profile_to = IB_PROFILE_SRGB;
385
386                 /* sequencer has got trickier conversion happened above
387                  * also assume opengl's space matches byte buffer color space */
388                 IMB_buffer_float_from_byte(rectf, rect,
389                                            profile_to, IB_PROFILE_SRGB, true,
390                                            oglrender->sizex, oglrender->sizey, oglrender->sizex, oglrender->sizex);
391
392                 /* rr->rectf is now filled with image data */
393
394                 if ((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW))
395                         BKE_image_stamp_buf(scene, camera, rect, rectf, rr->rectx, rr->recty, 4);
396
397                 MEM_freeN(rect);
398         }
399 }
400
401 static void screen_opengl_render_write(OGLRender *oglrender)
402 {
403         Scene *scene = oglrender->scene;
404         RenderResult *rr;
405         bool ok;
406         char name[FILE_MAX];
407
408         rr = RE_AcquireResultRead(oglrender->re);
409
410         BKE_image_path_from_imformat(
411                 name, scene->r.pic, oglrender->bmain->name, scene->r.cfra,
412                 &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, false, NULL);
413
414         /* write images as individual images or stereo */
415         BKE_render_result_stamp_info(scene, scene->camera, rr, false);
416         ok = RE_WriteRenderViewsImage(oglrender->reports, rr, scene, false, name);
417
418         RE_ReleaseResultImage(oglrender->re);
419
420         if (ok) printf("OpenGL Render written to '%s'\n", name);
421         else printf("OpenGL Render failed to write '%s'\n", name);
422 }
423
424 static void screen_opengl_render_apply(OGLRender *oglrender)
425 {
426         RenderResult *rr;
427         RenderView *rv;
428         int view_id;
429         ImBuf *ibuf;
430         void *lock;
431
432         rr = RE_AcquireResultRead(oglrender->re);
433         for (rv = rr->views.first, view_id = 0; rv; rv = rv->next, view_id++) {
434                 RE_SetActiveRenderView(oglrender->re, rv->name);
435                 oglrender->view_id = view_id;
436                 screen_opengl_render_doit(oglrender, rr);
437         }
438
439         RE_ReleaseResult(oglrender->re);
440
441         ibuf = BKE_image_acquire_ibuf(oglrender->ima, &oglrender->iuser, &lock);
442         if (ibuf) {
443                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
444         }
445         BKE_image_release_ibuf(oglrender->ima, ibuf, lock);
446
447         if (oglrender->write_still) {
448                 screen_opengl_render_write(oglrender);
449         }
450 }
451
452 static bool screen_opengl_render_init(bContext *C, wmOperator *op)
453 {
454         /* new render clears all callbacks */
455         wmWindowManager *wm = CTX_wm_manager(C);
456         wmWindow *win = CTX_wm_window(C);
457
458         Scene *scene = CTX_data_scene(C);
459         ScrArea *prevsa = CTX_wm_area(C);
460         ARegion *prevar = CTX_wm_region(C);
461         GPUOffScreen *ofs;
462         OGLRender *oglrender;
463         int sizex, sizey;
464         const int samples = (scene->r.mode & R_OSA) ? scene->r.osa : 0;
465         const bool full_samples = (samples != 0) && (scene->r.scemode & R_FULL_SAMPLE);
466         bool is_view_context = RNA_boolean_get(op->ptr, "view_context");
467         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
468         const bool is_sequencer = RNA_boolean_get(op->ptr, "sequencer");
469         const bool is_write_still = RNA_boolean_get(op->ptr, "write_still");
470         char err_out[256] = "unknown";
471
472         if (G.background) {
473                 BKE_report(op->reports, RPT_ERROR, "Cannot use OpenGL render in background mode (no opengl context)");
474                 return false;
475         }
476
477         /* only one render job at a time */
478         if (WM_jobs_test(wm, scene, WM_JOB_TYPE_RENDER))
479                 return false;
480
481         if (is_sequencer) {
482                 is_view_context = false;
483         }
484         else {
485                 /* ensure we have a 3d view */
486                 if (!ED_view3d_context_activate(C)) {
487                         RNA_boolean_set(op->ptr, "view_context", false);
488                         is_view_context = false;
489                 }
490
491                 if (!is_view_context && scene->camera == NULL) {
492                         BKE_report(op->reports, RPT_ERROR, "Scene has no camera");
493                         return false;
494                 }
495         }
496
497         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
498                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
499                 return false;
500         }
501
502         /* stop all running jobs, except screen one. currently previews frustrate Render */
503         WM_jobs_kill_all_except(wm, CTX_wm_screen(C));
504
505         /* create offscreen buffer */
506         sizex = (scene->r.size * scene->r.xsch) / 100;
507         sizey = (scene->r.size * scene->r.ysch) / 100;
508
509         /* corrects render size with actual size, not every card supports non-power-of-two dimensions */
510         ofs = GPU_offscreen_create(sizex, sizey, full_samples ? 0 : samples, err_out);
511
512         if (!ofs) {
513                 BKE_reportf(op->reports, RPT_ERROR, "Failed to create OpenGL off-screen buffer, %s", err_out);
514                 return false;
515         }
516
517         /* allocate opengl render */
518         oglrender = MEM_callocN(sizeof(OGLRender), "OGLRender");
519         op->customdata = oglrender;
520
521         oglrender->ofs = ofs;
522         oglrender->ofs_samples = samples;
523         oglrender->ofs_full_samples = full_samples;
524         oglrender->sizex = sizex;
525         oglrender->sizey = sizey;
526         oglrender->bmain = CTX_data_main(C);
527         oglrender->scene = scene;
528         oglrender->cfrao = scene->r.cfra;
529
530         oglrender->write_still = is_write_still && !is_animation;
531
532         oglrender->is_sequencer = is_sequencer;
533         if (is_sequencer) {
534                 oglrender->sseq = CTX_wm_space_seq(C);
535         }
536
537         oglrender->prevsa = prevsa;
538         oglrender->prevar = prevar;
539
540         if (is_view_context) {
541                 ED_view3d_context_user_region(C, &oglrender->v3d, &oglrender->ar); /* so quad view renders camera */
542                 oglrender->rv3d = oglrender->ar->regiondata;
543
544                 /* MUST be cleared on exit */
545                 oglrender->scene->customdata_mask_modal = ED_view3d_datamask(oglrender->scene, oglrender->v3d);
546
547                 /* apply immediately in case we're rendering from a script,
548                  * running notifiers again will overwrite */
549                 oglrender->scene->customdata_mask |= oglrender->scene->customdata_mask_modal;
550
551                 if (oglrender->v3d->fx_settings.fx_flag & (GPU_FX_FLAG_DOF | GPU_FX_FLAG_SSAO)) {
552                         oglrender->fx = GPU_fx_compositor_create();
553                 }
554         }
555
556         /* create render */
557         oglrender->re = RE_NewRender(scene->id.name);
558
559         /* create image and image user */
560         oglrender->ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
561         BKE_image_signal(oglrender->ima, NULL, IMA_SIGNAL_FREE);
562         BKE_image_backup_render(oglrender->scene, oglrender->ima);
563
564         oglrender->iuser.scene = scene;
565         oglrender->iuser.ok = 1;
566
567         /* create render result */
568         RE_InitState(oglrender->re, NULL, &scene->r, NULL, sizex, sizey, NULL);
569
570         /* create render views */
571         screen_opengl_views_setup(oglrender);
572
573         /* wm vars */
574         oglrender->wm = wm;
575         oglrender->win = win;
576
577         oglrender->totvideos = 0;
578         oglrender->mh = NULL;
579         oglrender->movie_ctx_arr = NULL;
580
581         return true;
582 }
583
584 static void screen_opengl_render_end(bContext *C, OGLRender *oglrender)
585 {
586         Main *bmain = CTX_data_main(C);
587         Scene *scene = oglrender->scene;
588         int i;
589
590         if (oglrender->mh) {
591                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
592                         for (i = 0; i < oglrender->totvideos; i++) {
593                                 oglrender->mh->end_movie(oglrender->movie_ctx_arr[i]);
594                                 oglrender->mh->context_free(oglrender->movie_ctx_arr[i]);
595                         }
596                 }
597
598                 if (oglrender->movie_ctx_arr) {
599                         MEM_freeN(oglrender->movie_ctx_arr);
600                 }
601         }
602
603         if (oglrender->timer) { /* exec will not have a timer */
604                 scene->r.cfra = oglrender->cfrao;
605                 BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, screen_opengl_layers(oglrender));
606
607                 WM_event_remove_timer(oglrender->wm, oglrender->win, oglrender->timer);
608         }
609
610         WM_cursor_modal_restore(oglrender->win);
611
612         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, oglrender->scene);
613
614         if (oglrender->fx)
615                 GPU_fx_compositor_destroy(oglrender->fx);
616
617         GPU_offscreen_free(oglrender->ofs);
618
619         oglrender->scene->customdata_mask_modal = 0;
620
621         CTX_wm_area_set(C, oglrender->prevsa);
622         CTX_wm_region_set(C, oglrender->prevar);
623
624         MEM_freeN(oglrender);
625 }
626
627 static void screen_opengl_render_cancel(bContext *C, wmOperator *op)
628 {
629         screen_opengl_render_end(C, op->customdata);
630 }
631
632 /* share between invoke and exec */
633 static bool screen_opengl_render_anim_initialize(bContext *C, wmOperator *op)
634 {
635         /* initialize animation */
636         OGLRender *oglrender;
637         Scene *scene;
638
639         oglrender = op->customdata;
640         scene = oglrender->scene;
641         oglrender->totvideos = BKE_scene_multiview_num_videos_get(&scene->r);
642
643         oglrender->reports = op->reports;
644
645         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
646                 size_t width, height;
647                 int i;
648
649                 BKE_scene_multiview_videos_dimensions_get(&scene->r, oglrender->sizex, oglrender->sizey, &width, &height);
650                 oglrender->mh = BKE_movie_handle_get(scene->r.im_format.imtype);
651
652                 if (oglrender->mh == NULL) {
653                         BKE_report(oglrender->reports, RPT_ERROR, "Movie format unsupported");
654                         screen_opengl_render_end(C, oglrender);
655                         return false;
656                 }
657
658                 oglrender->movie_ctx_arr = MEM_mallocN(sizeof(void *) * oglrender->totvideos, "Movies");
659
660                 for (i = 0; i < oglrender->totvideos; i++) {
661                         const char *suffix = BKE_scene_multiview_view_id_suffix_get(&scene->r, i);
662
663                         oglrender->movie_ctx_arr[i] = oglrender->mh->context_create();
664                         if (!oglrender->mh->start_movie(oglrender->movie_ctx_arr[i], scene, &scene->r, oglrender->sizex,
665                                                         oglrender->sizey, oglrender->reports, PRVRANGEON != 0, suffix))
666                         {
667                                 screen_opengl_render_end(C, oglrender);
668                                 return false;
669                         }
670                 }
671         }
672
673         oglrender->cfrao = scene->r.cfra;
674         oglrender->nfra = PSFRA;
675         scene->r.cfra = PSFRA;
676
677         return true;
678 }
679
680 static bool screen_opengl_render_anim_step(bContext *C, wmOperator *op)
681 {
682         Main *bmain = CTX_data_main(C);
683         OGLRender *oglrender = op->customdata;
684         Scene *scene = oglrender->scene;
685         char name[FILE_MAX];
686         bool ok = false;
687         const bool view_context = (oglrender->v3d != NULL);
688         bool is_movie;
689         RenderResult *rr;
690
691         /* go to next frame */
692         if (CFRA < oglrender->nfra)
693                 CFRA++;
694         while (CFRA < oglrender->nfra) {
695                 unsigned int lay = screen_opengl_layers(oglrender);
696
697                 if (lay & 0xFF000000)
698                         lay &= 0xFF000000;
699
700                 BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, lay);
701                 CFRA++;
702         }
703
704         is_movie = BKE_imtype_is_movie(scene->r.im_format.imtype);
705
706         if (!is_movie) {
707                 BKE_image_path_from_imformat(
708                         name, scene->r.pic, oglrender->bmain->name, scene->r.cfra,
709                         &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, true, NULL);
710
711                 if ((scene->r.mode & R_NO_OVERWRITE) && BLI_exists(name)) {
712                         BKE_reportf(op->reports, RPT_INFO, "Skipping existing frame \"%s\"", name);
713                         ok = true;
714                         goto finally;
715                 }
716         }
717
718         WM_cursor_time(oglrender->win, scene->r.cfra);
719
720         BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, screen_opengl_layers(oglrender));
721
722         if (view_context) {
723                 if (oglrender->rv3d->persp == RV3D_CAMOB && oglrender->v3d->camera && oglrender->v3d->scenelock) {
724                         /* since BKE_scene_update_for_newframe() is used rather
725                          * then ED_update_for_newframe() the camera needs to be set */
726                         if (BKE_scene_camera_switch_update(scene)) {
727                                 oglrender->v3d->camera = scene->camera;
728                         }
729                 }
730         }
731         else {
732                 BKE_scene_camera_switch_update(scene);
733         }
734
735         /* render into offscreen buffer */
736         screen_opengl_render_apply(oglrender);
737
738         /* save to disk */
739         rr = RE_AcquireResultRead(oglrender->re);
740
741         if (is_movie) {
742                 ok = RE_WriteRenderViewsMovie(oglrender->reports, rr, scene, &scene->r, oglrender->mh,
743                                               oglrender->movie_ctx_arr, oglrender->totvideos, PRVRANGEON != 0);
744                 if (ok) {
745                         printf("Append frame %d", scene->r.cfra);
746                         BKE_reportf(op->reports, RPT_INFO, "Appended frame: %d", scene->r.cfra);
747                 }
748         }
749         else {
750                 BKE_render_result_stamp_info(scene, scene->camera, rr, false);
751                 ok = RE_WriteRenderViewsImage(op->reports, rr, scene, true, name);
752                 if (ok) {
753                         printf("Saved: %s", name);
754                         BKE_reportf(op->reports, RPT_INFO, "Saved file: %s", name);
755                 }
756                 else {
757                         printf("Write error: cannot save %s\n", name);
758                         BKE_reportf(op->reports, RPT_ERROR, "Write error: cannot save %s", name);
759                 }
760         }
761
762         RE_ReleaseResult(oglrender->re);
763
764
765         /* movie stats prints have no line break */
766         printf("\n");
767
768
769 finally:  /* Step the frame and bail early if needed */
770
771         /* go to next frame */
772         oglrender->nfra += scene->r.frame_step;
773
774         /* stop at the end or on error */
775         if (CFRA >= PEFRA || !ok) {
776                 screen_opengl_render_end(C, op->customdata);
777                 return 0;
778         }
779
780         return 1;
781 }
782
783
784 static int screen_opengl_render_modal(bContext *C, wmOperator *op, const wmEvent *event)
785 {
786         OGLRender *oglrender = op->customdata;
787         const bool anim = RNA_boolean_get(op->ptr, "animation");
788         bool ret;
789
790         switch (event->type) {
791                 case ESCKEY:
792                         /* cancel */
793                         screen_opengl_render_end(C, op->customdata);
794                         return OPERATOR_FINISHED;
795                 case TIMER:
796                         /* render frame? */
797                         if (oglrender->timer == event->customdata)
798                                 break;
799                         /* fall-through */
800                 default:
801                         /* nothing to do */
802                         return OPERATOR_RUNNING_MODAL;
803         }
804
805         /* run first because screen_opengl_render_anim_step can free oglrender */
806         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, oglrender->scene);
807         
808         if (anim == 0) {
809                 screen_opengl_render_apply(op->customdata);
810                 screen_opengl_render_end(C, op->customdata);
811                 return OPERATOR_FINISHED;
812         }
813         else {
814                 ret = screen_opengl_render_anim_step(C, op);
815         }
816
817         /* stop at the end or on error */
818         if (ret == false) {
819                 return OPERATOR_FINISHED;
820         }
821
822         return OPERATOR_RUNNING_MODAL;
823 }
824
825 static int screen_opengl_render_invoke(bContext *C, wmOperator *op, const wmEvent *event)
826 {
827         OGLRender *oglrender;
828         const bool anim = RNA_boolean_get(op->ptr, "animation");
829
830         if (!screen_opengl_render_init(C, op))
831                 return OPERATOR_CANCELLED;
832
833         if (anim) {
834                 if (!screen_opengl_render_anim_initialize(C, op))
835                         return OPERATOR_CANCELLED;
836         }
837         
838         oglrender = op->customdata;
839         render_view_open(C, event->x, event->y, op->reports);
840         
841         /* view may be changed above (R_OUTPUT_WINDOW) */
842         oglrender->win = CTX_wm_window(C);
843
844         WM_event_add_modal_handler(C, op);
845         oglrender->timer = WM_event_add_timer(oglrender->wm, oglrender->win, TIMER, 0.01f);
846         
847         return OPERATOR_RUNNING_MODAL;
848 }
849
850 /* executes blocking render */
851 static int screen_opengl_render_exec(bContext *C, wmOperator *op)
852 {
853         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
854
855         if (!screen_opengl_render_init(C, op))
856                 return OPERATOR_CANCELLED;
857
858         if (!is_animation) { /* same as invoke */
859                 /* render image */
860                 screen_opengl_render_apply(op->customdata);
861                 screen_opengl_render_end(C, op->customdata);
862
863                 return OPERATOR_FINISHED;
864         }
865         else {
866                 bool ret = true;
867
868                 if (!screen_opengl_render_anim_initialize(C, op))
869                         return OPERATOR_CANCELLED;
870
871                 while (ret) {
872                         ret = screen_opengl_render_anim_step(C, op);
873                 }
874         }
875
876         /* no redraw needed, we leave state as we entered it */
877 //      ED_update_for_newframe(C, 1);
878         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, CTX_data_scene(C));
879
880         return OPERATOR_FINISHED;
881 }
882
883 void RENDER_OT_opengl(wmOperatorType *ot)
884 {
885         PropertyRNA *prop;
886
887         /* identifiers */
888         ot->name = "OpenGL Render";
889         ot->description = "OpenGL render active viewport";
890         ot->idname = "RENDER_OT_opengl";
891
892         /* api callbacks */
893         ot->invoke = screen_opengl_render_invoke;
894         ot->exec = screen_opengl_render_exec; /* blocking */
895         ot->modal = screen_opengl_render_modal;
896         ot->cancel = screen_opengl_render_cancel;
897
898         ot->poll = ED_operator_screenactive;
899
900         prop = RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
901         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
902         prop = RNA_def_boolean(ot->srna, "sequencer", 0, "Sequencer", "Render using the sequencer's OpenGL display");
903         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
904         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)");
905         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
906         prop = RNA_def_boolean(ot->srna, "view_context", 1, "View Context", "Use the current 3D view for rendering, else use scene settings");
907         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
908
909 }
910
911 /* function for getting an opengl buffer from a View3D, used by sequencer */
912 // extern void *sequencer_view3d_cb;