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