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