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