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