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