Merging r57729 through r57815 from trunk into soc-2013-depsgraph_mt
[blender.git] / source / blender / editors / render / render_internal.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_internal.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 "BLI_blenlib.h"
37 #include "BLI_math.h"
38 #include "BLI_threads.h"
39 #include "BLI_utildefines.h"
40
41 #include "PIL_time.h"
42
43 #include "BLF_translation.h"
44
45 #include "DNA_object_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_view3d_types.h"
48 #include "DNA_userdef_types.h"
49
50 #include "BKE_blender.h"
51 #include "BKE_context.h"
52 #include "BKE_depsgraph.h"
53 #include "BKE_freestyle.h"
54 #include "BKE_global.h"
55 #include "BKE_image.h"
56 #include "BKE_library.h"
57 #include "BKE_main.h"
58 #include "BKE_node.h"
59 #include "BKE_multires.h"
60 #include "BKE_paint.h"
61 #include "BKE_report.h"
62 #include "BKE_sequencer.h"
63 #include "BKE_screen.h"
64 #include "BKE_scene.h"
65
66 #include "WM_api.h"
67 #include "WM_types.h"
68
69 #include "ED_object.h"
70 #include "ED_render.h"
71 #include "ED_screen.h"
72 #include "ED_view3d.h"
73
74 #include "RE_pipeline.h"
75 #include "RE_engine.h"
76
77 #include "IMB_colormanagement.h"
78 #include "IMB_imbuf.h"
79 #include "IMB_imbuf_types.h"
80
81 #include "GPU_extensions.h"
82
83 #include "BIF_gl.h"
84 #include "BIF_glutil.h"
85
86 #include "RNA_access.h"
87 #include "RNA_define.h"
88
89 #include "wm_window.h"
90
91 #include "render_intern.h"
92
93 /* Render Callbacks */
94 static int render_break(void *rjv);
95
96 /* called inside thread! */
97 void image_buffer_rect_update(Scene *scene, RenderResult *rr, ImBuf *ibuf, volatile rcti *renrect)
98 {
99         float *rectf = NULL;
100         int ymin, ymax, xmin, xmax;
101         int rymin, rxmin;
102
103         /* if renrect argument, we only refresh scanlines */
104         if (renrect) {
105                 /* if (ymax == recty), rendering of layer is ready, we should not draw, other things happen... */
106                 if (rr->renlay == NULL || renrect->ymax >= rr->recty)
107                         return;
108
109                 /* xmin here is first subrect x coord, xmax defines subrect width */
110                 xmin = renrect->xmin + rr->crop;
111                 xmax = renrect->xmax - xmin + rr->crop;
112                 if (xmax < 2)
113                         return;
114
115                 ymin = renrect->ymin + rr->crop;
116                 ymax = renrect->ymax - ymin + rr->crop;
117                 if (ymax < 2)
118                         return;
119                 renrect->ymin = renrect->ymax;
120
121         }
122         else {
123                 xmin = ymin = rr->crop;
124                 xmax = rr->rectx - 2 * rr->crop;
125                 ymax = rr->recty - 2 * rr->crop;
126         }
127
128         /* xmin ymin is in tile coords. transform to ibuf */
129         rxmin = rr->tilerect.xmin + xmin;
130         if (rxmin >= ibuf->x) return;
131         rymin = rr->tilerect.ymin + ymin;
132         if (rymin >= ibuf->y) return;
133
134         if (rxmin + xmax > ibuf->x)
135                 xmax = ibuf->x - rxmin;
136         if (rymin + ymax > ibuf->y)
137                 ymax = ibuf->y - rymin;
138
139         if (xmax < 1 || ymax < 1) return;
140
141         /* find current float rect for display, first case is after composite... still weak */
142         if (rr->rectf)
143                 rectf = rr->rectf;
144         else {
145                 if (rr->rect32) {
146                         /* special case, currently only happens with sequencer rendering,
147                          * which updates the whole frame, so we can only mark display buffer
148                          * as invalid here (sergey)
149                          */
150                         ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
151                         return;
152                 }
153                 else {
154                         if (rr->renlay == NULL || rr->renlay->rectf == NULL) return;
155                         rectf = rr->renlay->rectf;
156                 }
157         }
158         if (rectf == NULL) return;
159
160         if (ibuf->rect == NULL)
161                 imb_addrectImBuf(ibuf);
162
163         rectf += 4 * (rr->rectx * ymin + xmin);
164
165         IMB_partial_display_buffer_update(ibuf, rectf, NULL, rr->rectx, rxmin, rymin,
166                                           &scene->view_settings, &scene->display_settings,
167                                           rxmin, rymin, rxmin + xmax, rymin + ymax, TRUE);
168 }
169
170 /* ****************************** render invoking ***************** */
171
172 /* set callbacks, exported to sequence render too.
173  * Only call in foreground (UI) renders. */
174
175 static void screen_render_scene_layer_set(wmOperator *op, Main *mainp, Scene **scene, SceneRenderLayer **srl)
176 {
177         /* single layer re-render */
178         if (RNA_struct_property_is_set(op->ptr, "scene")) {
179                 Scene *scn;
180                 char scene_name[MAX_ID_NAME - 2];
181
182                 RNA_string_get(op->ptr, "scene", scene_name);
183                 scn = (Scene *)BLI_findstring(&mainp->scene, scene_name, offsetof(ID, name) + 2);
184                 
185                 if (scn) {
186                         /* camera switch wont have updated */
187                         scn->r.cfra = (*scene)->r.cfra;
188                         BKE_scene_camera_switch_update(scn);
189
190                         *scene = scn;
191                 }
192         }
193
194         if (RNA_struct_property_is_set(op->ptr, "layer")) {
195                 SceneRenderLayer *rl;
196                 char rl_name[RE_MAXNAME];
197
198                 RNA_string_get(op->ptr, "layer", rl_name);
199                 rl = (SceneRenderLayer *)BLI_findstring(&(*scene)->r.layers, rl_name, offsetof(SceneRenderLayer, name));
200                 
201                 if (rl)
202                         *srl = rl;
203         }
204 }
205
206 /* executes blocking render */
207 static int screen_render_exec(bContext *C, wmOperator *op)
208 {
209         Scene *scene = CTX_data_scene(C);
210         SceneRenderLayer *srl = NULL;
211         Render *re;
212         Image *ima;
213         View3D *v3d = CTX_wm_view3d(C);
214         Main *mainp = CTX_data_main(C);
215         unsigned int lay;
216         const short is_animation = RNA_boolean_get(op->ptr, "animation");
217         const short is_write_still = RNA_boolean_get(op->ptr, "write_still");
218         struct Object *camera_override = v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
219
220         /* custom scene and single layer re-render */
221         screen_render_scene_layer_set(op, mainp, &scene, &srl);
222
223         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
224                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
225                 return OPERATOR_CANCELLED;
226         }
227
228         re = RE_NewRender(scene->id.name);
229         lay = (v3d) ? v3d->lay : scene->lay;
230
231         G.is_break = FALSE;
232         RE_test_break_cb(re, NULL, render_break);
233
234         ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
235         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
236         BKE_image_backup_render(scene, ima);
237
238         /* cleanup sequencer caches before starting user triggered render.
239          * otherwise, invalidated cache entries can make their way into
240          * the output rendering. We can't put that into RE_BlenderFrame,
241          * since sequence rendering can call that recursively... (peter) */
242         BKE_sequencer_cache_cleanup();
243
244         RE_SetReports(re, op->reports);
245
246         if (is_animation)
247                 RE_BlenderAnim(re, mainp, scene, camera_override, lay, scene->r.sfra, scene->r.efra, scene->r.frame_step);
248         else
249                 RE_BlenderFrame(re, mainp, scene, srl, camera_override, lay, scene->r.cfra, is_write_still);
250
251         RE_SetReports(re, NULL);
252
253         // no redraw needed, we leave state as we entered it
254         ED_update_for_newframe(mainp, scene, 1);
255
256         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, scene);
257
258         return OPERATOR_FINISHED;
259 }
260
261 typedef struct RenderJob {
262         Main *main;
263         Scene *scene;
264         Render *re;
265         wmWindow *win;
266         SceneRenderLayer *srl;
267         struct Object *camera_override;
268         int lay;
269         short anim, write_still;
270         Image *image;
271         ImageUser iuser;
272         short *stop;
273         short *do_update;
274         float *progress;
275         ReportList *reports;
276         bool interface_locked;
277 } RenderJob;
278
279 static void render_freejob(void *rjv)
280 {
281         RenderJob *rj = rjv;
282
283         MEM_freeN(rj);
284 }
285
286 /* str is IMA_MAX_RENDER_TEXT in size */
287 static void make_renderinfo_string(RenderStats *rs, Scene *scene, char *str)
288 {
289         char info_time_str[32]; // used to be extern to header_info.c
290         uintptr_t mem_in_use, mmap_in_use, peak_memory;
291         float megs_used_memory, mmap_used_memory, megs_peak_memory;
292         char *spos = str;
293
294         mem_in_use = MEM_get_memory_in_use();
295         mmap_in_use = MEM_get_mapped_memory_in_use();
296         peak_memory = MEM_get_peak_memory();
297
298         megs_used_memory = (mem_in_use - mmap_in_use) / (1024.0 * 1024.0);
299         mmap_used_memory = (mmap_in_use) / (1024.0 * 1024.0);
300         megs_peak_memory = (peak_memory) / (1024.0 * 1024.0);
301
302         /* local view */
303         if (rs->localview)
304                 spos += sprintf(spos, "%s | ", IFACE_("Local View"));
305
306         /* frame number */
307         spos += sprintf(spos, IFACE_("Frame:%d "), (scene->r.cfra));
308
309         /* previous and elapsed time */
310         BLI_timestr(rs->lastframetime, info_time_str, sizeof(info_time_str));
311
312         if (rs->infostr && rs->infostr[0]) {
313                 if (rs->lastframetime != 0.0)
314                         spos += sprintf(spos, IFACE_("| Last:%s "), info_time_str);
315                 else
316                         spos += sprintf(spos, "| ");
317
318                 BLI_timestr(PIL_check_seconds_timer() - rs->starttime, info_time_str, sizeof(info_time_str));
319         }
320         else
321                 spos += sprintf(spos, "| ");
322
323         spos += sprintf(spos, IFACE_("Time:%s "), info_time_str);
324
325         /* statistics */
326         if (rs->statstr) {
327                 if (rs->statstr[0]) {
328                         spos += sprintf(spos, "| %s ", rs->statstr);
329                 }
330         }
331         else {
332                 if (rs->totvert || rs->totface || rs->tothalo || rs->totstrand || rs->totlamp)
333                         spos += sprintf(spos, "| ");
334
335                 if (rs->totvert) spos += sprintf(spos, IFACE_("Ve:%d "), rs->totvert);
336                 if (rs->totface) spos += sprintf(spos, IFACE_("Fa:%d "), rs->totface);
337                 if (rs->tothalo) spos += sprintf(spos, IFACE_("Ha:%d "), rs->tothalo);
338                 if (rs->totstrand) spos += sprintf(spos, IFACE_("St:%d "), rs->totstrand);
339                 if (rs->totlamp) spos += sprintf(spos, IFACE_("La:%d "), rs->totlamp);
340
341                 if (rs->mem_peak == 0.0f)
342                         spos += sprintf(spos, IFACE_("| Mem:%.2fM (%.2fM, Peak %.2fM) "),
343                                         megs_used_memory, mmap_used_memory, megs_peak_memory);
344                 else
345                         spos += sprintf(spos, IFACE_("| Mem:%.2fM, Peak: %.2fM "), rs->mem_used, rs->mem_peak);
346
347                 if (rs->curfield)
348                         spos += sprintf(spos, IFACE_("Field %d "), rs->curfield);
349                 if (rs->curblur)
350                         spos += sprintf(spos, IFACE_("Blur %d "), rs->curblur);
351         }
352
353         /* full sample */
354         if (rs->curfsa)
355                 spos += sprintf(spos, IFACE_("| Full Sample %d "), rs->curfsa);
356         
357         /* extra info */
358         if (rs->infostr && rs->infostr[0])
359                 spos += sprintf(spos, "| %s ", rs->infostr);
360
361         /* very weak... but 512 characters is quite safe */
362         if (spos >= str + IMA_MAX_RENDER_TEXT)
363                 if (G.debug & G_DEBUG)
364                         printf("WARNING! renderwin text beyond limit\n");
365
366 }
367
368 static void image_renderinfo_cb(void *rjv, RenderStats *rs)
369 {
370         RenderJob *rj = rjv;
371         RenderResult *rr;
372
373         rr = RE_AcquireResultRead(rj->re);
374
375         if (rr) {
376                 /* malloc OK here, stats_draw is not in tile threads */
377                 if (rr->text == NULL)
378                         rr->text = MEM_callocN(IMA_MAX_RENDER_TEXT, "rendertext");
379
380                 make_renderinfo_string(rs, rj->scene, rr->text);
381         }
382
383         RE_ReleaseResult(rj->re);
384
385         /* make jobs timer to send notifier */
386         *(rj->do_update) = TRUE;
387
388 }
389
390 static void render_progress_update(void *rjv, float progress)
391 {
392         RenderJob *rj = rjv;
393         
394         if (rj->progress && *rj->progress != progress) {
395                 *rj->progress = progress;
396
397                 /* make jobs timer to send notifier */
398                 *(rj->do_update) = TRUE;
399         }
400 }
401
402 static void image_rect_update(void *rjv, RenderResult *rr, volatile rcti *renrect)
403 {
404         RenderJob *rj = rjv;
405         Image *ima = rj->image;
406         ImBuf *ibuf;
407         void *lock;
408
409         /* only update if we are displaying the slot being rendered */
410         if (ima->render_slot != ima->last_render_slot)
411                 return;
412
413         ibuf = BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
414         if (ibuf) {
415                 image_buffer_rect_update(rj->scene, rr, ibuf, renrect);
416
417                 /* make jobs timer to send notifier */
418                 *(rj->do_update) = TRUE;
419         }
420         BKE_image_release_ibuf(ima, ibuf, lock);
421 }
422
423 static void render_startjob(void *rjv, short *stop, short *do_update, float *progress)
424 {
425         RenderJob *rj = rjv;
426
427         rj->stop = stop;
428         rj->do_update = do_update;
429         rj->progress = progress;
430
431         RE_SetReports(rj->re, rj->reports);
432
433         if (rj->anim)
434                 RE_BlenderAnim(rj->re, rj->main, rj->scene, rj->camera_override, rj->lay, rj->scene->r.sfra, rj->scene->r.efra, rj->scene->r.frame_step);
435         else
436                 RE_BlenderFrame(rj->re, rj->main, rj->scene, rj->srl, rj->camera_override, rj->lay, rj->scene->r.cfra, rj->write_still);
437
438         RE_SetReports(rj->re, NULL);
439 }
440
441 static void render_endjob(void *rjv)
442 {
443         RenderJob *rj = rjv;
444
445         /* this render may be used again by the sequencer without the active 'Render' where the callbacks
446          * would be re-assigned. assign dummy callbacks to avoid referencing freed renderjobs bug [#24508] */
447         RE_InitRenderCB(rj->re);
448
449         if (rj->main != G.main)
450                 free_main(rj->main);
451
452         /* else the frame will not update for the original value */
453         if (rj->anim && !(rj->scene->r.scemode & R_NO_FRAME_UPDATE)) {
454                 /* possible this fails of loading new file while rendering */
455                 if (G.main->wm.first) {
456                         ED_update_for_newframe(G.main, rj->scene, 1);
457                 }
458         }
459         
460         /* XXX above function sets all tags in nodes */
461         ntreeCompositClearTags(rj->scene->nodetree);
462         
463         /* potentially set by caller */
464         rj->scene->r.scemode &= ~R_NO_FRAME_UPDATE;
465         
466         if (rj->srl) {
467                 nodeUpdateID(rj->scene->nodetree, &rj->scene->id);
468                 WM_main_add_notifier(NC_NODE | NA_EDITED, rj->scene);
469         }
470
471         /* XXX render stability hack */
472         G.is_rendering = FALSE;
473         WM_main_add_notifier(NC_SCENE | ND_RENDER_RESULT, NULL);
474
475         /* Partial render result will always update display buffer
476          * for first render layer only. This is nice because you'll
477          * see render progress during rendering, but it ends up in
478          * wrong display buffer shown after rendering.
479          *
480          * The code below will mark display buffer as invalid after
481          * rendering in case multiple layers were rendered, which
482          * ensures display buffer matches render layer after
483          * rendering.
484          *
485          * Perhaps proper way would be to toggle active render
486          * layer in image editor and job, so we always display
487          * layer being currently rendered. But this is not so much
488          * trivial at this moment, especially because of external
489          * engine API, so lets use simple and robust way for now
490          *                                          - sergey -
491          */
492         if (rj->scene->r.layers.first != rj->scene->r.layers.last) {
493                 void *lock;
494                 Image *ima = rj->image;
495                 ImBuf *ibuf = BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
496
497                 if (ibuf)
498                         ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
499
500                 BKE_image_release_ibuf(ima, ibuf, lock);
501         }
502
503         /* Finally unlock the user interface (if it was locked). */
504         if (rj->interface_locked) {
505                 /* Interface was locked, so window manager couldn't have been changed
506                  * and using one from Global will unlock exactly the same manager as
507                  * was locked before running the job.
508                  */
509                 WM_set_locked_interface(G.main->wm.first, false);
510         }
511 }
512
513 /* called by render, check job 'stop' value or the global */
514 static int render_breakjob(void *rjv)
515 {
516         RenderJob *rj = rjv;
517
518         if (G.is_break)
519                 return 1;
520         if (rj->stop && *(rj->stop))
521                 return 1;
522         return 0;
523 }
524
525 /* for exec() when there is no render job
526  * note: this wont check for the escape key being pressed, but doing so isnt threadsafe */
527 static int render_break(void *UNUSED(rjv))
528 {
529         if (G.is_break)
530                 return 1;
531         return 0;
532 }
533
534 /* runs in thread, no cursor setting here works. careful with notifiers too (malloc conflicts) */
535 /* maybe need a way to get job send notifer? */
536 static void render_drawlock(void *rjv, int lock)
537 {
538         RenderJob *rj = rjv;
539
540         /* If interface is locked, renderer callback shall do nothing. */
541         if (!rj->interface_locked) {
542                 BKE_spacedata_draw_locks(lock);
543         }
544 }
545
546 /* catch esc */
547 static int screen_render_modal(bContext *C, wmOperator *op, const wmEvent *event)
548 {
549         Scene *scene = (Scene *) op->customdata;
550
551         /* no running blender, remove handler and pass through */
552         if (0 == WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_RENDER)) {
553                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
554         }
555
556         /* running render */
557         switch (event->type) {
558                 case ESCKEY:
559                         return OPERATOR_RUNNING_MODAL;
560                         break;
561         }
562         return OPERATOR_PASS_THROUGH;
563 }
564
565 /* using context, starts job */
566 static int screen_render_invoke(bContext *C, wmOperator *op, const wmEvent *event)
567 {
568         /* new render clears all callbacks */
569         Main *mainp;
570         Scene *scene = CTX_data_scene(C);
571         SceneRenderLayer *srl = NULL;
572         View3D *v3d = CTX_wm_view3d(C);
573         Render *re;
574         wmJob *wm_job;
575         RenderJob *rj;
576         Image *ima;
577         int jobflag;
578         const short is_animation = RNA_boolean_get(op->ptr, "animation");
579         const short is_write_still = RNA_boolean_get(op->ptr, "write_still");
580         struct Object *camera_override = v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
581         const char *name;
582         Object *active_object = CTX_data_active_object(C);
583         
584         /* only one render job at a time */
585         if (WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_RENDER))
586                 return OPERATOR_CANCELLED;
587
588         if (!RE_is_rendering_allowed(scene, camera_override, op->reports)) {
589                 return OPERATOR_CANCELLED;
590         }
591
592         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
593                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
594                 return OPERATOR_CANCELLED;
595         }
596         
597         /* stop all running jobs, except screen one. currently previews frustrate Render */
598         WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C));
599
600         /* get main */
601         if (G.debug_value == 101) {
602                 /* thread-safety experiment, copy main from the undo buffer */
603                 mainp = BKE_undo_get_main(&scene);
604         }
605         else
606                 mainp = CTX_data_main(C);
607
608         /* cancel animation playback */
609         if (ED_screen_animation_playing(CTX_wm_manager(C)))
610                 ED_screen_animation_play(C, 0, 0);
611         
612         /* handle UI stuff */
613         WM_cursor_wait(1);
614
615         /* flush multires changes (for sculpt) */
616         multires_force_render_update(active_object);
617
618         /* flush changes from dynamic topology sculpt */
619         sculptsession_bm_to_me_for_render(active_object);
620
621         /* cleanup sequencer caches before starting user triggered render.
622          * otherwise, invalidated cache entries can make their way into
623          * the output rendering. We can't put that into RE_BlenderFrame,
624          * since sequence rendering can call that recursively... (peter) */
625         BKE_sequencer_cache_cleanup();
626
627         /* get editmode results */
628         ED_object_editmode_load(CTX_data_edit_object(C));
629
630         // store spare
631         // get view3d layer, local layer, make this nice api call to render
632         // store spare
633
634         /* ensure at least 1 area shows result */
635         render_view_open(C, event->x, event->y);
636
637         jobflag = WM_JOB_EXCL_RENDER | WM_JOB_PRIORITY | WM_JOB_PROGRESS;
638         
639         /* custom scene and single layer re-render */
640         screen_render_scene_layer_set(op, mainp, &scene, &srl);
641
642         if (RNA_struct_property_is_set(op->ptr, "layer"))
643                 jobflag |= WM_JOB_SUSPEND;
644
645         /* job custom data */
646         rj = MEM_callocN(sizeof(RenderJob), "render job");
647         rj->main = mainp;
648         rj->scene = scene;
649         rj->win = CTX_wm_window(C);
650         rj->srl = srl;
651         rj->camera_override = camera_override;
652         rj->lay = scene->lay;
653         rj->anim = is_animation;
654         rj->write_still = is_write_still && !is_animation;
655         rj->iuser.scene = scene;
656         rj->iuser.ok = 1;
657         rj->reports = op->reports;
658
659         if (v3d) {
660                 rj->lay = v3d->lay;
661
662                 if (v3d->localvd)
663                         rj->lay |= v3d->localvd->lay;
664         }
665
666         /* Lock the user interface depending on render settings. */
667         if (scene->r.use_lock_interface) {
668                 WM_set_locked_interface(CTX_wm_manager(C), true);
669
670                 /* Set flag interface need to be unlocked.
671                  *
672                  * This is so because we don't have copy of render settings
673                  * accessible from render job and copy is needed in case
674                  * of non-locked rendering, so we wouldn't try to unlock
675                  * anything if option was initially unset but then was
676                  * enabled during rendering.
677                  */
678                 rj->interface_locked = true;
679
680                 /* TODO(sergey): clean memory used by viewport? */
681         }
682
683         /* setup job */
684         if (RE_seq_render_active(scene, &scene->r)) name = "Sequence Render";
685         else name = "Render";
686
687         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, name, jobflag, WM_JOB_TYPE_RENDER);
688         WM_jobs_customdata_set(wm_job, rj, render_freejob);
689         WM_jobs_timer(wm_job, 0.2, NC_SCENE | ND_RENDER_RESULT, 0);
690         WM_jobs_callbacks(wm_job, render_startjob, NULL, NULL, render_endjob);
691
692         /* get a render result image, and make sure it is empty */
693         ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
694         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
695         BKE_image_backup_render(rj->scene, ima);
696         rj->image = ima;
697
698         /* setup new render */
699         re = RE_NewRender(scene->id.name);
700         RE_test_break_cb(re, rj, render_breakjob);
701         RE_draw_lock_cb(re, rj, render_drawlock);
702         RE_display_draw_cb(re, rj, image_rect_update);
703         RE_stats_draw_cb(re, rj, image_renderinfo_cb);
704         RE_progress_cb(re, rj, render_progress_update);
705
706         rj->re = re;
707         G.is_break = FALSE;
708
709         /* store actual owner of job, so modal operator could check for it,
710          * the reason of this is that active scene could change when rendering
711          * several layers from compositor [#31800]
712          */
713         op->customdata = scene;
714
715         WM_jobs_start(CTX_wm_manager(C), wm_job);
716
717         WM_cursor_wait(0);
718         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, scene);
719
720         /* we set G.is_rendering here already instead of only in the job, this ensure
721          * main loop or other scene updates are disabled in time, since they may
722          * have started before the job thread */
723         G.is_rendering = TRUE;
724
725         /* add modal handler for ESC */
726         WM_event_add_modal_handler(C, op);
727
728         return OPERATOR_RUNNING_MODAL;
729 }
730
731 /* contextual render, using current scene, view3d? */
732 void RENDER_OT_render(wmOperatorType *ot)
733 {
734         PropertyRNA *prop;
735
736         /* identifiers */
737         ot->name = "Render";
738         ot->description = "Render active scene";
739         ot->idname = "RENDER_OT_render";
740
741         /* api callbacks */
742         ot->invoke = screen_render_invoke;
743         ot->modal = screen_render_modal;
744         ot->exec = screen_render_exec;
745
746         /*ot->poll = ED_operator_screenactive;*/ /* this isn't needed, causes failer in background mode */
747
748         RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
749         RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
750         prop = RNA_def_string(ot->srna, "layer", "", RE_MAXNAME, "Render Layer", "Single render layer to re-render (used only when animation is disabled)");
751         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
752         prop = RNA_def_string(ot->srna, "scene", "", MAX_ID_NAME - 2, "Scene", "Scene to render, current scene if not specified");
753         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
754 }
755
756
757 /* ************** preview for 3d viewport ***************** */
758
759 #define PR_UPDATE_VIEW                          1
760 #define PR_UPDATE_RENDERSIZE            2
761 #define PR_UPDATE_MATERIAL                      4
762
763 typedef struct RenderPreview {
764         /* from wmJob */
765         void *owner;
766         short *stop, *do_update;
767         
768         Scene *scene;
769         ScrArea *sa;
770         ARegion *ar;
771         View3D *v3d;
772         RegionView3D *rv3d;
773         Main *bmain;
774         RenderEngine *engine;
775         
776         float viewmat[4][4];
777         
778         int keep_data;
779 } RenderPreview;
780
781 static int render_view3d_disprect(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D *rv3d, rcti *disprect)
782 {
783         /* copied code from view3d_draw.c */
784         rctf viewborder;
785         int draw_border;
786         
787         if (rv3d->persp == RV3D_CAMOB)
788                 draw_border = (scene->r.mode & R_BORDER) != 0;
789         else
790                 draw_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
791
792         if (draw_border) {
793                 if (rv3d->persp == RV3D_CAMOB) {
794                         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
795                         
796                         disprect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
797                         disprect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
798                         disprect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
799                         disprect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
800                 }
801                 else {
802                         disprect->xmin = v3d->render_border.xmin * ar->winx;
803                         disprect->xmax = v3d->render_border.xmax * ar->winx;
804                         disprect->ymin = v3d->render_border.ymin * ar->winy;
805                         disprect->ymax = v3d->render_border.ymax * ar->winy;
806                 }
807                 
808                 return 1;
809         }
810         
811         BLI_rcti_init(disprect, 0, 0, 0, 0);
812         return 0;
813 }
814
815 /* returns true if OK  */
816 static bool render_view3d_get_rects(ARegion *ar, View3D *v3d, RegionView3D *rv3d, rctf *viewplane, RenderEngine *engine,
817                                     float *r_clipsta, float *r_clipend, float *r_pixsize, bool *r_ortho)
818 {
819         
820         if (ar->winx < 4 || ar->winy < 4) return false;
821         
822         *r_ortho = ED_view3d_viewplane_get(v3d, rv3d, ar->winx, ar->winy, viewplane, r_clipsta, r_clipend, r_pixsize);
823         
824         engine->resolution_x = ar->winx;
825         engine->resolution_y = ar->winy;
826
827         return true;
828 }
829
830 /* called by renderer, checks job value */
831 static int render_view3d_break(void *rpv)
832 {
833         RenderPreview *rp = rpv;
834         
835         if (G.is_break)
836                 return 1;
837         
838         /* during render, rv3d->engine can get freed */
839         if (rp->rv3d->render_engine == NULL)
840                 *rp->stop = 1;
841         
842         return *(rp->stop);
843 }
844
845 static void render_view3d_draw_update(void *rpv, RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect))
846 {
847         RenderPreview *rp = rpv;
848         
849         *(rp->do_update) = TRUE;
850 }
851
852 static void render_view3d_renderinfo_cb(void *rjp, RenderStats *rs)
853 {
854         RenderPreview *rp = rjp;
855
856         /* during render, rv3d->engine can get freed */
857         if (rp->rv3d->render_engine == NULL)
858                 *rp->stop = 1;
859         else if (rp->engine->text) {
860                 make_renderinfo_string(rs, rp->scene, rp->engine->text);
861         
862                 /* make jobs timer to send notifier */
863                 *(rp->do_update) = TRUE;
864         }
865 }
866
867
868 static void render_view3d_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
869 {
870         RenderPreview *rp = customdata;
871         Render *re;
872         RenderStats *rstats;
873         RenderData rdata;
874         rctf viewplane;
875         rcti cliprct;
876         float clipsta, clipend, pixsize;
877         bool orth, restore = 0;
878         char name[32];
879                 
880         G.is_break = FALSE;
881         
882         if (false == render_view3d_get_rects(rp->ar, rp->v3d, rp->rv3d, &viewplane, rp->engine, &clipsta, &clipend, &pixsize, &orth))
883                 return;
884         
885         rp->stop = stop;
886         rp->do_update = do_update;
887
888         // printf("Enter previewrender\n");
889         
890         /* ok, are we rendering all over? */
891         sprintf(name, "View3dPreview %p", (void *)rp->ar);
892         re = rp->engine->re = RE_GetRender(name);
893         
894         if (rp->engine->re == NULL) {
895                 
896                 re = rp->engine->re = RE_NewRender(name);
897                 
898                 rp->keep_data = 0;
899         }
900         
901         /* set this always, rp is different for each job */
902         RE_test_break_cb(re, rp, render_view3d_break);
903         RE_display_draw_cb(re, rp, render_view3d_draw_update);
904         RE_stats_draw_cb(re, rp, render_view3d_renderinfo_cb);
905         
906         rstats = RE_GetStats(re);
907
908         if (rp->keep_data == 0 || rstats->convertdone == 0 || (rp->keep_data & PR_UPDATE_RENDERSIZE)) {
909                 /* no osa, blur, seq, layers, etc for preview render */
910                 rdata = rp->scene->r;
911                 rdata.mode &= ~(R_OSA | R_MBLUR | R_BORDER | R_PANORAMA);
912                 rdata.scemode &= ~(R_DOSEQ | R_DOCOMP | R_FREE_IMAGE);
913                 rdata.scemode |= R_VIEWPORT_PREVIEW;
914                 
915                 /* we do use layers, but only active */
916                 rdata.scemode |= R_SINGLE_LAYER;
917
918                 /* initalize always */
919                 if (render_view3d_disprect(rp->scene, rp->ar, rp->v3d, rp->rv3d, &cliprct)) {
920                         rdata.mode |= R_BORDER;
921                         RE_InitState(re, NULL, &rdata, NULL, rp->ar->winx, rp->ar->winy, &cliprct);
922                 }
923                 else
924                         RE_InitState(re, NULL, &rdata, NULL, rp->ar->winx, rp->ar->winy, NULL);
925         }
926
927         if (orth)
928                 RE_SetOrtho(re, &viewplane, clipsta, clipend);
929         else
930                 RE_SetWindow(re, &viewplane, clipsta, clipend);
931
932         RE_SetPixelSize(re, pixsize);
933         
934         /* database free can crash on a empty Render... */
935         if (rp->keep_data == 0 && rstats->convertdone)
936                 RE_Database_Free(re);
937
938         if (rstats->convertdone == 0) {
939                 unsigned int lay = rp->scene->lay;
940
941                 /* allow localview render for objects with lights in normal layers */
942                 if (rp->v3d->lay & 0xFF000000)
943                         lay |= rp->v3d->lay;
944                 else lay = rp->v3d->lay;
945                 
946                 RE_SetView(re, rp->viewmat);
947                 
948                 RE_Database_FromScene(re, rp->bmain, rp->scene, lay, 0);                // 0= dont use camera view
949                 // printf("dbase update\n");
950         }
951         else {
952                 // printf("dbase rotate\n");
953                 RE_DataBase_IncrementalView(re, rp->viewmat, 0);
954                 restore = 1;
955         }
956
957         RE_DataBase_ApplyWindow(re);
958
959         /* OK, can we enter render code? */
960         if (rstats->convertdone) {
961                 RE_TileProcessor(re);
962                 
963                 /* always rotate back */
964                 if (restore)
965                         RE_DataBase_IncrementalView(re, rp->viewmat, 1);
966
967                 rp->engine->flag &= ~RE_ENGINE_DO_UPDATE;
968         }
969 }
970
971 static void render_view3d_free(void *customdata)
972 {
973         RenderPreview *rp = customdata;
974         
975         MEM_freeN(rp);
976 }
977
978 static void render_view3d_do(RenderEngine *engine, const bContext *C, int keep_data)
979 {
980         wmJob *wm_job;
981         RenderPreview *rp;
982         Scene *scene = CTX_data_scene(C);
983         
984         if (CTX_wm_window(C) == NULL) {
985                 engine->flag |= RE_ENGINE_DO_UPDATE;
986                 return;
987         }
988
989         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), CTX_wm_region(C), "Render Preview",
990                              WM_JOB_EXCL_RENDER, WM_JOB_TYPE_RENDER_PREVIEW);
991         rp = MEM_callocN(sizeof(RenderPreview), "render preview");
992         
993         /* customdata for preview thread */
994         rp->scene = scene;
995         rp->engine = engine;
996         rp->sa = CTX_wm_area(C);
997         rp->ar = CTX_wm_region(C);
998         rp->v3d = rp->sa->spacedata.first;
999         rp->rv3d = CTX_wm_region_view3d(C);
1000         rp->bmain = CTX_data_main(C);
1001         rp->keep_data = keep_data;
1002         copy_m4_m4(rp->viewmat, rp->rv3d->viewmat);
1003         
1004         /* dont alloc in threads */
1005         if (engine->text == NULL)
1006                 engine->text = MEM_callocN(IMA_MAX_RENDER_TEXT, "rendertext");
1007         
1008         /* setup job */
1009         WM_jobs_customdata_set(wm_job, rp, render_view3d_free);
1010         WM_jobs_timer(wm_job, 0.1, NC_SPACE | ND_SPACE_VIEW3D, NC_SPACE | ND_SPACE_VIEW3D);
1011         WM_jobs_callbacks(wm_job, render_view3d_startjob, NULL, NULL, NULL);
1012         
1013         WM_jobs_start(CTX_wm_manager(C), wm_job);
1014         
1015         engine->flag &= ~RE_ENGINE_DO_UPDATE;
1016
1017 }
1018
1019 /* callback for render engine , on changes */
1020 void render_view3d(RenderEngine *engine, const bContext *C)
1021 {       
1022         render_view3d_do(engine, C, 0);
1023 }
1024
1025 static int render_view3d_changed(RenderEngine *engine, const bContext *C)
1026 {
1027         ARegion *ar = CTX_wm_region(C);
1028         Render *re;
1029         int update = 0;
1030         char name[32];
1031         
1032         sprintf(name, "View3dPreview %p", (void *)ar);
1033         re = RE_GetRender(name);
1034
1035         if (re) {
1036                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
1037                 View3D *v3d = CTX_wm_view3d(C);
1038                 Scene *scene = CTX_data_scene(C);
1039                 rctf viewplane, viewplane1;
1040                 rcti disprect, disprect1;
1041                 float mat[4][4];
1042                 float clipsta, clipend;
1043                 bool orth;
1044
1045                 if (engine->update_flag & RE_ENGINE_UPDATE_MA)
1046                         update |= PR_UPDATE_MATERIAL;
1047                 
1048                 if (engine->update_flag & RE_ENGINE_UPDATE_OTHER)
1049                         update |= PR_UPDATE_MATERIAL;
1050                 
1051                 engine->update_flag = 0;
1052                 
1053                 if (engine->resolution_x != ar->winx || engine->resolution_y != ar->winy)
1054                         update |= PR_UPDATE_RENDERSIZE;
1055
1056                 RE_GetView(re, mat);
1057                 if (compare_m4m4(mat, rv3d->viewmat, 0.00001f) == 0) {
1058                         update |= PR_UPDATE_VIEW;
1059                 }
1060                 
1061                 render_view3d_get_rects(ar, v3d, rv3d, &viewplane, engine, &clipsta, &clipend, NULL, &orth);
1062                 RE_GetViewPlane(re, &viewplane1, &disprect1);
1063                 
1064                 if (BLI_rctf_compare(&viewplane, &viewplane1, 0.00001f) == 0)
1065                         update |= PR_UPDATE_VIEW;
1066                 
1067                 render_view3d_disprect(scene, ar, v3d, rv3d, &disprect);
1068                 if (BLI_rcti_compare(&disprect, &disprect1) == 0)
1069                         update |= PR_UPDATE_RENDERSIZE;
1070                 
1071                 if (update)
1072                         engine->flag |= RE_ENGINE_DO_UPDATE;
1073                 //if (update)
1074                 //      printf("changed ma %d res %d view %d\n", update & PR_UPDATE_MATERIAL, update & PR_UPDATE_RENDERSIZE, update & PR_UPDATE_VIEW);
1075         }
1076         
1077         return update;
1078 }
1079
1080 void render_view3d_draw(RenderEngine *engine, const bContext *C)
1081 {
1082         Render *re = engine->re;
1083         RenderResult rres;
1084         int keep_data = render_view3d_changed(engine, C);
1085         
1086         if (engine->flag & RE_ENGINE_DO_UPDATE)
1087                 render_view3d_do(engine, C, keep_data);
1088
1089         if (re == NULL) return;
1090         
1091         RE_AcquireResultImage(re, &rres);
1092         
1093         if (rres.rectf) {
1094                 Scene *scene = CTX_data_scene(C);
1095                 bool force_fallback = false;
1096                 bool need_fallback = true;
1097                 float dither = scene->r.dither_intensity;
1098
1099                 /* Dithering is not supported on GLSL yet */
1100                 force_fallback |= dither != 0.0f;
1101
1102                 /* If user decided not to use GLSL, fallback to glaDrawPixelsAuto */
1103                 force_fallback |= (U.image_draw_method != IMAGE_DRAW_METHOD_GLSL);
1104
1105                 /* Try using GLSL display transform. */
1106                 if (force_fallback == false) {
1107                         if (IMB_colormanagement_setup_glsl_draw(NULL, &scene->display_settings, TRUE)) {
1108                                 glEnable(GL_BLEND);
1109                                 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1110                                 glaDrawPixelsTex(rres.xof, rres.yof, rres.rectx, rres.recty, GL_RGBA, GL_FLOAT,
1111                                                  GL_LINEAR, rres.rectf);
1112                                 glDisable(GL_BLEND);
1113
1114                                 IMB_colormanagement_finish_glsl_draw();
1115                                 need_fallback = false;
1116                         }
1117                 }
1118
1119                 /* If GLSL failed, use old-school CPU-based transform. */
1120                 if (need_fallback) {
1121                         unsigned char *display_buffer = MEM_mallocN(4 * rres.rectx * rres.recty * sizeof(char),
1122                                                                     "render_view3d_draw");
1123
1124                         IMB_colormanagement_buffer_make_display_space(rres.rectf, display_buffer, rres.rectx, rres.recty,
1125                                                                       4, dither, NULL, &scene->display_settings);
1126
1127                         glEnable(GL_BLEND);
1128                         glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1129                         glaDrawPixelsAuto(rres.xof, rres.yof, rres.rectx, rres.recty, GL_RGBA, GL_UNSIGNED_BYTE,
1130                                           GL_LINEAR, display_buffer);
1131                         glDisable(GL_BLEND);
1132
1133                         MEM_freeN(display_buffer);
1134                 }
1135         }
1136
1137         RE_ReleaseResultImage(re);
1138 }