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