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