Fix T38969: RenderResult in RenderPart can be NULL if multithreaded
[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_colortools.h"
53 #include "BKE_depsgraph.h"
54 #include "BKE_freestyle.h"
55 #include "BKE_global.h"
56 #include "BKE_image.h"
57 #include "BKE_library.h"
58 #include "BKE_main.h"
59 #include "BKE_node.h"
60 #include "BKE_multires.h"
61 #include "BKE_object.h"
62 #include "BKE_paint.h"
63 #include "BKE_report.h"
64 #include "BKE_sequencer.h"
65 #include "BKE_screen.h"
66 #include "BKE_scene.h"
67
68 #include "WM_api.h"
69 #include "WM_types.h"
70
71 #include "ED_object.h"
72 #include "ED_render.h"
73 #include "ED_screen.h"
74 #include "ED_util.h"
75 #include "ED_view3d.h"
76
77 #include "RE_pipeline.h"
78 #include "RE_engine.h"
79
80 #include "IMB_colormanagement.h"
81 #include "IMB_imbuf.h"
82 #include "IMB_imbuf_types.h"
83
84 #include "GPU_extensions.h"
85
86 #include "BIF_gl.h"
87 #include "BIF_glutil.h"
88
89 #include "RNA_access.h"
90 #include "RNA_define.h"
91
92 #include "wm_window.h"
93
94 #include "render_intern.h"
95
96 /* Render Callbacks */
97 static int render_break(void *rjv);
98
99 typedef struct RenderJob {
100         Main *main;
101         Scene *scene;
102         Render *re;
103         SceneRenderLayer *srl;
104         struct Object *camera_override;
105         int lay_override;
106         bool v3d_override;
107         short anim, write_still;
108         Image *image;
109         ImageUser iuser;
110         bool image_outdated;
111         short *stop;
112         short *do_update;
113         float *progress;
114         ReportList *reports;
115         int orig_layer;
116         int last_layer;
117         ScrArea *sa;
118         ColorManagedViewSettings view_settings;
119         ColorManagedDisplaySettings display_settings;
120         bool interface_locked;
121 } RenderJob;
122
123 /* called inside thread! */
124 static void image_buffer_rect_update(RenderJob *rj, RenderResult *rr, ImBuf *ibuf, ImageUser *iuser, volatile rcti *renrect)
125 {
126         Scene *scene = rj->scene;
127         float *rectf = NULL;
128         int ymin, ymax, xmin, xmax;
129         int rymin, rxmin;
130         int linear_stride, linear_offset_x, linear_offset_y;
131         ColorManagedViewSettings *view_settings;
132         ColorManagedDisplaySettings *display_settings;
133
134         if (ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) {
135                 /* The whole image buffer it so be color managed again anyway. */
136                 return;
137         }
138
139         /* if renrect argument, we only refresh scanlines */
140         if (renrect) {
141                 /* if (ymax == recty), rendering of layer is ready, we should not draw, other things happen... */
142                 if (rr->renlay == NULL || renrect->ymax >= rr->recty)
143                         return;
144
145                 /* xmin here is first subrect x coord, xmax defines subrect width */
146                 xmin = renrect->xmin + rr->crop;
147                 xmax = renrect->xmax - xmin + rr->crop;
148                 if (xmax < 2)
149                         return;
150
151                 ymin = renrect->ymin + rr->crop;
152                 ymax = renrect->ymax - ymin + rr->crop;
153                 if (ymax < 2)
154                         return;
155                 renrect->ymin = renrect->ymax;
156
157         }
158         else {
159                 xmin = ymin = rr->crop;
160                 xmax = rr->rectx - 2 * rr->crop;
161                 ymax = rr->recty - 2 * rr->crop;
162         }
163
164         /* xmin ymin is in tile coords. transform to ibuf */
165         rxmin = rr->tilerect.xmin + xmin;
166         if (rxmin >= ibuf->x) return;
167         rymin = rr->tilerect.ymin + ymin;
168         if (rymin >= ibuf->y) return;
169
170         if (rxmin + xmax > ibuf->x)
171                 xmax = ibuf->x - rxmin;
172         if (rymin + ymax > ibuf->y)
173                 ymax = ibuf->y - rymin;
174
175         if (xmax < 1 || ymax < 1) return;
176
177         /* The thing here is, the logic below (which was default behavior
178          * of how rectf is acquiring since forever) gives float buffer for
179          * composite output only. This buffer can not be used for other
180          * passes obviously.
181          *
182          * We might try finding corresponding for pass buffer in render result
183          * (which is actually missing when rendering with Cycles, who only
184          * writes all the passes when the tile is finished) or use float
185          * buffer from image buffer as reference, which is easier to use and
186          * contains all the data we need anyway.
187          *                                              - sergey -
188          */
189         /* TODO(sergey): Need to check has_combined here? */
190         if (iuser->pass == 0) {
191                 /* find current float rect for display, first case is after composite... still weak */
192                 if (rr->rectf)
193                         rectf = rr->rectf;
194                 else {
195                         if (rr->rect32) {
196                                 /* special case, currently only happens with sequencer rendering,
197                                  * which updates the whole frame, so we can only mark display buffer
198                                  * as invalid here (sergey)
199                                  */
200                                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
201                                 return;
202                         }
203                         else {
204                                 if (rr->renlay == NULL || rr->renlay->rectf == NULL) return;
205                                 rectf = rr->renlay->rectf;
206                         }
207                 }
208                 if (rectf == NULL) return;
209
210                 rectf += 4 * (rr->rectx * ymin + xmin);
211                 linear_stride = rr->rectx;
212                 linear_offset_x = rxmin;
213                 linear_offset_y = rymin;
214         }
215         else {
216                 rectf = ibuf->rect_float;
217                 linear_stride = ibuf->x;
218                 linear_offset_x = 0;
219                 linear_offset_y = 0;
220         }
221
222         if (rr->do_exr_tile) {
223                 /* We don't support changing color management settings during rendering
224                  * when using Save Buffers option.
225                  */
226                 view_settings = &rj->view_settings;
227                 display_settings = &rj->display_settings;
228         }
229         else {
230                 view_settings = &scene->view_settings;
231                 display_settings = &scene->display_settings;
232         }
233
234         IMB_partial_display_buffer_update(ibuf, rectf, NULL,
235                                           linear_stride, linear_offset_x, linear_offset_y,
236                                           view_settings, display_settings,
237                                           rxmin, rymin, rxmin + xmax, rymin + ymax,
238                                           rr->do_exr_tile);
239 }
240
241 /* ****************************** render invoking ***************** */
242
243 /* set callbacks, exported to sequence render too.
244  * Only call in foreground (UI) renders. */
245
246 static void screen_render_scene_layer_set(wmOperator *op, Main *mainp, Scene **scene, SceneRenderLayer **srl)
247 {
248         /* single layer re-render */
249         if (RNA_struct_property_is_set(op->ptr, "scene")) {
250                 Scene *scn;
251                 char scene_name[MAX_ID_NAME - 2];
252
253                 RNA_string_get(op->ptr, "scene", scene_name);
254                 scn = (Scene *)BLI_findstring(&mainp->scene, scene_name, offsetof(ID, name) + 2);
255                 
256                 if (scn) {
257                         /* camera switch wont have updated */
258                         scn->r.cfra = (*scene)->r.cfra;
259                         BKE_scene_camera_switch_update(scn);
260
261                         *scene = scn;
262                 }
263         }
264
265         if (RNA_struct_property_is_set(op->ptr, "layer")) {
266                 SceneRenderLayer *rl;
267                 char rl_name[RE_MAXNAME];
268
269                 RNA_string_get(op->ptr, "layer", rl_name);
270                 rl = (SceneRenderLayer *)BLI_findstring(&(*scene)->r.layers, rl_name, offsetof(SceneRenderLayer, name));
271                 
272                 if (rl)
273                         *srl = rl;
274         }
275 }
276
277 /* executes blocking render */
278 static int screen_render_exec(bContext *C, wmOperator *op)
279 {
280         Scene *scene = CTX_data_scene(C);
281         SceneRenderLayer *srl = NULL;
282         Render *re;
283         Image *ima;
284         View3D *v3d = CTX_wm_view3d(C);
285         Main *mainp = CTX_data_main(C);
286         unsigned int lay_override;
287         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
288         const bool is_write_still = RNA_boolean_get(op->ptr, "write_still");
289         struct Object *camera_override = v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
290
291         /* custom scene and single layer re-render */
292         screen_render_scene_layer_set(op, mainp, &scene, &srl);
293
294         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
295                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
296                 return OPERATOR_CANCELLED;
297         }
298
299         re = RE_NewRender(scene->id.name);
300         lay_override = (v3d && v3d->lay != scene->lay) ? v3d->lay : 0;
301
302         G.is_break = FALSE;
303         RE_test_break_cb(re, NULL, render_break);
304
305         ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
306         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
307         BKE_image_backup_render(scene, ima);
308
309         /* cleanup sequencer caches before starting user triggered render.
310          * otherwise, invalidated cache entries can make their way into
311          * the output rendering. We can't put that into RE_BlenderFrame,
312          * since sequence rendering can call that recursively... (peter) */
313         BKE_sequencer_cache_cleanup();
314
315         RE_SetReports(re, op->reports);
316
317         if (is_animation)
318                 RE_BlenderAnim(re, mainp, scene, camera_override, lay_override, scene->r.sfra, scene->r.efra, scene->r.frame_step);
319         else
320                 RE_BlenderFrame(re, mainp, scene, srl, camera_override, lay_override, scene->r.cfra, is_write_still);
321
322         RE_SetReports(re, NULL);
323
324         // no redraw needed, we leave state as we entered it
325         ED_update_for_newframe(mainp, scene, 1);
326
327         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, scene);
328
329         return OPERATOR_FINISHED;
330 }
331
332 static void render_freejob(void *rjv)
333 {
334         RenderJob *rj = rjv;
335
336         BKE_color_managed_view_settings_free(&rj->view_settings);
337         MEM_freeN(rj);
338 }
339
340 /* str is IMA_MAX_RENDER_TEXT in size */
341 static void make_renderinfo_string(RenderStats *rs, Scene *scene, bool v3d_override, char *str)
342 {
343         char info_time_str[32]; // used to be extern to header_info.c
344         uintptr_t mem_in_use, mmap_in_use, peak_memory;
345         float megs_used_memory, mmap_used_memory, megs_peak_memory;
346         char *spos = str;
347
348         mem_in_use = MEM_get_memory_in_use();
349         mmap_in_use = MEM_get_mapped_memory_in_use();
350         peak_memory = MEM_get_peak_memory();
351
352         megs_used_memory = (mem_in_use - mmap_in_use) / (1024.0 * 1024.0);
353         mmap_used_memory = (mmap_in_use) / (1024.0 * 1024.0);
354         megs_peak_memory = (peak_memory) / (1024.0 * 1024.0);
355
356         /* local view */
357         if (rs->localview)
358                 spos += sprintf(spos, "%s | ", IFACE_("3D Local View"));
359         else if (v3d_override)
360                 spos += sprintf(spos, "%s | ", IFACE_("3D View"));
361
362         /* frame number */
363         spos += sprintf(spos, IFACE_("Frame:%d "), (scene->r.cfra));
364
365         /* previous and elapsed time */
366         BLI_timestr(rs->lastframetime, info_time_str, sizeof(info_time_str));
367
368         if (rs->infostr && rs->infostr[0]) {
369                 if (rs->lastframetime != 0.0)
370                         spos += sprintf(spos, IFACE_("| Last:%s "), info_time_str);
371                 else
372                         spos += sprintf(spos, "| ");
373
374                 BLI_timestr(PIL_check_seconds_timer() - rs->starttime, info_time_str, sizeof(info_time_str));
375         }
376         else
377                 spos += sprintf(spos, "| ");
378
379         spos += sprintf(spos, IFACE_("Time:%s "), info_time_str);
380
381         /* statistics */
382         if (rs->statstr) {
383                 if (rs->statstr[0]) {
384                         spos += sprintf(spos, "| %s ", rs->statstr);
385                 }
386         }
387         else {
388                 if (rs->totvert || rs->totface || rs->tothalo || rs->totstrand || rs->totlamp)
389                         spos += sprintf(spos, "| ");
390
391                 if (rs->totvert) spos += sprintf(spos, IFACE_("Ve:%d "), rs->totvert);
392                 if (rs->totface) spos += sprintf(spos, IFACE_("Fa:%d "), rs->totface);
393                 if (rs->tothalo) spos += sprintf(spos, IFACE_("Ha:%d "), rs->tothalo);
394                 if (rs->totstrand) spos += sprintf(spos, IFACE_("St:%d "), rs->totstrand);
395                 if (rs->totlamp) spos += sprintf(spos, IFACE_("La:%d "), rs->totlamp);
396
397                 if (rs->mem_peak == 0.0f)
398                         spos += sprintf(spos, IFACE_("| Mem:%.2fM (%.2fM, Peak %.2fM) "),
399                                         megs_used_memory, mmap_used_memory, megs_peak_memory);
400                 else
401                         spos += sprintf(spos, IFACE_("| Mem:%.2fM, Peak: %.2fM "), rs->mem_used, rs->mem_peak);
402
403                 if (rs->curfield)
404                         spos += sprintf(spos, IFACE_("Field %d "), rs->curfield);
405                 if (rs->curblur)
406                         spos += sprintf(spos, IFACE_("Blur %d "), rs->curblur);
407         }
408
409         /* full sample */
410         if (rs->curfsa)
411                 spos += sprintf(spos, IFACE_("| Full Sample %d "), rs->curfsa);
412         
413         /* extra info */
414         if (rs->infostr && rs->infostr[0])
415                 spos += sprintf(spos, "| %s ", rs->infostr);
416
417         /* very weak... but 512 characters is quite safe */
418         if (spos >= str + IMA_MAX_RENDER_TEXT)
419                 if (G.debug & G_DEBUG)
420                         printf("WARNING! renderwin text beyond limit\n");
421
422 }
423
424 static void image_renderinfo_cb(void *rjv, RenderStats *rs)
425 {
426         RenderJob *rj = rjv;
427         RenderResult *rr;
428
429         rr = RE_AcquireResultRead(rj->re);
430
431         if (rr) {
432                 /* malloc OK here, stats_draw is not in tile threads */
433                 if (rr->text == NULL)
434                         rr->text = MEM_callocN(IMA_MAX_RENDER_TEXT, "rendertext");
435
436                 make_renderinfo_string(rs, rj->scene, rj->v3d_override, rr->text);
437         }
438
439         RE_ReleaseResult(rj->re);
440
441         /* make jobs timer to send notifier */
442         *(rj->do_update) = TRUE;
443
444 }
445
446 static void render_progress_update(void *rjv, float progress)
447 {
448         RenderJob *rj = rjv;
449         
450         if (rj->progress && *rj->progress != progress) {
451                 *rj->progress = progress;
452
453                 /* make jobs timer to send notifier */
454                 *(rj->do_update) = TRUE;
455         }
456 }
457
458 /* Not totally reliable, but works fine in most of cases and
459  * in worst case would just make it so extra color management
460  * for the whole render result is applied (which was already
461  * happening already).
462  */
463 static void render_image_update_pass_and_layer(RenderJob *rj, RenderResult *rr, ImageUser *iuser)
464 {
465         wmWindowManager *wm;
466         ScrArea *first_sa = NULL, *matched_sa = NULL;
467
468         /* image window, compo node users */
469         for (wm = rj->main->wm.first; wm && matched_sa == NULL; wm = wm->id.next) { /* only 1 wm */
470                 wmWindow *win;
471                 for (win = wm->windows.first; win && matched_sa == NULL; win = win->next) {
472                         ScrArea *sa;
473                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
474                                 if (sa->spacetype == SPACE_IMAGE) {
475                                         SpaceImage *sima = sa->spacedata.first;
476                                         if (sima->image == rj->image) {
477                                                 if (first_sa == NULL) {
478                                                         first_sa = sa;
479                                                 }
480                                                 if (sa == rj->sa) {
481                                                         matched_sa = sa;
482                                                         break;
483                                                 }
484                                         }
485                                 }
486                         }
487                 }
488         }
489
490         if (matched_sa == NULL) {
491                 matched_sa = first_sa;
492         }
493
494         if (matched_sa) {
495                 SpaceImage *sima = matched_sa->spacedata.first;
496                 RenderResult *main_rr = RE_AcquireResultRead(rj->re);
497
498                 /* TODO(sergey): is there faster way to get the layer index? */
499                 if (rr->renlay) {
500                         int layer = BLI_findstringindex(&main_rr->layers,
501                                                         (char *)rr->renlay->name,
502                                                         offsetof(RenderLayer, name));
503                         if (layer != rj->last_layer) {
504                                 sima->iuser.layer = layer;
505                                 rj->last_layer = layer;
506                         }
507                 }
508
509                 iuser->pass = sima->iuser.pass;
510                 iuser->layer = sima->iuser.layer;
511
512                 RE_ReleaseResult(rj->re);
513         }
514 }
515
516 static void image_rect_update(void *rjv, RenderResult *rr, volatile rcti *renrect)
517 {
518         RenderJob *rj = rjv;
519         Image *ima = rj->image;
520         ImBuf *ibuf;
521         void *lock;
522
523         /* only update if we are displaying the slot being rendered */
524         if (ima->render_slot != ima->last_render_slot) {
525                 rj->image_outdated = true;
526                 return;
527         }
528         else if (rj->image_outdated) {
529                 /* update entire render */
530                 rj->image_outdated = false;
531                 BKE_image_signal(ima, NULL, IMA_SIGNAL_COLORMANAGE);
532                 *(rj->do_update) = TRUE;
533                 return;
534         }
535         
536         if (rr == NULL)
537                 return;
538         
539         /* update part of render */
540         render_image_update_pass_and_layer(rj, rr, &rj->iuser);
541         ibuf = BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
542         if (ibuf) {
543                 /* Don't waste time on CPU side color management if
544                  * image will be displayed using GLSL.
545                  *
546                  * Need to update rect if Save Buffers enabled because in
547                  * this case GLSL doesn't have original float buffer to
548                  * operate with.
549                  */
550                 if (rr->do_exr_tile ||
551                     ibuf->channels == 1 ||
552                     U.image_draw_method != IMAGE_DRAW_METHOD_GLSL)
553                 {
554                         image_buffer_rect_update(rj, rr, ibuf, &rj->iuser, renrect);
555                 }
556                 
557                 /* make jobs timer to send notifier */
558                 *(rj->do_update) = TRUE;
559         }
560         BKE_image_release_ibuf(ima, ibuf, lock);
561 }
562
563 static void render_startjob(void *rjv, short *stop, short *do_update, float *progress)
564 {
565         RenderJob *rj = rjv;
566
567         rj->stop = stop;
568         rj->do_update = do_update;
569         rj->progress = progress;
570
571         RE_SetReports(rj->re, rj->reports);
572
573         if (rj->anim)
574                 RE_BlenderAnim(rj->re, rj->main, rj->scene, rj->camera_override, rj->lay_override, rj->scene->r.sfra, rj->scene->r.efra, rj->scene->r.frame_step);
575         else
576                 RE_BlenderFrame(rj->re, rj->main, rj->scene, rj->srl, rj->camera_override, rj->lay_override, rj->scene->r.cfra, rj->write_still);
577
578         RE_SetReports(rj->re, NULL);
579 }
580
581 static void render_image_restore_layer(RenderJob *rj)
582 {
583         wmWindowManager *wm;
584
585         /* image window, compo node users */
586         for (wm = rj->main->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
587                 wmWindow *win;
588                 for (win = wm->windows.first; win; win = win->next) {
589                         ScrArea *sa;
590                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
591                                 if (sa == rj->sa) {
592                                         if (sa->spacetype == SPACE_IMAGE) {
593                                                 SpaceImage *sima = sa->spacedata.first;
594                                                 sima->iuser.layer = rj->orig_layer;
595                                         }
596                                         return;
597                                 }
598                         }
599                 }
600         }
601 }
602
603 static void render_endjob(void *rjv)
604 {
605         RenderJob *rj = rjv;
606
607         /* this render may be used again by the sequencer without the active 'Render' where the callbacks
608          * would be re-assigned. assign dummy callbacks to avoid referencing freed renderjobs bug [#24508] */
609         RE_InitRenderCB(rj->re);
610
611         if (rj->main != G.main)
612                 BKE_main_free(rj->main);
613
614         /* else the frame will not update for the original value */
615         if (rj->anim && !(rj->scene->r.scemode & R_NO_FRAME_UPDATE)) {
616                 /* possible this fails of loading new file while rendering */
617                 if (G.main->wm.first) {
618                         ED_update_for_newframe(G.main, rj->scene, 1);
619                 }
620         }
621         
622         /* XXX above function sets all tags in nodes */
623         ntreeCompositClearTags(rj->scene->nodetree);
624         
625         /* potentially set by caller */
626         rj->scene->r.scemode &= ~R_NO_FRAME_UPDATE;
627         
628         if (rj->srl) {
629                 nodeUpdateID(rj->scene->nodetree, &rj->scene->id);
630                 WM_main_add_notifier(NC_NODE | NA_EDITED, rj->scene);
631         }
632
633         if (rj->sa) {
634                 render_image_restore_layer(rj);
635         }
636
637         /* XXX render stability hack */
638         G.is_rendering = FALSE;
639         WM_main_add_notifier(NC_SCENE | ND_RENDER_RESULT, NULL);
640
641         /* Partial render result will always update display buffer
642          * for first render layer only. This is nice because you'll
643          * see render progress during rendering, but it ends up in
644          * wrong display buffer shown after rendering.
645          *
646          * The code below will mark display buffer as invalid after
647          * rendering in case multiple layers were rendered, which
648          * ensures display buffer matches render layer after
649          * rendering.
650          *
651          * Perhaps proper way would be to toggle active render
652          * layer in image editor and job, so we always display
653          * layer being currently rendered. But this is not so much
654          * trivial at this moment, especially because of external
655          * engine API, so lets use simple and robust way for now
656          *                                          - sergey -
657          */
658         if (rj->scene->r.layers.first != rj->scene->r.layers.last ||
659             rj->image_outdated)
660         {
661                 void *lock;
662                 Image *ima = rj->image;
663                 ImBuf *ibuf = BKE_image_acquire_ibuf(ima, &rj->iuser, &lock);
664
665                 if (ibuf)
666                         ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
667
668                 BKE_image_release_ibuf(ima, ibuf, lock);
669         }
670
671         /* Finally unlock the user interface (if it was locked). */
672         if (rj->interface_locked) {
673                 Scene *scene;
674
675                 /* Interface was locked, so window manager couldn't have been changed
676                  * and using one from Global will unlock exactly the same manager as
677                  * was locked before running the job.
678                  */
679                 WM_set_locked_interface(G.main->wm.first, false);
680
681                 /* We've freed all the derived caches before rendering, which is
682                  * effectively the same as if we re-loaded the file.
683                  *
684                  * So let's not try being smart here and just reset all updated
685                  * scene layers and use generic DAG_on_visible_update.
686                  */
687                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
688                         scene->lay_updated = 0;
689                 }
690
691                 DAG_on_visible_update(G.main, false);
692         }
693 }
694
695 /* called by render, check job 'stop' value or the global */
696 static int render_breakjob(void *rjv)
697 {
698         RenderJob *rj = rjv;
699
700         if (G.is_break)
701                 return 1;
702         if (rj->stop && *(rj->stop))
703                 return 1;
704         return 0;
705 }
706
707 /* for exec() when there is no render job
708  * note: this wont check for the escape key being pressed, but doing so isnt threadsafe */
709 static int render_break(void *UNUSED(rjv))
710 {
711         if (G.is_break)
712                 return 1;
713         return 0;
714 }
715
716 /* runs in thread, no cursor setting here works. careful with notifiers too (malloc conflicts) */
717 /* maybe need a way to get job send notifer? */
718 static void render_drawlock(void *rjv, int lock)
719 {
720         RenderJob *rj = rjv;
721
722         /* If interface is locked, renderer callback shall do nothing. */
723         if (!rj->interface_locked) {
724                 BKE_spacedata_draw_locks(lock);
725         }
726 }
727
728 /* catch esc */
729 static int screen_render_modal(bContext *C, wmOperator *op, const wmEvent *event)
730 {
731         Scene *scene = (Scene *) op->customdata;
732
733         /* no running blender, remove handler and pass through */
734         if (0 == WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_RENDER)) {
735                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
736         }
737
738         /* running render */
739         switch (event->type) {
740                 case ESCKEY:
741                         return OPERATOR_RUNNING_MODAL;
742                         break;
743         }
744         return OPERATOR_PASS_THROUGH;
745 }
746
747 static void screen_render_cancel(bContext *C, wmOperator *op)
748 {
749         wmWindowManager *wm = CTX_wm_manager(C);
750         Scene *scene = (Scene *) op->customdata;
751
752         /* kill on cancel, because job is using op->reports */
753         WM_jobs_kill_type(wm, scene, WM_JOB_TYPE_RENDER);
754 }
755
756 static void clean_viewport_memory(Main *bmain, Scene *scene, int renderlay)
757 {
758         Object *object;
759         Scene *sce_iter;
760         Base *base;
761
762         for (object = bmain->object.first; object; object = object->id.next) {
763                 object->id.flag |= LIB_DOIT;
764         }
765
766         for (SETLOOPER(scene, sce_iter, base)) {
767                 if ((base->lay & renderlay) == 0) {
768                         continue;
769                 }
770
771                 if (RE_allow_render_generic_object(base->object)) {
772                         base->object->id.flag &= ~LIB_DOIT;
773                 }
774         }
775
776         for (object = bmain->object.first; object; object = object->id.next) {
777                 if ((object->id.flag & LIB_DOIT) == 0) {
778                         continue;
779                 }
780                 object->id.flag &= ~LIB_DOIT;
781
782                 BKE_object_free_derived_caches(object);
783         }
784 }
785
786 /* using context, starts job */
787 static int screen_render_invoke(bContext *C, wmOperator *op, const wmEvent *event)
788 {
789         /* new render clears all callbacks */
790         Main *mainp;
791         Scene *scene = CTX_data_scene(C);
792         SceneRenderLayer *srl = NULL;
793         Render *re;
794         wmJob *wm_job;
795         RenderJob *rj;
796         Image *ima;
797         int jobflag;
798         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
799         const bool is_write_still = RNA_boolean_get(op->ptr, "write_still");
800         const bool use_viewport = RNA_boolean_get(op->ptr, "use_viewport");
801         View3D *v3d = use_viewport ? CTX_wm_view3d(C) : NULL;
802         struct Object *camera_override = v3d ? V3D_CAMERA_LOCAL(v3d) : NULL;
803         const char *name;
804         ScrArea *sa;
805         
806         /* only one render job at a time */
807         if (WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_RENDER))
808                 return OPERATOR_CANCELLED;
809
810         if (RE_force_single_renderlayer(scene))
811                 WM_event_add_notifier(C, NC_SCENE | ND_RENDER_OPTIONS, NULL);
812
813         if (!RE_is_rendering_allowed(scene, camera_override, op->reports)) {
814                 return OPERATOR_CANCELLED;
815         }
816
817         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
818                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
819                 return OPERATOR_CANCELLED;
820         }
821         
822         /* stop all running jobs, except screen one. currently previews frustrate Render */
823         WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C));
824
825         /* get main */
826         if (G.debug_value == 101) {
827                 /* thread-safety experiment, copy main from the undo buffer */
828                 mainp = BKE_undo_get_main(&scene);
829         }
830         else
831                 mainp = CTX_data_main(C);
832
833         /* cancel animation playback */
834         if (ED_screen_animation_playing(CTX_wm_manager(C)))
835                 ED_screen_animation_play(C, 0, 0);
836         
837         /* handle UI stuff */
838         WM_cursor_wait(1);
839
840         /* flush sculpt and editmode changes */
841         ED_editors_flush_edits(C, true);
842
843         /* cleanup sequencer caches before starting user triggered render.
844          * otherwise, invalidated cache entries can make their way into
845          * the output rendering. We can't put that into RE_BlenderFrame,
846          * since sequence rendering can call that recursively... (peter) */
847         BKE_sequencer_cache_cleanup();
848
849         // store spare
850         // get view3d layer, local layer, make this nice api call to render
851         // store spare
852
853         /* ensure at least 1 area shows result */
854         sa = render_view_open(C, event->x, event->y);
855
856         jobflag = WM_JOB_EXCL_RENDER | WM_JOB_PRIORITY | WM_JOB_PROGRESS;
857         
858         /* custom scene and single layer re-render */
859         screen_render_scene_layer_set(op, mainp, &scene, &srl);
860
861         if (RNA_struct_property_is_set(op->ptr, "layer"))
862                 jobflag |= WM_JOB_SUSPEND;
863
864         /* job custom data */
865         rj = MEM_callocN(sizeof(RenderJob), "render job");
866         rj->main = mainp;
867         rj->scene = scene;
868         rj->srl = srl;
869         rj->camera_override = camera_override;
870         rj->lay_override = 0;
871         rj->anim = is_animation;
872         rj->write_still = is_write_still && !is_animation;
873         rj->iuser.scene = scene;
874         rj->iuser.ok = 1;
875         rj->reports = op->reports;
876         rj->orig_layer = 0;
877         rj->last_layer = 0;
878         rj->sa = sa;
879
880         BKE_color_managed_display_settings_copy(&rj->display_settings, &scene->display_settings);
881         BKE_color_managed_view_settings_copy(&rj->view_settings, &scene->view_settings);
882
883         if (sa) {
884                 SpaceImage *sima = sa->spacedata.first;
885                 rj->orig_layer = sima->iuser.layer;
886         }
887
888         if (v3d) {
889                 if (scene->lay != v3d->lay) {
890                         rj->lay_override = v3d->lay;
891                         rj->v3d_override = true;
892                 }
893                 else if (camera_override && camera_override != scene->camera)
894                         rj->v3d_override = true;
895
896                 if (v3d->localvd)
897                         rj->lay_override |= v3d->localvd->lay;
898         }
899
900         /* Lock the user interface depending on render settings. */
901         if (scene->r.use_lock_interface) {
902                 int renderlay = rj->lay_override ? rj->lay_override : scene->lay;
903
904                 WM_set_locked_interface(CTX_wm_manager(C), true);
905
906                 /* Set flag interface need to be unlocked.
907                  *
908                  * This is so because we don't have copy of render settings
909                  * accessible from render job and copy is needed in case
910                  * of non-locked rendering, so we wouldn't try to unlock
911                  * anything if option was initially unset but then was
912                  * enabled during rendering.
913                  */
914                 rj->interface_locked = true;
915
916                 /* Clean memory used by viewport? */
917                 clean_viewport_memory(rj->main, scene, renderlay);
918         }
919
920         /* setup job */
921         if (RE_seq_render_active(scene, &scene->r)) name = "Sequence Render";
922         else name = "Render";
923
924         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, name, jobflag, WM_JOB_TYPE_RENDER);
925         WM_jobs_customdata_set(wm_job, rj, render_freejob);
926         WM_jobs_timer(wm_job, 0.2, NC_SCENE | ND_RENDER_RESULT, 0);
927         WM_jobs_callbacks(wm_job, render_startjob, NULL, NULL, render_endjob);
928
929         /* get a render result image, and make sure it is empty */
930         ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
931         BKE_image_signal(ima, NULL, IMA_SIGNAL_FREE);
932         BKE_image_backup_render(rj->scene, ima);
933         rj->image = ima;
934
935         /* setup new render */
936         re = RE_NewRender(scene->id.name);
937         RE_test_break_cb(re, rj, render_breakjob);
938         RE_draw_lock_cb(re, rj, render_drawlock);
939         RE_display_update_cb(re, rj, image_rect_update);
940         RE_stats_draw_cb(re, rj, image_renderinfo_cb);
941         RE_progress_cb(re, rj, render_progress_update);
942
943         rj->re = re;
944         G.is_break = FALSE;
945
946         /* store actual owner of job, so modal operator could check for it,
947          * the reason of this is that active scene could change when rendering
948          * several layers from compositor [#31800]
949          */
950         op->customdata = scene;
951
952         WM_jobs_start(CTX_wm_manager(C), wm_job);
953
954         WM_cursor_wait(0);
955         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, scene);
956
957         /* we set G.is_rendering here already instead of only in the job, this ensure
958          * main loop or other scene updates are disabled in time, since they may
959          * have started before the job thread */
960         G.is_rendering = TRUE;
961
962         /* add modal handler for ESC */
963         WM_event_add_modal_handler(C, op);
964
965         return OPERATOR_RUNNING_MODAL;
966 }
967
968 /* contextual render, using current scene, view3d? */
969 void RENDER_OT_render(wmOperatorType *ot)
970 {
971         PropertyRNA *prop;
972
973         /* identifiers */
974         ot->name = "Render";
975         ot->description = "Render active scene";
976         ot->idname = "RENDER_OT_render";
977
978         /* api callbacks */
979         ot->invoke = screen_render_invoke;
980         ot->modal = screen_render_modal;
981         ot->cancel = screen_render_cancel;
982         ot->exec = screen_render_exec;
983
984         /*ot->poll = ED_operator_screenactive;*/ /* this isn't needed, causes failer in background mode */
985
986         RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
987         RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
988         RNA_def_boolean(ot->srna, "use_viewport", 0, "Use 3D Viewport", "When inside a 3D viewport, use layers and camera of the viewport");
989         prop = RNA_def_string(ot->srna, "layer", NULL, RE_MAXNAME, "Render Layer", "Single render layer to re-render (used only when animation is disabled)");
990         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
991         prop = RNA_def_string(ot->srna, "scene", NULL, MAX_ID_NAME - 2, "Scene", "Scene to render, current scene if not specified");
992         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
993 }
994
995
996 /* ************** preview for 3d viewport ***************** */
997
998 #define PR_UPDATE_VIEW                          1
999 #define PR_UPDATE_RENDERSIZE            2
1000 #define PR_UPDATE_MATERIAL                      4
1001 #define PR_UPDATE_DATABASE                      8
1002
1003 typedef struct RenderPreview {
1004         /* from wmJob */
1005         void *owner;
1006         short *stop, *do_update;
1007         wmJob *job;
1008         
1009         Scene *scene;
1010         ScrArea *sa;
1011         ARegion *ar;
1012         View3D *v3d;
1013         RegionView3D *rv3d;
1014         Main *bmain;
1015         RenderEngine *engine;
1016         
1017         float viewmat[4][4];
1018 } RenderPreview;
1019
1020 static int render_view3d_disprect(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D *rv3d, rcti *disprect)
1021 {
1022         /* copied code from view3d_draw.c */
1023         rctf viewborder;
1024         int draw_border;
1025         
1026         if (rv3d->persp == RV3D_CAMOB)
1027                 draw_border = (scene->r.mode & R_BORDER) != 0;
1028         else
1029                 draw_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
1030
1031         if (draw_border) {
1032                 if (rv3d->persp == RV3D_CAMOB) {
1033                         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
1034                         
1035                         disprect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
1036                         disprect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
1037                         disprect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
1038                         disprect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
1039                 }
1040                 else {
1041                         disprect->xmin = v3d->render_border.xmin * ar->winx;
1042                         disprect->xmax = v3d->render_border.xmax * ar->winx;
1043                         disprect->ymin = v3d->render_border.ymin * ar->winy;
1044                         disprect->ymax = v3d->render_border.ymax * ar->winy;
1045                 }
1046                 
1047                 return 1;
1048         }
1049         
1050         BLI_rcti_init(disprect, 0, 0, 0, 0);
1051         return 0;
1052 }
1053
1054 /* returns true if OK  */
1055 static bool render_view3d_get_rects(ARegion *ar, View3D *v3d, RegionView3D *rv3d, rctf *viewplane, RenderEngine *engine,
1056                                     float *r_clipsta, float *r_clipend, float *r_pixsize, bool *r_ortho)
1057 {
1058         
1059         if (ar->winx < 4 || ar->winy < 4) return false;
1060         
1061         *r_ortho = ED_view3d_viewplane_get(v3d, rv3d, ar->winx, ar->winy, viewplane, r_clipsta, r_clipend, r_pixsize);
1062         
1063         engine->resolution_x = ar->winx;
1064         engine->resolution_y = ar->winy;
1065
1066         return true;
1067 }
1068
1069 static bool render_view3d_is_valid(RenderPreview *rp)
1070 {
1071         return (rp->rv3d->render_engine != NULL);
1072 }
1073
1074 /* called by renderer, checks job value */
1075 static int render_view3d_break(void *rpv)
1076 {
1077         RenderPreview *rp = rpv;
1078         
1079         if (G.is_break)
1080                 return 1;
1081         
1082         /* during render, rv3d->engine can get freed */
1083         if (render_view3d_is_valid(rp) == false) {
1084                 *rp->stop = 1;
1085         }
1086         
1087         return *(rp->stop);
1088 }
1089
1090 static void render_view3d_display_update(void *rpv, RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect))
1091 {
1092         RenderPreview *rp = rpv;
1093         
1094         *(rp->do_update) = TRUE;
1095 }
1096
1097 static void render_view3d_renderinfo_cb(void *rjp, RenderStats *rs)
1098 {
1099         RenderPreview *rp = rjp;
1100
1101         /* during render, rv3d->engine can get freed */
1102         if (rp->rv3d->render_engine == NULL) {
1103                 *rp->stop = 1;
1104         }
1105         else {
1106                 make_renderinfo_string(rs, rp->scene, false, rp->engine->text);
1107         
1108                 /* make jobs timer to send notifier */
1109                 *(rp->do_update) = TRUE;
1110         }
1111 }
1112
1113
1114 static void render_view3d_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
1115 {
1116         RenderPreview *rp = customdata;
1117         Render *re;
1118         RenderStats *rstats;
1119         RenderData rdata;
1120         rctf viewplane;
1121         rcti cliprct;
1122         float clipsta, clipend, pixsize;
1123         bool orth, restore = 0;
1124         char name[32];
1125         int update_flag;
1126
1127         update_flag = rp->engine->job_update_flag;
1128         rp->engine->job_update_flag = 0;
1129
1130         //printf("ma %d res %d view %d db %d\n", update_flag & PR_UPDATE_MATERIAL, update_flag & PR_UPDATE_RENDERSIZE, update_flag & PR_UPDATE_VIEW, update_flag & PR_UPDATE_DATABASE);
1131
1132         G.is_break = FALSE;
1133         
1134         if (false == render_view3d_get_rects(rp->ar, rp->v3d, rp->rv3d, &viewplane, rp->engine, &clipsta, &clipend, &pixsize, &orth))
1135                 return;
1136         
1137         rp->stop = stop;
1138         rp->do_update = do_update;
1139
1140         // printf("Enter previewrender\n");
1141         
1142         /* ok, are we rendering all over? */
1143         sprintf(name, "View3dPreview %p", (void *)rp->ar);
1144         re = rp->engine->re = RE_GetRender(name);
1145         
1146         /* set this always, rp is different for each job */
1147         RE_test_break_cb(re, rp, render_view3d_break);
1148         RE_display_update_cb(re, rp, render_view3d_display_update);
1149         RE_stats_draw_cb(re, rp, render_view3d_renderinfo_cb);
1150         
1151         rstats = RE_GetStats(re);
1152
1153         if ((update_flag & (PR_UPDATE_RENDERSIZE | PR_UPDATE_DATABASE)) || rstats->convertdone == 0) {
1154                 /* no osa, blur, seq, layers, etc for preview render */
1155                 rdata = rp->scene->r;
1156                 rdata.mode &= ~(R_OSA | R_MBLUR | R_BORDER | R_PANORAMA);
1157                 rdata.scemode &= ~(R_DOSEQ | R_DOCOMP | R_FREE_IMAGE);
1158                 rdata.scemode |= R_VIEWPORT_PREVIEW;
1159                 
1160                 /* we do use layers, but only active */
1161                 rdata.scemode |= R_SINGLE_LAYER;
1162
1163                 /* initalize always */
1164                 if (render_view3d_disprect(rp->scene, rp->ar, rp->v3d, rp->rv3d, &cliprct)) {
1165                         rdata.mode |= R_BORDER;
1166                         RE_InitState(re, NULL, &rdata, NULL, rp->ar->winx, rp->ar->winy, &cliprct);
1167                 }
1168                 else
1169                         RE_InitState(re, NULL, &rdata, NULL, rp->ar->winx, rp->ar->winy, NULL);
1170         }
1171
1172         if (orth)
1173                 RE_SetOrtho(re, &viewplane, clipsta, clipend);
1174         else
1175                 RE_SetWindow(re, &viewplane, clipsta, clipend);
1176
1177         RE_SetPixelSize(re, pixsize);
1178         
1179         if ((update_flag & PR_UPDATE_DATABASE) || rstats->convertdone == 0) {
1180                 unsigned int lay = rp->scene->lay;
1181
1182                 /* allow localview render for objects with lights in normal layers */
1183                 if (rp->v3d->lay & 0xFF000000)
1184                         lay |= rp->v3d->lay;
1185                 else lay = rp->v3d->lay;
1186                 
1187                 RE_SetView(re, rp->viewmat);
1188
1189                 /* copying blender data while main thread is locked, to avoid crashes */
1190                 WM_job_main_thread_lock_acquire(rp->job);
1191                 RE_Database_Free(re);
1192                 RE_Database_FromScene(re, rp->bmain, rp->scene, lay, 0);                // 0= dont use camera view
1193                 WM_job_main_thread_lock_release(rp->job);
1194
1195                 /* do preprocessing like building raytree, shadows, volumes, SSS */
1196                 RE_Database_Preprocess(re);
1197
1198                 /* conversion not completed, need to do it again */
1199                 if (!rstats->convertdone) {
1200                         if (render_view3d_is_valid(rp)) {
1201                                 rp->engine->job_update_flag |= PR_UPDATE_DATABASE;
1202                         }
1203                 }
1204
1205                 // printf("dbase update\n");
1206         }
1207         else {
1208                 // printf("dbase rotate\n");
1209                 RE_DataBase_IncrementalView(re, rp->viewmat, 0);
1210                 restore = 1;
1211         }
1212
1213         RE_DataBase_ApplyWindow(re);
1214
1215         /* OK, can we enter render code? */
1216         if (rstats->convertdone) {
1217                 RE_TileProcessor(re);
1218                 
1219                 /* always rotate back */
1220                 if (restore)
1221                         RE_DataBase_IncrementalView(re, rp->viewmat, 1);
1222         }
1223 }
1224
1225 static void render_view3d_free(void *customdata)
1226 {
1227         RenderPreview *rp = customdata;
1228         
1229         MEM_freeN(rp);
1230 }
1231
1232 static bool render_view3d_flag_changed(RenderEngine *engine, const bContext *C)
1233 {
1234         RegionView3D *rv3d = CTX_wm_region_view3d(C);
1235         View3D *v3d = CTX_wm_view3d(C);
1236         ARegion *ar = CTX_wm_region(C);
1237         Scene *scene = CTX_data_scene(C);
1238         Render *re;
1239         rctf viewplane;
1240         rcti disprect;
1241         float clipsta, clipend;
1242         bool orth;
1243         int job_update_flag = 0;
1244         char name[32];
1245         
1246         /* ensure render engine exists */
1247         re = engine->re;
1248
1249         if (!re) {
1250                 sprintf(name, "View3dPreview %p", (void *)ar);
1251                 re = engine->re = RE_GetRender(name);
1252                 if (!re)
1253                         re = engine->re = RE_NewRender(name);
1254
1255                 engine->update_flag |= RE_ENGINE_UPDATE_DATABASE;
1256         }
1257
1258         /* check update_flag */
1259         if (engine->update_flag & RE_ENGINE_UPDATE_MA)
1260                 job_update_flag |= PR_UPDATE_MATERIAL;
1261         
1262         if (engine->update_flag & RE_ENGINE_UPDATE_OTHER)
1263                 job_update_flag |= PR_UPDATE_MATERIAL;
1264         
1265         if (engine->update_flag & RE_ENGINE_UPDATE_DATABASE) {
1266                 job_update_flag |= PR_UPDATE_DATABASE;
1267
1268                 /* load editmesh */
1269                 if (scene->obedit)
1270                         ED_object_editmode_load(scene->obedit);
1271         }
1272         
1273         engine->update_flag = 0;
1274         
1275         /* check if viewport changed */
1276         if (engine->last_winx != ar->winx || engine->last_winy != ar->winy) {
1277                 engine->last_winx = ar->winx;
1278                 engine->last_winy = ar->winy;
1279                 job_update_flag |= PR_UPDATE_RENDERSIZE;
1280         }
1281
1282         if (compare_m4m4(engine->last_viewmat, rv3d->viewmat, 0.00001f) == 0) {
1283                 copy_m4_m4(engine->last_viewmat, rv3d->viewmat);
1284                 job_update_flag |= PR_UPDATE_VIEW;
1285         }
1286         
1287         render_view3d_get_rects(ar, v3d, rv3d, &viewplane, engine, &clipsta, &clipend, NULL, &orth);
1288         
1289         if (BLI_rctf_compare(&viewplane, &engine->last_viewplane, 0.00001f) == 0) {
1290                 engine->last_viewplane = viewplane;
1291                 job_update_flag |= PR_UPDATE_VIEW;
1292         }
1293         
1294         render_view3d_disprect(scene, ar, v3d, rv3d, &disprect);
1295         if (BLI_rcti_compare(&disprect, &engine->last_disprect) == 0) {
1296                 engine->last_disprect = disprect;
1297                 job_update_flag |= PR_UPDATE_RENDERSIZE;
1298         }
1299
1300         /* any changes? go ahead and rerender */
1301         if (job_update_flag) {
1302                 engine->job_update_flag |= job_update_flag;
1303                 return true;
1304         }
1305
1306         return false;
1307 }
1308
1309 static void render_view3d_do(RenderEngine *engine, const bContext *C)
1310 {
1311         wmJob *wm_job;
1312         RenderPreview *rp;
1313         Scene *scene = CTX_data_scene(C);
1314         
1315         if (CTX_wm_window(C) == NULL)
1316                 return;
1317         if (!render_view3d_flag_changed(engine, C))
1318                 return;
1319
1320         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), CTX_wm_region(C), "Render Preview",
1321                              WM_JOB_EXCL_RENDER, WM_JOB_TYPE_RENDER_PREVIEW);
1322         rp = MEM_callocN(sizeof(RenderPreview), "render preview");
1323         rp->job = wm_job;
1324
1325         /* customdata for preview thread */
1326         rp->scene = scene;
1327         rp->engine = engine;
1328         rp->sa = CTX_wm_area(C);
1329         rp->ar = CTX_wm_region(C);
1330         rp->v3d = rp->sa->spacedata.first;
1331         rp->rv3d = CTX_wm_region_view3d(C);
1332         rp->bmain = CTX_data_main(C);
1333         copy_m4_m4(rp->viewmat, rp->rv3d->viewmat);
1334         
1335         /* clear info text */
1336         engine->text[0] = '\0';
1337         
1338         /* setup job */
1339         WM_jobs_customdata_set(wm_job, rp, render_view3d_free);
1340         WM_jobs_timer(wm_job, 0.1, NC_SPACE | ND_SPACE_VIEW3D, NC_SPACE | ND_SPACE_VIEW3D);
1341         WM_jobs_callbacks(wm_job, render_view3d_startjob, NULL, NULL, NULL);
1342         
1343         WM_jobs_start(CTX_wm_manager(C), wm_job);
1344         
1345         engine->flag &= ~RE_ENGINE_DO_UPDATE;
1346 }
1347
1348 /* callback for render engine , on changes */
1349 void render_view3d_update(RenderEngine *engine, const bContext *C)
1350 {       
1351         /* this shouldn't be needed and causes too many database rebuilds, but we
1352          * aren't actually tracking updates for all relevent datablocks so this is
1353          * a catch-all for updates */
1354         engine->update_flag |= RE_ENGINE_UPDATE_DATABASE;
1355
1356         render_view3d_do(engine, C);
1357 }
1358
1359 void render_view3d_draw(RenderEngine *engine, const bContext *C)
1360 {
1361         Render *re = engine->re;
1362         RenderResult rres;
1363         char name[32];
1364         
1365         render_view3d_do(engine, C);
1366         
1367         if (re == NULL) {
1368                 sprintf(name, "View3dPreview %p", (void *)CTX_wm_region(C));
1369                 re = RE_GetRender(name);
1370         
1371                 if (re == NULL) return;
1372         }
1373         
1374         RE_AcquireResultImage(re, &rres);
1375         
1376         if (rres.rectf) {
1377                 Scene *scene = CTX_data_scene(C);
1378                 bool force_fallback = false;
1379                 bool need_fallback = true;
1380                 float dither = scene->r.dither_intensity;
1381
1382                 /* Dithering is not supported on GLSL yet */
1383                 force_fallback |= dither != 0.0f;
1384
1385                 /* If user decided not to use GLSL, fallback to glaDrawPixelsAuto */
1386                 force_fallback |= (U.image_draw_method != IMAGE_DRAW_METHOD_GLSL);
1387
1388                 /* Try using GLSL display transform. */
1389                 if (force_fallback == false) {
1390                         if (IMB_colormanagement_setup_glsl_draw(&scene->view_settings, &scene->display_settings, 0.0f, true)) {
1391                                 glEnable(GL_BLEND);
1392                                 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1393                                 glaDrawPixelsTex(rres.xof, rres.yof, rres.rectx, rres.recty, GL_RGBA, GL_FLOAT,
1394                                                  GL_NEAREST, rres.rectf);
1395                                 glDisable(GL_BLEND);
1396
1397                                 IMB_colormanagement_finish_glsl_draw();
1398                                 need_fallback = false;
1399                         }
1400                 }
1401
1402                 /* If GLSL failed, use old-school CPU-based transform. */
1403                 if (need_fallback) {
1404                         unsigned char *display_buffer = MEM_mallocN(4 * rres.rectx * rres.recty * sizeof(char),
1405                                                                     "render_view3d_draw");
1406
1407                         IMB_colormanagement_buffer_make_display_space(rres.rectf, display_buffer, rres.rectx, rres.recty,
1408                                                                       4, dither, &scene->view_settings, &scene->display_settings);
1409
1410                         glEnable(GL_BLEND);
1411                         glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1412                         glaDrawPixelsAuto(rres.xof, rres.yof, rres.rectx, rres.recty, GL_RGBA, GL_UNSIGNED_BYTE,
1413                                           GL_NEAREST, display_buffer);
1414                         glDisable(GL_BLEND);
1415
1416                         MEM_freeN(display_buffer);
1417                 }
1418         }
1419
1420         RE_ReleaseResultImage(re);
1421 }
1422
1423 void ED_viewport_render_kill_jobs(const bContext *C, bool free_database)
1424 {
1425         wmWindowManager *wm = CTX_wm_manager(C);
1426         Main *bmain = CTX_data_main(C);
1427         bScreen *sc;
1428         ScrArea *sa;
1429         ARegion *ar;
1430
1431         if (!wm)
1432                 return;
1433
1434         /* kill all actively running jobs */
1435         WM_jobs_kill(wm, NULL, render_view3d_startjob);
1436
1437         /* loop over 3D view render engines */
1438         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
1439                 for (sa = sc->areabase.first; sa; sa = sa->next) {
1440                         if (sa->spacetype != SPACE_VIEW3D)
1441                                 continue;
1442                         
1443                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1444                                 RegionView3D *rv3d;
1445                                 
1446                                 if (ar->regiontype != RGN_TYPE_WINDOW)
1447                                         continue;
1448                                 
1449                                 rv3d = ar->regiondata;
1450
1451                                 if (rv3d->render_engine) {
1452                                         /* free render database now before we change data, because
1453                                          * RE_Database_Free will also loop over blender data */
1454                                         if (free_database) {
1455                                                 char name[32];
1456                                                 Render *re;
1457
1458                                                 sprintf(name, "View3dPreview %p", (void *)ar);
1459                                                 re = RE_GetRender(name);
1460
1461                                                 if (re)
1462                                                         RE_Database_Free(re);
1463
1464                                                 /* tag render engine to update entire database */
1465                                                 rv3d->render_engine->update_flag |= RE_ENGINE_UPDATE_DATABASE;
1466                                         }
1467                                         else {
1468                                                 /* quick shader update */
1469                                                 rv3d->render_engine->update_flag |= RE_ENGINE_UPDATE_MA;
1470                                         }
1471                                 }
1472                         }
1473                 }
1474         }
1475 }
1476
1477 Scene *ED_render_job_get_scene(const bContext *C)
1478 {
1479         wmWindowManager *wm = CTX_wm_manager(C);
1480         RenderJob *rj = (RenderJob *)WM_jobs_customdata_from_type(wm, WM_JOB_TYPE_RENDER);
1481         
1482         if (rj)
1483                 return rj->scene;
1484         
1485         return NULL;
1486 }