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