image format arg parsing for creator.c
[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 <GL/glew.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_editVert.h"
41 #include "BLI_dlrbTree.h"
42 #include "BLI_utildefines.h"
43
44 #include "DNA_scene_types.h"
45 #include "DNA_object_types.h"
46
47 #include "BKE_context.h"
48 #include "BKE_image.h"
49 #include "BKE_main.h"
50 #include "BKE_report.h"
51 #include "BKE_scene.h"
52 #include "BKE_writeavi.h"
53
54 #include "WM_api.h"
55 #include "WM_types.h"
56
57 #include "ED_screen.h"
58 #include "ED_view3d.h"
59 #include "ED_image.h"
60
61 #include "RE_pipeline.h"
62 #include "IMB_imbuf_types.h"
63 #include "IMB_imbuf.h"
64
65 #include "RNA_access.h"
66 #include "RNA_define.h"
67
68
69 #include "GPU_extensions.h"
70
71 #include "wm_window.h"
72
73 #include "render_intern.h"
74
75 typedef struct OGLRender {
76         Main *bmain;
77         Render *re;
78         Scene *scene;
79
80         View3D *v3d;
81         RegionView3D *rv3d;
82         ARegion *ar;
83
84         Image *ima;
85         ImageUser iuser;
86
87         GPUOffScreen *ofs;
88         int sizex, sizey;
89         int write_still;
90
91         ReportList *reports;
92         bMovieHandle *mh;
93         int cfrao, nfra;
94
95         wmTimer *timer; /* use to check if running modal or not (invoke'd or exec'd)*/
96 } OGLRender;
97
98 /* added because v3d is not always valid */
99 static unsigned int screen_opengl_layers(OGLRender *oglrender)
100 {
101         if(oglrender->v3d) {
102                 return oglrender->scene->lay | oglrender->v3d->lay;
103         }
104         else {
105                 return oglrender->scene->lay;
106         }
107 }
108
109 static void screen_opengl_render_apply(OGLRender *oglrender)
110 {
111         Scene *scene= oglrender->scene;
112         ARegion *ar= oglrender->ar;
113         View3D *v3d= oglrender->v3d;
114         RegionView3D *rv3d= oglrender->rv3d;
115         RenderResult *rr;
116         Object *camera= NULL;
117         ImBuf *ibuf;
118         void *lock;
119         float winmat[4][4];
120         int sizex= oglrender->sizex;
121         int sizey= oglrender->sizey;
122         const short view_context= (v3d != NULL);
123
124         rr= RE_AcquireResultRead(oglrender->re);
125         
126         /* note on color management:
127          * looked into how best to deal with color management here and found heres how it should work.
128          *
129          * OpenGL materials etc are color corrected, so a float buffer from the graphics card is
130          * color corrected, without running any conversion functions.
131          * 
132          * With color correction disabled blender expects the rr->rectf to be non-color managed so
133          * just do a direct copy from the byte array to the rectf with no conversion too.
134          * notice IMB_float_from_rect has the profile set so no conversion is done.
135          */
136
137         if(view_context) {
138                 GPU_offscreen_bind(oglrender->ofs); /* bind */
139
140                 /* render 3d view */
141                 if(rv3d->persp==RV3D_CAMOB && v3d->camera) {
142                         /*int is_ortho= scene->r.mode & R_ORTHO;*/
143                         camera= v3d->camera;
144                         RE_GetCameraWindow(oglrender->re, camera, scene->r.cfra, winmat);
145                         
146                 }
147                 else {
148                         rctf viewplane;
149                         float clipsta, clipend;
150
151                         int is_ortho= ED_view3d_viewplane_get(v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend);
152                         if(is_ortho) orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend);
153                         else  perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
154                 }
155
156                 if((scene->r.mode & R_OSA) == 0) { 
157                         ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat);
158                         GPU_offscreen_read_pixels(oglrender->ofs, GL_FLOAT, rr->rectf);
159                 }
160                 else {
161                         /* simple accumulation, less hassle then FSAA FBO's */
162 #                       define SAMPLES 5 /* fixed, easy to have more but for now this is ok */
163                         const float jit_ofs[SAMPLES][2] = {{0, 0}, {0.5f, 0.5f}, {-0.5f,-0.5f}, {-0.5f, 0.5f}, {0.5f, -0.5f}};
164                         float winmat_jitter[4][4];
165                         float *accum_buffer= MEM_mallocN(sizex * sizey * sizeof(float) * 4, "accum1");
166                         float *accum_tmp= MEM_mallocN(sizex * sizey * sizeof(float) * 4, "accum2");
167                         int j;
168
169                         /* first sample buffer, also initializes 'rv3d->persmat' */
170                         ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat);
171                         GPU_offscreen_read_pixels(oglrender->ofs, GL_FLOAT, accum_buffer);
172
173                         /* skip the first sample */
174                         for(j=1; j < SAMPLES; j++) {
175                                 copy_m4_m4(winmat_jitter, winmat);
176                                 window_translate_m4(winmat_jitter, rv3d->persmat, jit_ofs[j][0] / sizex, jit_ofs[j][1] / sizey);
177
178                                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat_jitter);
179                                 GPU_offscreen_read_pixels(oglrender->ofs, GL_FLOAT, accum_tmp);
180                                 add_vn_vn(accum_buffer, accum_tmp, sizex*sizey*sizeof(float));
181                         }
182
183                         mul_vn_vn_fl(rr->rectf, accum_buffer, sizex*sizey*sizeof(float), 1.0/SAMPLES);
184
185                         MEM_freeN(accum_buffer);
186                         MEM_freeN(accum_tmp);
187                 }
188
189                 GPU_offscreen_unbind(oglrender->ofs); /* unbind */
190         }
191         else {
192                 /* shouldnt suddenly give errors mid-render but possible */
193                 char err_out[256]= "unknown";
194                 ImBuf *ibuf_view= ED_view3d_draw_offscreen_imbuf_simple(scene, scene->camera, oglrender->sizex, oglrender->sizey, IB_rectfloat, OB_SOLID, err_out);
195                 camera= scene->camera;
196
197                 if(ibuf_view) {
198                         memcpy(rr->rectf, ibuf_view->rect_float, sizeof(float) * 4 * oglrender->sizex * oglrender->sizey);
199                         IMB_freeImBuf(ibuf_view);
200                 }
201                 else {
202                         fprintf(stderr, "screen_opengl_render_apply: failed to get buffer, %s\n", err_out);
203                 }
204         }
205         
206         /* rr->rectf is now filled with image data */
207
208         if((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW))
209                 BKE_stamp_buf(scene, camera, NULL, rr->rectf, rr->rectx, rr->recty, 4);
210
211         RE_ReleaseResult(oglrender->re);
212
213         /* update byte from float buffer */
214         ibuf= BKE_image_acquire_ibuf(oglrender->ima, &oglrender->iuser, &lock);
215
216         if(ibuf) {
217                 image_buffer_rect_update(NULL, rr, ibuf, NULL);
218
219                 if(oglrender->write_still) {
220                         char name[FILE_MAX];
221                         int ok;
222
223                         if(scene->r.im_format.planes == R_IMF_CHAN_DEPTH_8) {
224                                 IMB_color_to_bw(ibuf);
225                         }
226
227                         BKE_makepicstring(name, scene->r.pic, oglrender->bmain->name, scene->r.cfra, scene->r.im_format.imtype, scene->r.scemode & R_EXTENSION, FALSE);
228                         ok= BKE_write_ibuf(ibuf, name, &scene->r.im_format); /* no need to stamp here */
229                         if(ok)  printf("OpenGL Render written to '%s'\n", name);
230                         else    printf("OpenGL Render failed to write '%s'\n", name);
231                 }
232         }
233         
234         BKE_image_release_ibuf(oglrender->ima, lock);
235 }
236
237 static int screen_opengl_render_init(bContext *C, wmOperator *op)
238 {
239         /* new render clears all callbacks */
240         Scene *scene= CTX_data_scene(C);
241         RenderResult *rr;
242         GPUOffScreen *ofs;
243         OGLRender *oglrender;
244         int sizex, sizey;
245         short is_view_context= RNA_boolean_get(op->ptr, "view_context");
246         const short is_animation= RNA_boolean_get(op->ptr, "animation");
247         const short is_write_still= RNA_boolean_get(op->ptr, "write_still");
248         char err_out[256]= "unknown";
249
250         /* ensure we have a 3d view */
251
252         if(!ED_view3d_context_activate(C)) {
253                 RNA_boolean_set(op->ptr, "view_context", 0);
254                 is_view_context= 0;
255         }
256
257         /* only one render job at a time */
258         if(WM_jobs_test(CTX_wm_manager(C), scene))
259                 return 0;
260         
261         if(!is_view_context && scene->camera==NULL) {
262                 BKE_report(op->reports, RPT_ERROR, "Scene has no camera");
263                 return 0;
264         }
265
266         if(!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
267                 BKE_report(op->reports, RPT_ERROR, "Can't write a single file with an animation format selected");
268                 return 0;
269         }
270
271         /* stop all running jobs, currently previews frustrate Render */
272         WM_jobs_stop_all(CTX_wm_manager(C));
273
274         /* handle UI stuff */
275         WM_cursor_wait(1);
276
277         /* create offscreen buffer */
278         sizex= (scene->r.size*scene->r.xsch)/100;
279         sizey= (scene->r.size*scene->r.ysch)/100;
280
281         /* corrects render size with actual size, not every card supports non-power-of-two dimensions */
282         ofs= GPU_offscreen_create(sizex, sizey, err_out);
283
284         if(!ofs) {
285                 BKE_reportf(op->reports, RPT_ERROR, "Failed to create OpenGL offscreen buffer, %s", err_out);
286                 return 0;
287         }
288
289         /* allocate opengl render */
290         oglrender= MEM_callocN(sizeof(OGLRender), "OGLRender");
291         op->customdata= oglrender;
292
293         oglrender->ofs= ofs;
294         oglrender->sizex= sizex;
295         oglrender->sizey= sizey;
296         oglrender->bmain= CTX_data_main(C);
297         oglrender->scene= scene;
298
299         oglrender->write_still= is_write_still && !is_animation;
300
301         if(is_view_context) {
302                 oglrender->v3d= CTX_wm_view3d(C);
303                 oglrender->ar= CTX_wm_region(C);
304                 oglrender->rv3d= CTX_wm_region_view3d(C);
305
306                 /* MUST be cleared on exit */
307                 oglrender->scene->customdata_mask_modal= ED_view3d_datamask(oglrender->scene, oglrender->v3d);
308         }
309
310         /* create image and image user */
311         oglrender->ima= BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
312         BKE_image_signal(oglrender->ima, NULL, IMA_SIGNAL_FREE);
313
314         oglrender->iuser.scene= scene;
315         oglrender->iuser.ok= 1;
316
317         /* create render and render result */
318         oglrender->re= RE_NewRender(scene->id.name);
319         RE_InitState(oglrender->re, NULL, &scene->r, NULL, sizex, sizey, NULL);
320
321         rr= RE_AcquireResultWrite(oglrender->re);
322         if(rr->rectf==NULL)
323                 rr->rectf= MEM_callocN(sizeof(float)*4*sizex*sizey, "screen_opengl_render_init rect");
324         RE_ReleaseResult(oglrender->re);
325
326         return 1;
327 }
328
329 static void screen_opengl_render_end(bContext *C, OGLRender *oglrender)
330 {
331         Main *bmain= CTX_data_main(C);
332         Scene *scene= oglrender->scene;
333
334         if(oglrender->mh) {
335                 if(BKE_imtype_is_movie(scene->r.im_format.imtype))
336                         oglrender->mh->end_movie();
337         }
338
339         if(oglrender->timer) { /* exec will not have a timer */
340                 scene->r.cfra= oglrender->cfrao;
341                 scene_update_for_newframe(bmain, scene, screen_opengl_layers(oglrender));
342
343                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), oglrender->timer);
344         }
345
346         WM_cursor_wait(0);
347         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, oglrender->scene);
348
349         GPU_offscreen_free(oglrender->ofs);
350
351         oglrender->scene->customdata_mask_modal= 0;
352
353         MEM_freeN(oglrender);
354 }
355
356 static int screen_opengl_render_cancel(bContext *C, wmOperator *op)
357 {
358         screen_opengl_render_end(C, op->customdata);
359
360         return OPERATOR_CANCELLED;
361 }
362
363 /* share between invoke and exec */
364 static int screen_opengl_render_anim_initialize(bContext *C, wmOperator *op)
365 {
366         /* initialize animation */
367         OGLRender *oglrender;
368         Scene *scene;
369
370         oglrender= op->customdata;
371         scene= oglrender->scene;
372
373         oglrender->reports= op->reports;
374         oglrender->mh= BKE_get_movie_handle(scene->r.im_format.imtype);
375         if(BKE_imtype_is_movie(scene->r.im_format.imtype)) {
376                 if(!oglrender->mh->start_movie(scene, &scene->r, oglrender->sizex, oglrender->sizey, oglrender->reports)) {
377                         screen_opengl_render_end(C, oglrender);
378                         return 0;
379                 }
380         }
381
382         oglrender->cfrao= scene->r.cfra;
383         oglrender->nfra= PSFRA;
384         scene->r.cfra= PSFRA;
385
386         return 1;
387 }
388 static int screen_opengl_render_anim_step(bContext *C, wmOperator *op)
389 {
390         Main *bmain= CTX_data_main(C);
391         OGLRender *oglrender= op->customdata;
392         Scene *scene= oglrender->scene;
393         ImBuf *ibuf;
394         void *lock;
395         char name[FILE_MAXDIR+FILE_MAXFILE];
396         int ok= 0;
397         const short  view_context= (oglrender->v3d != NULL);
398         Object *camera= NULL;
399
400         /* update animated image textures for gpu, etc,
401          * call before scene_update_for_newframe so modifiers with textuers dont lag 1 frame */
402         ED_image_update_frame(bmain, scene->r.cfra);
403
404         /* go to next frame */
405         while(CFRA<oglrender->nfra) {
406                 unsigned int lay= screen_opengl_layers(oglrender);
407
408                 if(lay & 0xFF000000)
409                         lay &= 0xFF000000;
410
411                 scene_update_for_newframe(bmain, scene, lay);
412                 CFRA++;
413         }
414
415         scene_update_for_newframe(bmain, scene, screen_opengl_layers(oglrender));
416
417         if(view_context) {
418                 if(oglrender->rv3d->persp==RV3D_CAMOB && oglrender->v3d->camera && oglrender->v3d->scenelock) {
419                         /* since scene_update_for_newframe() is used rather
420                          * then ED_update_for_newframe() the camera needs to be set */
421                         if(scene_camera_switch_update(scene)) {
422                                 oglrender->v3d->camera= scene->camera;
423                         }
424
425                         camera= oglrender->v3d->camera;
426                 }
427         }
428         else {
429                 scene_camera_switch_update(scene);
430
431                 camera= scene->camera;
432         }
433
434         /* render into offscreen buffer */
435         screen_opengl_render_apply(oglrender);
436
437         /* save to disk */
438         ibuf= BKE_image_acquire_ibuf(oglrender->ima, &oglrender->iuser, &lock);
439
440         if(ibuf) {
441                 /* color -> greyscale */
442                 /* editing directly would alter the render view */
443                 if(scene->r.im_format.planes == R_IMF_PLANES_BW) {
444                         ImBuf *ibuf_bw= IMB_dupImBuf(ibuf);
445                         IMB_color_to_bw(ibuf_bw);
446                         // IMB_freeImBuf(ibuf); /* owned by the image */
447                         ibuf= ibuf_bw;
448                 }
449                 else {
450                         /* this is lightweight & doesnt re-alloc the buffers, only do this
451                          * to save the correct bit depth since the image is always RGBA */
452                         ImBuf *ibuf_cpy= IMB_allocImBuf(ibuf->x, ibuf->y, scene->r.im_format.planes, 0);
453                         ibuf_cpy->rect= ibuf->rect;
454                         ibuf_cpy->rect_float= ibuf->rect_float;
455                         ibuf_cpy->zbuf_float= ibuf->zbuf_float;
456                         ibuf= ibuf_cpy;
457                 }
458
459                 if(BKE_imtype_is_movie(scene->r.im_format.imtype)) {
460                         ok= oglrender->mh->append_movie(&scene->r, CFRA, (int*)ibuf->rect, oglrender->sizex, oglrender->sizey, oglrender->reports);
461                         if(ok) {
462                                 printf("Append frame %d", scene->r.cfra);
463                                 BKE_reportf(op->reports, RPT_INFO, "Appended frame: %d", scene->r.cfra);
464                         }
465                 }
466                 else {
467                         BKE_makepicstring(name, scene->r.pic, oglrender->bmain->name, scene->r.cfra, scene->r.im_format.imtype, scene->r.scemode & R_EXTENSION, TRUE);
468                         ok= BKE_write_ibuf_stamp(scene, camera, ibuf, name, &scene->r.im_format);
469
470                         if(ok==0) {
471                                 printf("Write error: cannot save %s\n", name);
472                                 BKE_reportf(op->reports, RPT_ERROR, "Write error: cannot save %s", name);
473                         }
474                         else {
475                                 printf("Saved: %s", name);
476                                 BKE_reportf(op->reports, RPT_INFO, "Saved file: %s", name);
477                         }
478                 }
479
480                 /* imbuf knows which rects are not part of ibuf */
481                 IMB_freeImBuf(ibuf);
482         }
483
484         BKE_image_release_ibuf(oglrender->ima, lock);
485
486         /* movie stats prints have no line break */
487         printf("\n");
488
489         /* go to next frame */
490         oglrender->nfra += scene->r.frame_step;
491         scene->r.cfra++;
492
493         /* stop at the end or on error */
494         if(scene->r.cfra > PEFRA || !ok) {
495                 screen_opengl_render_end(C, op->customdata);
496                 return 0;
497         }
498
499         return 1;
500 }
501
502
503 static int screen_opengl_render_modal(bContext *C, wmOperator *op, wmEvent *event)
504 {
505         OGLRender *oglrender= op->customdata;
506         int anim= RNA_boolean_get(op->ptr, "animation");
507         int ret;
508
509         switch(event->type) {
510                 case ESCKEY:
511                         /* cancel */
512                         screen_opengl_render_end(C, op->customdata);
513                         return OPERATOR_FINISHED;
514                 case TIMER:
515                         /* render frame? */
516                         if(oglrender->timer == event->customdata)
517                                 break;
518                 default:
519                         /* nothing to do */
520                         return OPERATOR_RUNNING_MODAL;
521         }
522
523         /* run first because screen_opengl_render_anim_step can free oglrender */
524         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, oglrender->scene);
525         
526         if(anim == 0) {
527                 screen_opengl_render_apply(op->customdata);
528                 screen_opengl_render_end(C, op->customdata);
529                 return OPERATOR_FINISHED;
530         }
531         else
532                 ret= screen_opengl_render_anim_step(C, op);
533
534         /* stop at the end or on error */
535         if(ret == 0) {
536                 return OPERATOR_FINISHED;
537         }
538
539         return OPERATOR_RUNNING_MODAL;
540 }
541
542 static int screen_opengl_render_invoke(bContext *C, wmOperator *op, wmEvent *event)
543 {
544         OGLRender *oglrender;
545         int anim= RNA_boolean_get(op->ptr, "animation");
546
547         if(!screen_opengl_render_init(C, op))
548                 return OPERATOR_CANCELLED;
549
550         if(anim) {
551                 if(!screen_opengl_render_anim_initialize(C, op))
552                         return OPERATOR_CANCELLED;
553         }
554         
555         oglrender= op->customdata;
556         render_view_open(C, event->x, event->y);
557         
558         WM_event_add_modal_handler(C, op);
559         oglrender->timer= WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.01f);
560         
561         return OPERATOR_RUNNING_MODAL;
562 }
563
564 /* executes blocking render */
565 static int screen_opengl_render_exec(bContext *C, wmOperator *op)
566 {
567         const short is_animation= RNA_boolean_get(op->ptr, "animation");
568
569         if(!screen_opengl_render_init(C, op))
570                 return OPERATOR_CANCELLED;
571
572         if(!is_animation) { /* same as invoke */
573                 /* render image */
574                 screen_opengl_render_apply(op->customdata);
575                 screen_opengl_render_end(C, op->customdata);
576
577                 return OPERATOR_FINISHED;
578         }
579         else {
580                 int ret= 1;
581
582                 if(!screen_opengl_render_anim_initialize(C, op))
583                         return OPERATOR_CANCELLED;
584
585                 while(ret) {
586                         ret= screen_opengl_render_anim_step(C, op);
587                 }
588         }
589
590         // no redraw needed, we leave state as we entered it
591 //      ED_update_for_newframe(C, 1);
592         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, CTX_data_scene(C));
593
594         return OPERATOR_FINISHED;
595 }
596
597 void RENDER_OT_opengl(wmOperatorType *ot)
598 {
599         /* identifiers */
600         ot->name= "OpenGL Render";
601         ot->description= "OpenGL render active viewport";
602         ot->idname= "RENDER_OT_opengl";
603
604         /* api callbacks */
605         ot->invoke= screen_opengl_render_invoke;
606         ot->exec= screen_opengl_render_exec; /* blocking */
607         ot->modal= screen_opengl_render_modal;
608         ot->cancel= screen_opengl_render_cancel;
609
610         ot->poll= ED_operator_screenactive;
611
612         RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
613         RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
614         RNA_def_boolean(ot->srna, "view_context", 1, "View Context", "Use the current 3D view for rendering, else use scene settings");
615 }
616
617 /* function for getting an opengl buffer from a View3D, used by sequencer */
618 // extern void *sequencer_view3d_cb;