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