03742b489a1ff81d24e99b15bdc62acce83ea44d
[blender.git] / source / blender / editors / render / render_preview.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) Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/render/render_preview.c
29  *  \ingroup edrend
30  */
31
32
33 /* global includes */
34
35 #include <stdlib.h>
36 #include <math.h>
37 #include <string.h>
38
39 #ifndef WIN32
40 #include <unistd.h>
41 #else
42 #include <io.h>
43 #endif   
44 #include "MEM_guardedalloc.h"
45
46 #include "BLI_math.h"
47 #include "BLI_blenlib.h"
48 #include "BLI_utildefines.h"
49
50 #include "BLO_readfile.h"
51
52 #include "DNA_world_types.h"
53 #include "DNA_camera_types.h"
54 #include "DNA_material_types.h"
55 #include "DNA_node_types.h"
56 #include "DNA_object_types.h"
57 #include "DNA_lamp_types.h"
58 #include "DNA_space_types.h"
59 #include "DNA_scene_types.h"
60 #include "DNA_brush_types.h"
61 #include "DNA_screen_types.h"
62
63 #include "BKE_appdir.h"
64 #include "BKE_brush.h"
65 #include "BKE_context.h"
66 #include "BKE_colortools.h"
67 #include "BKE_global.h"
68 #include "BKE_idprop.h"
69 #include "BKE_image.h"
70 #include "BKE_icons.h"
71 #include "BKE_lamp.h"
72 #include "BKE_layer.h"
73 #include "BKE_library.h"
74 #include "BKE_library_remap.h"
75 #include "BKE_main.h"
76 #include "BKE_material.h"
77 #include "BKE_node.h"
78 #include "BKE_scene.h"
79 #include "BKE_texture.h"
80 #include "BKE_world.h"
81
82 #include "DEG_depsgraph.h"
83 #include "DEG_depsgraph_build.h"
84
85 #include "IMB_imbuf.h"
86 #include "IMB_imbuf_types.h"
87 #include "IMB_thumbs.h"
88
89 #include "BIF_gl.h"
90 #include "BIF_glutil.h"
91
92 #include "GPU_shader.h"
93
94 #include "RE_pipeline.h"
95 #include "RE_engine.h"
96
97 #include "WM_api.h"
98 #include "WM_types.h"
99
100 #include "ED_datafiles.h"
101 #include "ED_render.h"
102 #include "ED_screen.h"
103
104 #ifndef NDEBUG
105 /* Used for database init assert(). */
106 #  include "BLI_threads.h"
107 #endif
108
109 ImBuf *get_brush_icon(Brush *brush)
110 {
111         static const int flags = IB_rect | IB_multilayer | IB_metadata;
112
113         char path[FILE_MAX];
114         const char *folder;
115
116         if (!(brush->icon_imbuf)) {
117                 if (brush->flag & BRUSH_CUSTOM_ICON) {
118
119                         if (brush->icon_filepath[0]) {
120                                 // first use the path directly to try and load the file
121
122                                 BLI_strncpy(path, brush->icon_filepath, sizeof(brush->icon_filepath));
123                                 BLI_path_abs(path, G.main->name);
124
125                                 /* use default colorspaces for brushes */
126                                 brush->icon_imbuf = IMB_loadiffname(path, flags, NULL);
127
128                                 // otherwise lets try to find it in other directories
129                                 if (!(brush->icon_imbuf)) {
130                                         folder = BKE_appdir_folder_id(BLENDER_DATAFILES, "brushicons");
131
132                                         BLI_make_file_string(G.main->name, path, folder, brush->icon_filepath);
133
134                                         if (path[0]) {
135                                                 /* use fefault color spaces */
136                                                 brush->icon_imbuf = IMB_loadiffname(path, flags, NULL);
137                                         }
138                                 }
139
140                                 if (brush->icon_imbuf)
141                                         BKE_icon_changed(BKE_icon_id_ensure(&brush->id));
142                         }
143                 }
144         }
145
146         if (!(brush->icon_imbuf))
147                 brush->id.icon_id = 0;
148
149         return brush->icon_imbuf;
150 }
151
152 typedef struct ShaderPreview {
153         /* from wmJob */
154         void *owner;
155         short *stop, *do_update;
156         
157         Scene *scene;
158         ID *id;
159         ID *parent;
160         MTex *slot;
161         
162         /* datablocks with nodes need full copy during preview render, glsl uses it too */
163         Material *matcopy;
164         Tex *texcopy;
165         Lamp *lampcopy;
166         World *worldcopy;
167         
168         float col[4];       /* active object color */
169         
170         int sizex, sizey;
171         unsigned int *pr_rect;
172         int pr_method;
173
174         Main *bmain;
175         Main *pr_main;
176 } ShaderPreview;
177
178 typedef struct IconPreviewSize {
179         struct IconPreviewSize *next, *prev;
180         int sizex, sizey;
181         unsigned int *rect;
182 } IconPreviewSize;
183
184 typedef struct IconPreview {
185         Main *bmain;
186         Scene *scene;
187         void *owner;
188         ID *id;
189         ListBase sizes;
190 } IconPreview;
191
192 /* *************************** Preview for buttons *********************** */
193
194 static Main *G_pr_main = NULL;
195 static Main *G_pr_main_cycles = NULL;
196
197 #ifndef WITH_HEADLESS
198 static Main *load_main_from_memory(const void *blend, int blend_size)
199 {
200         const int fileflags = G.fileflags;
201         Main *bmain = NULL;
202         BlendFileData *bfd;
203
204         G.fileflags |= G_FILE_NO_UI;
205         bfd = BLO_read_from_memory(blend, blend_size, NULL, BLO_READ_SKIP_NONE);
206         if (bfd) {
207                 bmain = bfd->main;
208
209                 MEM_freeN(bfd);
210         }
211         G.fileflags = fileflags;
212
213         return bmain;
214 }
215 #endif
216
217 void ED_preview_ensure_dbase(void)
218 {
219 #ifndef WITH_HEADLESS
220         static bool base_initialized = false;
221         BLI_assert(BLI_thread_is_main());
222         if (!base_initialized) {
223                 G_pr_main = load_main_from_memory(datatoc_preview_blend, datatoc_preview_blend_size);
224                 G_pr_main_cycles = load_main_from_memory(datatoc_preview_cycles_blend, datatoc_preview_cycles_blend_size);
225                 base_initialized = true;
226         }
227 #endif
228 }
229
230 static bool check_engine_supports_textures(Scene *scene)
231 {
232         RenderEngineType *type = RE_engines_find(scene->r.engine);
233         return type->flag & RE_USE_TEXTURE_PREVIEW;
234 }
235
236 void ED_preview_free_dbase(void)
237 {
238         if (G_pr_main)
239                 BKE_main_free(G_pr_main);
240
241         if (G_pr_main_cycles)
242                 BKE_main_free(G_pr_main_cycles);
243 }
244
245 static Scene *preview_get_scene(Main *pr_main)
246 {
247         if (pr_main == NULL) return NULL;
248         
249         return pr_main->scene.first;
250 }
251
252 static const char *preview_layer_name(const char pr_type)
253 {
254         switch (pr_type) {
255                 case MA_FLAT:
256                         return "Flat";
257                 case MA_SPHERE:
258                         return "Sphere";
259                 case MA_CUBE:
260                         return "Cube";
261                 case MA_MONKEY:
262                         return "Monkey";
263                 case MA_SPHERE_A:
264                         return "World Sphere";
265                 case MA_TEXTURE:
266                         return "Texture";
267                 case MA_LAMP:
268                         return "Lamp";
269                 case MA_SKY:
270                         return "Sky";
271                 case MA_HAIR:
272                         return "Hair";
273                 case MA_ATMOS:
274                         return "Atmosphere";
275                 default:
276                         BLI_assert(!"Unknown preview type");
277                         return "";
278         }
279 }
280
281 static void set_preview_layer(ViewLayer *view_layer, char pr_type)
282 {
283         LayerCollection *lc;
284         const char *collection_name = preview_layer_name(pr_type);
285
286         for (lc = view_layer->layer_collections.first; lc; lc = lc->next) {
287                 if (STREQ(lc->scene_collection->name, collection_name)) {
288                         lc->flag = COLLECTION_VIEWPORT | COLLECTION_RENDER;
289                 }
290                 else {
291                         lc->flag = COLLECTION_DISABLED;
292                 }
293         }
294 }
295
296 static World *preview_get_localized_world(ShaderPreview *sp, World *world)
297 {
298         if (world == NULL) {
299                 return NULL;
300         }
301         if (sp->worldcopy != NULL) {
302                 return sp->worldcopy;
303         }
304         sp->worldcopy = BKE_world_localize(world);
305         BLI_addtail(&sp->pr_main->world, sp->worldcopy);
306         return sp->worldcopy;
307 }
308
309 /* call this with a pointer to initialize preview scene */
310 /* call this with NULL to restore assigned ID pointers in preview scene */
311 static Scene *preview_prepare_scene(Main *bmain, Scene *scene, ID *id, int id_type, ShaderPreview *sp)
312 {
313         Scene *sce;
314         Main *pr_main = sp->pr_main;
315
316         memcpy(pr_main->name, bmain->name, sizeof(pr_main->name));
317
318         sce = preview_get_scene(pr_main);
319         if (sce) {
320                 ViewLayer *view_layer = sce->view_layers.first;
321
322                 /* this flag tells render to not execute depsgraph or ipos etc */
323                 sce->r.scemode |= R_BUTS_PREVIEW;
324                 /* set world always back, is used now */
325                 sce->world = pr_main->world.first;
326                 /* now: exposure copy */
327                 if (scene->world) {
328                         sce->world->exp = scene->world->exp;
329                         sce->world->range = scene->world->range;
330                 }
331                 
332                 sce->r.color_mgt_flag = scene->r.color_mgt_flag;
333                 BKE_color_managed_display_settings_copy(&sce->display_settings, &scene->display_settings);
334
335                 BKE_color_managed_view_settings_free(&sce->view_settings);
336                 BKE_color_managed_view_settings_copy(&sce->view_settings, &scene->view_settings);
337                 
338                 /* prevent overhead for small renders and icons (32) */
339                 if (id && sp->sizex < 40) {
340                         sce->r.tilex = sce->r.tiley = 64;
341                 }
342                 else {
343                         sce->r.tilex = sce->r.xsch / 4;
344                         sce->r.tiley = sce->r.ysch / 4;
345                 }
346                 
347                 if ((id && sp->pr_method == PR_ICON_RENDER) && id_type != ID_WO)
348                         sce->r.alphamode = R_ALPHAPREMUL;
349                 else
350                         sce->r.alphamode = R_ADDSKY;
351
352                 sce->r.cfra = scene->r.cfra;
353
354                 if (id_type == ID_TE && !check_engine_supports_textures(scene)) {
355                         /* Force blender internal for texture icons and nodes render,
356                          * seems commonly used render engines does not support
357                          * such kind of rendering.
358                          */
359                         BLI_strncpy(sce->r.engine, RE_engine_id_BLENDER_EEVEE, sizeof(sce->r.engine));
360                 }
361                 else {
362                         BLI_strncpy(sce->r.engine, scene->r.engine, sizeof(sce->r.engine));
363                 }
364                 
365                 if (id_type == ID_MA) {
366                         Material *mat = NULL, *origmat = (Material *)id;
367                         
368                         if (origmat) {
369                                 /* work on a copy */
370                                 mat = BKE_material_localize(origmat);
371                                 sp->matcopy = mat;
372                                 BLI_addtail(&pr_main->mat, mat);
373                                 
374                                 /* use current scene world to light sphere */
375                                 if (mat->pr_type == MA_SPHERE_A && sp->pr_method == PR_BUTS_RENDER) {
376                                         /* Use current scene world to light sphere. */
377                                         sce->world = preview_get_localized_world(sp, scene->world);
378                                 }
379                                 else if (sce->world) {
380                                         /* Use a default world color. Using the current
381                                          * scene world can be slow if it has big textures. */
382                                         sce->world->use_nodes = false;
383                                         sce->world->horr = 0.5f;
384                                         sce->world->horg = 0.5f;
385                                         sce->world->horb = 0.5f;
386                                 }
387                                 
388                                 if (sp->pr_method == PR_ICON_RENDER) {
389                                         set_preview_layer(view_layer, MA_SPHERE_A);
390                                 }
391                                 else {
392                                         set_preview_layer(view_layer, mat->pr_type);
393
394                                         if (mat->nodetree && sp->pr_method == PR_NODE_RENDER) {
395                                                 /* two previews, they get copied by wmJob */
396                                                 BKE_node_preview_init_tree(mat->nodetree, sp->sizex, sp->sizey, true);
397                                                 BKE_node_preview_init_tree(origmat->nodetree, sp->sizex, sp->sizey, true);
398                                         }
399                                 }
400                         }
401                         else {
402                                 sce->r.mode &= ~(R_OSA);
403                                 
404                         }
405                         
406                         for (Base *base = view_layer->object_bases.first; base; base = base->next) {
407                                 if (base->object->id.name[2] == 'p') {
408                                         /* copy over object color, in case material uses it */
409                                         copy_v4_v4(base->object->col, sp->col);
410                                         
411                                         if (OB_TYPE_SUPPORT_MATERIAL(base->object->type)) {
412                                                 /* don't use assign_material, it changed mat->id.us, which shows in the UI */
413                                                 Material ***matar = give_matarar(base->object);
414                                                 int actcol = max_ii(base->object->actcol - 1, 0);
415
416                                                 if (matar && actcol < base->object->totcol)
417                                                         (*matar)[actcol] = mat;
418                                         }
419                                         else if (base->object->type == OB_LAMP) {
420                                                 base->flag |= BASE_VISIBLED;
421                                         }
422                                 }
423                         }
424                 }
425                 else if (id_type == ID_TE) {
426                         Tex *tex = NULL, *origtex = (Tex *)id;
427                         
428                         if (origtex) {
429                                 tex = BKE_texture_localize(origtex);
430                                 sp->texcopy = tex;
431                                 BLI_addtail(&pr_main->tex, tex);
432                         }
433                         set_preview_layer(view_layer, MA_TEXTURE);
434                         
435                         if (tex && tex->nodetree && sp->pr_method == PR_NODE_RENDER) {
436                                 /* two previews, they get copied by wmJob */
437                                 BKE_node_preview_init_tree(origtex->nodetree, sp->sizex, sp->sizey, true);
438                                 BKE_node_preview_init_tree(tex->nodetree, sp->sizex, sp->sizey, true);
439                         }
440                 }
441                 else if (id_type == ID_LA) {
442                         Lamp *la = NULL, *origla = (Lamp *)id;
443
444                         /* work on a copy */
445                         if (origla) {
446                                 la = BKE_lamp_localize(origla);
447                                 sp->lampcopy = la;
448                                 BLI_addtail(&pr_main->lamp, la);
449                         }
450
451                         set_preview_layer(view_layer, MA_LAMP);
452
453                         if (sce->world) {
454                                 /* Only use lighting from the lamp. */
455                                 sce->world->use_nodes = false;
456                                 sce->world->horr = 0.0f;
457                                 sce->world->horg = 0.0f;
458                                 sce->world->horb = 0.0f;
459                         }
460                                 
461                         for (Base *base = view_layer->object_bases.first; base; base = base->next) {
462                                 if (base->object->id.name[2] == 'p') {
463                                         if (base->object->type == OB_LAMP)
464                                                 base->object->data = la;
465                                 }
466                         }
467
468                         if (la && la->nodetree && sp->pr_method == PR_NODE_RENDER) {
469                                 /* two previews, they get copied by wmJob */
470                                 BKE_node_preview_init_tree(origla->nodetree, sp->sizex, sp->sizey, true);
471                                 BKE_node_preview_init_tree(la->nodetree, sp->sizex, sp->sizey, true);
472                         }
473                 }
474                 else if (id_type == ID_WO) {
475                         World *wrld = NULL, *origwrld = (World *)id;
476
477                         if (origwrld) {
478                                 wrld = BKE_world_localize(origwrld);
479                                 sp->worldcopy = wrld;
480                                 BLI_addtail(&pr_main->world, wrld);
481                         }
482
483                         set_preview_layer(view_layer, MA_SKY);
484                         sce->world = wrld;
485
486                         if (wrld && wrld->nodetree && sp->pr_method == PR_NODE_RENDER) {
487                                 /* two previews, they get copied by wmJob */
488                                 BKE_node_preview_init_tree(wrld->nodetree, sp->sizex, sp->sizey, true);
489                                 BKE_node_preview_init_tree(origwrld->nodetree, sp->sizex, sp->sizey, true);
490                         }
491                 }
492
493                 Depsgraph *depsgraph = BKE_scene_get_depsgraph(sce, view_layer, true);
494                 /* TODO(sergey): Use proper flag for tagging here. */
495                 DEG_graph_id_tag_update(pr_main, depsgraph, &sce->id, 0);
496                 DEG_relations_tag_update(pr_main);
497                 BKE_scene_graph_update_tagged(depsgraph, pr_main);
498
499                 return sce;
500         }
501         
502         return NULL;
503 }
504
505 /* new UI convention: draw is in pixel space already. */
506 /* uses UI_BTYPE_ROUNDBOX button in block to get the rect */
507 static bool ed_preview_draw_rect(ScrArea *sa, int split, int first, rcti *rect, rcti *newrect)
508 {
509         Render *re;
510         RenderView *rv;
511         RenderResult rres;
512         char name[32];
513         int offx = 0;
514         int newx = BLI_rcti_size_x(rect);
515         int newy = BLI_rcti_size_y(rect);
516         bool ok = false;
517
518         if (!split || first) sprintf(name, "Preview %p", (void *)sa);
519         else sprintf(name, "SecondPreview %p", (void *)sa);
520
521         if (split) {
522                 if (first) {
523                         offx = 0;
524                         newx = newx / 2;
525                 }
526                 else {
527                         offx = newx / 2;
528                         newx = newx - newx / 2;
529                 }
530         }
531
532         /* test if something rendered ok */
533         re = RE_GetRender(name);
534
535         if (re == NULL)
536                 return false;
537
538         RE_AcquireResultImageViews(re, &rres);
539
540         if (!BLI_listbase_is_empty(&rres.views)) {
541                 /* material preview only needs monoscopy (view 0) */
542                 rv = RE_RenderViewGetById(&rres, 0);
543         }
544         else {
545                 /* possible the job clears the views but we're still drawing T45496 */
546                 rv = NULL;
547         }
548
549         if (rv && rv->rectf) {
550                 
551                 if (ABS(rres.rectx - newx) < 2 && ABS(rres.recty - newy) < 2) {
552
553                         newrect->xmax = max_ii(newrect->xmax, rect->xmin + rres.rectx + offx);
554                         newrect->ymax = max_ii(newrect->ymax, rect->ymin + rres.recty);
555
556                         if (rres.rectx && rres.recty) {
557                                 unsigned char *rect_byte = MEM_mallocN(rres.rectx * rres.recty * sizeof(int), "ed_preview_draw_rect");
558                                 float fx = rect->xmin + offx;
559                                 float fy = rect->ymin;
560
561                                 /* material preview only needs monoscopy (view 0) */
562                                 if (re)
563                                         RE_AcquiredResultGet32(re, &rres, (unsigned int *)rect_byte, 0);
564
565                                 IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR);
566                                 immDrawPixelsTex(&state, fx, fy, rres.rectx, rres.recty, GL_RGBA, GL_UNSIGNED_BYTE, GL_NEAREST, rect_byte,
567                                                  1.0f, 1.0f, NULL);
568                                 
569                                 MEM_freeN(rect_byte);
570                                 
571                                 ok = 1;
572                         }
573                 }
574         }
575
576         RE_ReleaseResultImageViews(re, &rres);
577
578         return ok;
579 }
580
581 void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, rcti *rect)
582 {
583         if (idp) {
584                 wmWindowManager *wm = CTX_wm_manager(C);
585                 ScrArea *sa = CTX_wm_area(C);
586                 ID *id = (ID *)idp;
587                 ID *parent = (ID *)parentp;
588                 MTex *slot = (MTex *)slotp;
589                 SpaceButs *sbuts = CTX_wm_space_buts(C);
590                 ShaderPreview *sp = WM_jobs_customdata(wm, sa);
591                 rcti newrect;
592                 int ok;
593                 int newx = BLI_rcti_size_x(rect);
594                 int newy = BLI_rcti_size_y(rect);
595
596                 newrect.xmin = rect->xmin;
597                 newrect.xmax = rect->xmin;
598                 newrect.ymin = rect->ymin;
599                 newrect.ymax = rect->ymin;
600
601                 if (parent) {
602                         ok = ed_preview_draw_rect(sa, 1, 1, rect, &newrect);
603                         ok &= ed_preview_draw_rect(sa, 1, 0, rect, &newrect);
604                 }
605                 else
606                         ok = ed_preview_draw_rect(sa, 0, 0, rect, &newrect);
607
608                 if (ok)
609                         *rect = newrect;
610
611                 /* start a new preview render job if signaled through sbuts->preview,
612                  * if no render result was found and no preview render job is running,
613                  * or if the job is running and the size of preview changed */
614                 if ((sbuts != NULL && sbuts->preview) ||
615                     (!ok && !WM_jobs_test(wm, sa, WM_JOB_TYPE_RENDER_PREVIEW)) ||
616                     (sp && (ABS(sp->sizex - newx) >= 2 || ABS(sp->sizey - newy) > 2)))
617                 {
618                         if (sbuts != NULL) {
619                                 sbuts->preview = 0;
620                         }
621                         ED_preview_shader_job(C, sa, id, parent, slot, newx, newy, PR_BUTS_RENDER);
622                 }
623         }
624 }
625
626 /* **************************** new shader preview system ****************** */
627
628 /* inside thread, called by renderer, sets job update value */
629 static void shader_preview_update(void *spv, RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect))
630 {
631         ShaderPreview *sp = spv;
632         
633         *(sp->do_update) = true;
634 }
635
636 /* called by renderer, checks job value */
637 static int shader_preview_break(void *spv)
638 {
639         ShaderPreview *sp = spv;
640
641         return *(sp->stop);
642 }
643
644 /* outside thread, called before redraw notifiers, it moves finished preview over */
645 static void shader_preview_updatejob(void *spv)
646 {
647         ShaderPreview *sp = spv;
648         
649         if (sp->id) {
650                 if (sp->pr_method == PR_NODE_RENDER) {
651                         if (GS(sp->id->name) == ID_MA) {
652                                 Material *mat = (Material *)sp->id;
653                                 
654                                 if (sp->matcopy && mat->nodetree && sp->matcopy->nodetree)
655                                         ntreeLocalSync(sp->matcopy->nodetree, mat->nodetree);
656                         }
657                         else if (GS(sp->id->name) == ID_TE) {
658                                 Tex *tex = (Tex *)sp->id;
659                                 
660                                 if (sp->texcopy && tex->nodetree && sp->texcopy->nodetree)
661                                         ntreeLocalSync(sp->texcopy->nodetree, tex->nodetree);
662                         }
663                         else if (GS(sp->id->name) == ID_WO) {
664                                 World *wrld = (World *)sp->id;
665                                 
666                                 if (sp->worldcopy && wrld->nodetree && sp->worldcopy->nodetree)
667                                         ntreeLocalSync(sp->worldcopy->nodetree, wrld->nodetree);
668                         }
669                         else if (GS(sp->id->name) == ID_LA) {
670                                 Lamp *la = (Lamp *)sp->id;
671                                 
672                                 if (sp->lampcopy && la->nodetree && sp->lampcopy->nodetree)
673                                         ntreeLocalSync(sp->lampcopy->nodetree, la->nodetree);
674                         }
675                 }
676         }
677 }
678
679 static void shader_preview_render(ShaderPreview *sp, ID *id, int split, int first)
680 {
681         Render *re;
682         Scene *sce;
683         float oldlens;
684         short idtype = GS(id->name);
685         char name[32];
686         int sizex;
687         Main *pr_main = sp->pr_main;
688         
689         /* in case of split preview, use border render */
690         if (split) {
691                 if (first) sizex = sp->sizex / 2;
692                 else sizex = sp->sizex - sp->sizex / 2;
693         }
694         else {
695                 sizex = sp->sizex;
696         }
697
698         /* we have to set preview variables first */
699         sce = preview_get_scene(pr_main);
700         if (sce) {
701                 sce->r.xsch = sizex;
702                 sce->r.ysch = sp->sizey;
703                 sce->r.size = 100;
704         }
705         
706         /* get the stuff from the builtin preview dbase */
707         sce = preview_prepare_scene(sp->bmain, sp->scene, id, idtype, sp);
708         if (sce == NULL) return;
709         
710         if (!split || first) sprintf(name, "Preview %p", sp->owner);
711         else sprintf(name, "SecondPreview %p", sp->owner);
712         re = RE_GetRender(name);
713         
714         /* full refreshed render from first tile */
715         if (re == NULL)
716                 re = RE_NewRender(name);
717                 
718         /* sce->r gets copied in RE_InitState! */
719         sce->r.scemode &= ~(R_MATNODE_PREVIEW | R_TEXNODE_PREVIEW);
720         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
721
722         if (sp->pr_method == PR_ICON_RENDER) {
723                 sce->r.scemode |= R_NO_IMAGE_LOAD;
724                 sce->r.mode |= R_OSA;
725         }
726         else if (sp->pr_method == PR_NODE_RENDER) {
727                 if (idtype == ID_MA) sce->r.scemode |= R_MATNODE_PREVIEW;
728                 else if (idtype == ID_TE) sce->r.scemode |= R_TEXNODE_PREVIEW;
729                 sce->r.mode &= ~R_OSA;
730         }
731         else {  /* PR_BUTS_RENDER */
732                 sce->r.mode |= R_OSA;
733         }
734
735
736         /* callbacs are cleared on GetRender() */
737         if (ELEM(sp->pr_method, PR_BUTS_RENDER, PR_NODE_RENDER)) {
738                 RE_display_update_cb(re, sp, shader_preview_update);
739         }
740         /* set this for all previews, default is react to G.is_break still */
741         RE_test_break_cb(re, sp, shader_preview_break);
742         
743         /* lens adjust */
744         oldlens = ((Camera *)sce->camera->data)->lens;
745         if (sizex > sp->sizey)
746                 ((Camera *)sce->camera->data)->lens *= (float)sp->sizey / (float)sizex;
747
748         /* entire cycle for render engine */
749         RE_PreviewRender(re, pr_main, sce);
750
751         ((Camera *)sce->camera->data)->lens = oldlens;
752
753         /* handle results */
754         if (sp->pr_method == PR_ICON_RENDER) {
755                 // char *rct= (char *)(sp->pr_rect + 32*16 + 16);
756                 
757                 if (sp->pr_rect)
758                         RE_ResultGet32(re, sp->pr_rect);
759         }
760
761         /* unassign the pointers, reset vars */
762         preview_prepare_scene(sp->bmain, sp->scene, NULL, GS(id->name), sp);
763         
764         /* XXX bad exception, end-exec is not being called in render, because it uses local main */
765 //      if (idtype == ID_TE) {
766 //              Tex *tex= (Tex *)id;
767 //              if (tex->use_nodes && tex->nodetree)
768 //                      ntreeEndExecTree(tex->nodetree);
769 //      }
770
771 }
772
773 /* runs inside thread for material and icons */
774 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
775 {
776         ShaderPreview *sp = customdata;
777
778         sp->stop = stop;
779         sp->do_update = do_update;
780
781         if (sp->parent) {
782                 shader_preview_render(sp, sp->id, 1, 1);
783                 shader_preview_render(sp, sp->parent, 1, 0);
784         }
785         else
786                 shader_preview_render(sp, sp->id, 0, 0);
787
788         *do_update = true;
789 }
790
791 static void shader_preview_free(void *customdata)
792 {
793         ShaderPreview *sp = customdata;
794         Main *pr_main = sp->pr_main;
795         
796         if (sp->matcopy) {
797                 struct IDProperty *properties;
798                 
799                 /* node previews */
800                 shader_preview_updatejob(sp);
801                 
802                 /* get rid of copied material */
803                 BLI_remlink(&pr_main->mat, sp->matcopy);
804                 
805                 BKE_material_free(sp->matcopy);
806
807                 properties = IDP_GetProperties((ID *)sp->matcopy, false);
808                 if (properties) {
809                         IDP_FreeProperty(properties);
810                         MEM_freeN(properties);
811                 }
812                 MEM_freeN(sp->matcopy);
813         }
814         if (sp->texcopy) {
815                 struct IDProperty *properties;
816                 /* node previews */
817                 shader_preview_updatejob(sp);
818                 
819                 /* get rid of copied texture */
820                 BLI_remlink(&pr_main->tex, sp->texcopy);
821                 BKE_texture_free(sp->texcopy);
822                 
823                 properties = IDP_GetProperties((ID *)sp->texcopy, false);
824                 if (properties) {
825                         IDP_FreeProperty(properties);
826                         MEM_freeN(properties);
827                 }
828                 MEM_freeN(sp->texcopy);
829         }
830         if (sp->worldcopy) {
831                 struct IDProperty *properties;
832                 /* node previews */
833                 shader_preview_updatejob(sp);
834                 
835                 /* get rid of copied world */
836                 BLI_remlink(&pr_main->world, sp->worldcopy);
837                 BKE_world_free(sp->worldcopy);
838                 
839                 properties = IDP_GetProperties((ID *)sp->worldcopy, false);
840                 if (properties) {
841                         IDP_FreeProperty(properties);
842                         MEM_freeN(properties);
843                 }
844                 MEM_freeN(sp->worldcopy);
845         }
846         if (sp->lampcopy) {
847                 struct IDProperty *properties;
848                 /* node previews */
849                 shader_preview_updatejob(sp);
850                 
851                 /* get rid of copied lamp */
852                 BLI_remlink(&pr_main->lamp, sp->lampcopy);
853                 BKE_lamp_free(sp->lampcopy);
854                 
855                 properties = IDP_GetProperties((ID *)sp->lampcopy, false);
856                 if (properties) {
857                         IDP_FreeProperty(properties);
858                         MEM_freeN(properties);
859                 }
860                 MEM_freeN(sp->lampcopy);
861         }
862         
863         MEM_freeN(sp);
864 }
865
866 /* ************************* icon preview ********************** */
867
868 static void icon_copy_rect(ImBuf *ibuf, unsigned int w, unsigned int h, unsigned int *rect)
869 {
870         struct ImBuf *ima;
871         unsigned int *drect, *srect;
872         float scaledx, scaledy;
873         short ex, ey, dx, dy;
874
875         /* paranoia test */
876         if (ibuf == NULL || (ibuf->rect == NULL && ibuf->rect_float == NULL))
877                 return;
878         
879         /* waste of cpu cyles... but the imbuf API has no other way to scale fast (ton) */
880         ima = IMB_dupImBuf(ibuf);
881         
882         if (!ima) 
883                 return;
884         
885         if (ima->x > ima->y) {
886                 scaledx = (float)w;
887                 scaledy =  ( (float)ima->y / (float)ima->x) * (float)w;
888         }
889         else {
890                 scaledx =  ( (float)ima->x / (float)ima->y) * (float)h;
891                 scaledy = (float)h;
892         }
893         
894         ex = (short)scaledx;
895         ey = (short)scaledy;
896         
897         dx = (w - ex) / 2;
898         dy = (h - ey) / 2;
899         
900         IMB_scalefastImBuf(ima, ex, ey);
901         
902         /* if needed, convert to 32 bits */
903         if (ima->rect == NULL)
904                 IMB_rect_from_float(ima);
905
906         srect = ima->rect;
907         drect = rect;
908
909         drect += dy * w + dx;
910         for (; ey > 0; ey--) {
911                 memcpy(drect, srect, ex * sizeof(int));
912                 drect += w;
913                 srect += ima->x;
914         }
915
916         IMB_freeImBuf(ima);
917 }
918
919 static void set_alpha(char *cp, int sizex, int sizey, char alpha) 
920 {
921         int a, size = sizex * sizey;
922
923         for (a = 0; a < size; a++, cp += 4)
924                 cp[3] = alpha;
925 }
926
927 static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
928 {
929         ShaderPreview *sp = customdata;
930
931         if (sp->pr_method == PR_ICON_DEFERRED) {
932                 PreviewImage *prv = sp->owner;
933                 ImBuf *thumb;
934                 char *deferred_data = PRV_DEFERRED_DATA(prv);
935                 int source =  deferred_data[0];
936                 char *path = &deferred_data[1];
937
938 //              printf("generating deferred %d×%d preview for %s\n", sp->sizex, sp->sizey, path);
939
940                 thumb = IMB_thumb_manage(path, THB_LARGE, source);
941
942                 if (thumb) {
943                         /* PreviewImage assumes premultiplied alhpa... */
944                         IMB_premultiply_alpha(thumb);
945
946                         icon_copy_rect(thumb, sp->sizex, sp->sizey, sp->pr_rect);
947                         IMB_freeImBuf(thumb);
948                 }
949         }
950         else {
951                 ID *id = sp->id;
952                 short idtype = GS(id->name);
953
954                 if (idtype == ID_IM) {
955                         Image *ima = (Image *)id;
956                         ImBuf *ibuf = NULL;
957                         ImageUser iuser = {NULL};
958
959                         /* ima->ok is zero when Image cannot load */
960                         if (ima == NULL || ima->ok == 0)
961                                 return;
962
963                         /* setup dummy image user */
964                         iuser.ok = iuser.framenr = 1;
965                         iuser.scene = sp->scene;
966
967                         /* elubie: this needs to be changed: here image is always loaded if not
968                          * already there. Very expensive for large images. Need to find a way to
969                          * only get existing ibuf */
970                         ibuf = BKE_image_acquire_ibuf(ima, &iuser, NULL);
971                         if (ibuf == NULL || ibuf->rect == NULL) {
972                                 BKE_image_release_ibuf(ima, ibuf, NULL);
973                                 return;
974                         }
975
976                         icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);
977
978                         *do_update = true;
979
980                         BKE_image_release_ibuf(ima, ibuf, NULL);
981                 }
982                 else if (idtype == ID_BR) {
983                         Brush *br = (Brush *)id;
984
985                         br->icon_imbuf = get_brush_icon(br);
986
987                         memset(sp->pr_rect, 0x88, sp->sizex * sp->sizey * sizeof(unsigned int));
988
989                         if (!(br->icon_imbuf) || !(br->icon_imbuf->rect))
990                                 return;
991
992                         icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);
993
994                         *do_update = true;
995                 }
996                 else if (idtype == ID_SCR) {
997                         bScreen *screen = (bScreen *)id;
998
999                         ED_screen_preview_render(screen, sp->sizex, sp->sizey, sp->pr_rect);
1000                         *do_update = true;
1001                 }
1002                 else {
1003                         /* re-use shader job */
1004                         shader_preview_startjob(customdata, stop, do_update);
1005
1006                         /* world is rendered with alpha=0, so it wasn't displayed
1007                          * this could be render option for sky to, for later */
1008                         if (idtype == ID_WO) {
1009                                 set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
1010                         }
1011                 }
1012         }
1013 }
1014
1015 /* use same function for icon & shader, so the job manager
1016  * does not run two of them at the same time. */
1017
1018 static void common_preview_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
1019 {
1020         ShaderPreview *sp = customdata;
1021
1022         if (ELEM(sp->pr_method, PR_ICON_RENDER, PR_ICON_DEFERRED))
1023                 icon_preview_startjob(customdata, stop, do_update);
1024         else
1025                 shader_preview_startjob(customdata, stop, do_update);
1026 }
1027
1028 /* exported functions */
1029
1030 static void icon_preview_add_size(IconPreview *ip, unsigned int *rect, int sizex, int sizey)
1031 {
1032         IconPreviewSize *cur_size = ip->sizes.first, *new_size;
1033
1034         while (cur_size) {
1035                 if (cur_size->sizex == sizex && cur_size->sizey == sizey) {
1036                         /* requested size is already in list, no need to add it again */
1037                         return;
1038                 }
1039
1040                 cur_size = cur_size->next;
1041         }
1042
1043         new_size = MEM_callocN(sizeof(IconPreviewSize), "IconPreviewSize");
1044         new_size->sizex = sizex;
1045         new_size->sizey = sizey;
1046         new_size->rect = rect;
1047
1048         BLI_addtail(&ip->sizes, new_size);
1049 }
1050
1051 static void icon_preview_startjob_all_sizes(void *customdata, short *stop, short *do_update, float *progress)
1052 {
1053         IconPreview *ip = (IconPreview *)customdata;
1054         IconPreviewSize *cur_size;
1055
1056         for (cur_size = ip->sizes.first; cur_size; cur_size = cur_size->next) {
1057                 PreviewImage *prv = ip->owner;
1058
1059                 if (prv->tag & PRV_TAG_DEFFERED_DELETE) {
1060                         /* Non-thread-protected reading is not an issue here. */
1061                         continue;
1062                 }
1063
1064                 ShaderPreview *sp = MEM_callocN(sizeof(ShaderPreview), "Icon ShaderPreview");
1065                 const bool is_render = !(prv->tag & PRV_TAG_DEFFERED);
1066
1067                 /* construct shader preview from image size and previewcustomdata */
1068                 sp->scene = ip->scene;
1069                 sp->owner = ip->owner;
1070                 sp->sizex = cur_size->sizex;
1071                 sp->sizey = cur_size->sizey;
1072                 sp->pr_method = is_render ? PR_ICON_RENDER : PR_ICON_DEFERRED;
1073                 sp->pr_rect = cur_size->rect;
1074                 sp->id = ip->id;
1075                 sp->bmain = ip->bmain;
1076
1077                 if (is_render) {
1078                         BLI_assert(ip->id);
1079                         /* texture icon rendering is hardcoded to use the BI scene,
1080                          * so don't even think of using cycle's bmain for
1081                          * texture icons
1082                          */
1083                         if (GS(ip->id->name) != ID_TE)
1084                                 sp->pr_main = G_pr_main_cycles;
1085                         else
1086                                 sp->pr_main = G_pr_main;
1087                 }
1088
1089                 common_preview_startjob(sp, stop, do_update, progress);
1090                 shader_preview_free(sp);
1091         }
1092 }
1093
1094 static void icon_preview_endjob(void *customdata)
1095 {
1096         IconPreview *ip = customdata;
1097
1098         if (ip->id) {
1099
1100                 if (GS(ip->id->name) == ID_BR)
1101                         WM_main_add_notifier(NC_BRUSH | NA_EDITED, ip->id);
1102 #if 0           
1103                 if (GS(ip->id->name) == ID_MA) {
1104                         Material *ma = (Material *)ip->id;
1105                         PreviewImage *prv_img = ma->preview;
1106                         int i;
1107
1108                         /* signal to gpu texture */
1109                         for (i = 0; i < NUM_ICON_SIZES; ++i) {
1110                                 if (prv_img->gputexture[i]) {
1111                                         GPU_texture_free(prv_img->gputexture[i]);
1112                                         prv_img->gputexture[i] = NULL;
1113                                         WM_main_add_notifier(NC_MATERIAL|ND_SHADING_DRAW, ip->id);
1114                                 }
1115                         }
1116                 }
1117 #endif
1118         }
1119
1120         if (ip->owner) {
1121                 PreviewImage *prv_img = ip->owner;
1122                 prv_img->tag &= ~PRV_TAG_DEFFERED_RENDERING;
1123                 if (prv_img->tag & PRV_TAG_DEFFERED_DELETE) {
1124                         BLI_assert(prv_img->tag & PRV_TAG_DEFFERED);
1125                         BKE_previewimg_cached_release_pointer(prv_img);
1126                 }
1127         }
1128 }
1129
1130 static void icon_preview_free(void *customdata)
1131 {
1132         IconPreview *ip = (IconPreview *)customdata;
1133
1134         BLI_freelistN(&ip->sizes);
1135         MEM_freeN(ip);
1136 }
1137
1138 void ED_preview_icon_render(Main *bmain, Scene *scene, ID *id, unsigned int *rect, int sizex, int sizey)
1139 {
1140         IconPreview ip = {NULL};
1141         short stop = false, update = false;
1142         float progress = 0.0f;
1143
1144         ED_preview_ensure_dbase();
1145
1146         ip.bmain = bmain;
1147         ip.scene = scene;
1148         ip.owner = BKE_previewimg_id_ensure(id);
1149         ip.id = id;
1150
1151         icon_preview_add_size(&ip, rect, sizex, sizey);
1152
1153         icon_preview_startjob_all_sizes(&ip, &stop, &update, &progress);
1154
1155         icon_preview_endjob(&ip);
1156
1157         BLI_freelistN(&ip.sizes);
1158 }
1159
1160 void ED_preview_icon_job(const bContext *C, void *owner, ID *id, unsigned int *rect, int sizex, int sizey)
1161 {
1162         wmJob *wm_job;
1163         IconPreview *ip, *old_ip;
1164
1165         ED_preview_ensure_dbase();
1166
1167         /* suspended start means it starts after 1 timer step, see WM_jobs_timer below */
1168         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Icon Preview",
1169                              WM_JOB_EXCL_RENDER | WM_JOB_SUSPEND, WM_JOB_TYPE_RENDER_PREVIEW);
1170
1171         ip = MEM_callocN(sizeof(IconPreview), "icon preview");
1172
1173         /* render all resolutions from suspended job too */
1174         old_ip = WM_jobs_customdata_get(wm_job);
1175         if (old_ip)
1176                 BLI_movelisttolist(&ip->sizes, &old_ip->sizes);
1177
1178         /* customdata for preview thread */
1179         ip->bmain = CTX_data_main(C);
1180         ip->scene = CTX_data_scene(C);
1181         ip->owner = owner;
1182         ip->id = id;
1183
1184         icon_preview_add_size(ip, rect, sizex, sizey);
1185
1186         /* Special threading hack: warn main code that this preview is being rendered and cannot be freed... */
1187         {
1188                 PreviewImage *prv_img = owner;
1189                 if (prv_img->tag & PRV_TAG_DEFFERED) {
1190                         prv_img->tag |= PRV_TAG_DEFFERED_RENDERING;
1191                 }
1192         }
1193
1194         /* setup job */
1195         WM_jobs_customdata_set(wm_job, ip, icon_preview_free);
1196         WM_jobs_timer(wm_job, 0.1, NC_WINDOW, NC_WINDOW);
1197         WM_jobs_callbacks(wm_job, icon_preview_startjob_all_sizes, NULL, NULL, icon_preview_endjob);
1198
1199         WM_jobs_start(CTX_wm_manager(C), wm_job);
1200 }
1201
1202 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, MTex *slot, int sizex, int sizey, int method)
1203 {
1204         Object *ob = CTX_data_active_object(C);
1205         wmJob *wm_job;
1206         ShaderPreview *sp;
1207         Scene *scene = CTX_data_scene(C);
1208         short id_type = GS(id->name);
1209
1210         /* Use workspace render only for buttons Window, since the other previews are related to the datablock. */
1211
1212         /* Only texture node preview is supported with Cycles. */
1213         if (method == PR_NODE_RENDER && id_type != ID_TE) {
1214                 return;
1215         }
1216
1217         ED_preview_ensure_dbase();
1218
1219         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Shader Preview",
1220                             WM_JOB_EXCL_RENDER, WM_JOB_TYPE_RENDER_PREVIEW);
1221         sp = MEM_callocN(sizeof(ShaderPreview), "shader preview");
1222
1223         /* customdata for preview thread */
1224         sp->scene = scene;
1225         sp->owner = owner;
1226         sp->sizex = sizex;
1227         sp->sizey = sizey;
1228         sp->pr_method = method;
1229         sp->id = id;
1230         sp->parent = parent;
1231         sp->slot = slot;
1232         sp->bmain = CTX_data_main(C);
1233
1234         /* hardcoded preview .blend for Eevee + Cycles, this should be solved
1235          * once with custom preview .blend path for external engines */
1236         if ((method != PR_NODE_RENDER) && id_type != ID_TE) {
1237                 sp->pr_main = G_pr_main_cycles;
1238         }
1239         else {
1240                 sp->pr_main = G_pr_main;
1241         }
1242
1243         if (ob && ob->totcol) copy_v4_v4(sp->col, ob->col);
1244         else sp->col[0] = sp->col[1] = sp->col[2] = sp->col[3] = 1.0f;
1245         
1246         /* setup job */
1247         WM_jobs_customdata_set(wm_job, sp, shader_preview_free);
1248         WM_jobs_timer(wm_job, 0.1, NC_MATERIAL, NC_MATERIAL);
1249         WM_jobs_callbacks(wm_job, common_preview_startjob, NULL, shader_preview_updatejob, NULL);
1250         
1251         WM_jobs_start(CTX_wm_manager(C), wm_job);
1252 }
1253
1254 void ED_preview_kill_jobs(wmWindowManager *wm, Main *UNUSED(bmain))
1255 {
1256         if (wm)
1257                 WM_jobs_kill(wm, NULL, common_preview_startjob);
1258 }
1259