Merge with trunk r41342
[blender.git] / source / blender / editors / render / render_preview.c
1 /* 
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * The Original Code is Copyright (C) Blender Foundation.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/editors/render/render_preview.c
30  *  \ingroup edrend
31  */
32
33
34 /* global includes */
35
36 #include <stdlib.h>
37 #include <math.h>
38 #include <string.h>
39
40 #ifndef WIN32
41 #include <unistd.h>
42 #else
43 #include <io.h>
44 #endif   
45 #include "MEM_guardedalloc.h"
46
47 #include "BLO_readfile.h" 
48
49 #include "BLI_math.h"
50 #include "BLI_blenlib.h"
51 #include "BLI_threads.h"
52 #include "BLI_utildefines.h"
53
54 #include "DNA_world_types.h"
55 #include "DNA_camera_types.h"
56 #include "DNA_material_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_lamp_types.h"
60 #include "DNA_space_types.h"
61 #include "DNA_view3d_types.h"
62 #include "DNA_scene_types.h"
63 #include "DNA_brush_types.h"
64 #include "DNA_screen_types.h"
65
66 #include "BKE_brush.h"
67 #include "BKE_context.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_library.h"
74 #include "BKE_main.h"
75 #include "BKE_material.h"
76 #include "BKE_node.h"
77 #include "BKE_object.h"
78 #include "BKE_texture.h"
79 #include "BKE_world.h"
80
81 #include "IMB_imbuf.h"
82 #include "IMB_imbuf_types.h"
83
84 #include "BIF_gl.h"
85 #include "BIF_glutil.h"
86
87 #include "PIL_time.h"
88
89 #include "RE_pipeline.h"
90
91
92 #include "WM_api.h"
93 #include "WM_types.h"
94
95 #include "ED_render.h"
96 #include "ED_view3d.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[240];
107         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                                 brush->icon_imbuf= IMB_loadiffname(path, flags);
119
120                                 // otherwise lets try to find it in other directories
121                                 if (!(brush->icon_imbuf)) {
122                                         folder= BLI_get_folder(BLENDER_DATAFILES, "brushicons");
123
124                                         BLI_make_file_string(G.main->name, path, folder, brush->icon_filepath);
125
126                                         if (path[0])
127                                                 brush->icon_imbuf= IMB_loadiffname(path, flags);
128                                 }
129
130                                 if (brush->icon_imbuf)
131                                         BKE_icon_changed(BKE_icon_getid(&brush->id));
132                         }
133                 }
134         }
135
136         if (!(brush->icon_imbuf))
137                 brush->id.icon_id = 0;
138
139         return brush->icon_imbuf;
140 }
141
142 typedef struct ShaderPreview {
143         /* from wmJob */
144         void *owner;
145         short *stop, *do_update;
146         
147         Scene *scene;
148         ID *id;
149         ID *parent;
150         MTex *slot;
151         
152         /* datablocks with nodes need full copy during preview render, glsl uses it too */
153         Material *matcopy;
154         Tex *texcopy;
155         Lamp *lampcopy;
156         World *worldcopy;
157         
158         float col[4];           /* active object color */
159         
160         int sizex, sizey;
161         unsigned int *pr_rect;
162         int pr_method;
163         
164 } ShaderPreview;
165
166 /* *************************** Preview for buttons *********************** */
167
168 static Main *pr_main= NULL;
169
170 void ED_preview_init_dbase(void)
171 {
172 #ifndef WITH_HEADLESS
173         BlendFileData *bfd;
174         extern int datatoc_preview_blend_size;
175         extern char datatoc_preview_blend[];
176         const int fileflags= G.fileflags;
177         
178         G.fileflags |= G_FILE_NO_UI;
179         bfd= BLO_read_from_memory(datatoc_preview_blend, datatoc_preview_blend_size, NULL);
180         if (bfd) {
181                 pr_main= bfd->main;
182                 
183                 MEM_freeN(bfd);
184         }
185         G.fileflags= fileflags;
186 #endif
187 }
188
189 void ED_preview_free_dbase(void)
190 {
191         if(pr_main)
192                 free_main(pr_main);
193 }
194
195 static int preview_mat_has_sss(Material *mat, bNodeTree *ntree)
196 {
197         if(mat) {
198                 if(mat->sss_flag & MA_DIFF_SSS)
199                         return 1;
200                 if(mat->nodetree)
201                         if( preview_mat_has_sss(NULL, mat->nodetree))
202                                 return 1;
203         }
204         else if(ntree) {
205                 bNode *node;
206                 for(node= ntree->nodes.first; node; node= node->next) {
207                         if(node->type==NODE_GROUP && node->id) {
208                                 if( preview_mat_has_sss(NULL, (bNodeTree *)node->id))
209                                         return 1;
210                         }
211                         else if(node->id && ELEM(node->type, SH_NODE_MATERIAL, SH_NODE_MATERIAL_EXT)) {
212                                 mat= (Material *)node->id;
213                                 if(mat->sss_flag & MA_DIFF_SSS)
214                                         return 1;
215                         }
216                 }
217         }
218         return 0;
219 }
220
221 /* call this with a pointer to initialize preview scene */
222 /* call this with NULL to restore assigned ID pointers in preview scene */
223 static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPreview *sp)
224 {
225         Scene *sce;
226         Base *base;
227         
228         if(pr_main==NULL) return NULL;
229         
230         sce= pr_main->scene.first;
231         if(sce) {
232                 
233                 /* this flag tells render to not execute depsgraph or ipos etc */
234                 sce->r.scemode |= R_PREVIEWBUTS;
235                 /* set world always back, is used now */
236                 sce->world= pr_main->world.first;
237                 /* now: exposure copy */
238                 if(scene->world) {
239                         sce->world->exp= scene->world->exp;
240                         sce->world->range= scene->world->range;
241                 }
242                 
243                 sce->r.color_mgt_flag = scene->r.color_mgt_flag;
244                 
245                 /* prevent overhead for small renders and icons (32) */
246                 if(id && sp->sizex < 40)
247                         sce->r.xparts= sce->r.yparts= 1;
248                 else
249                         sce->r.xparts= sce->r.yparts= 4;
250                 
251                 /* exception: don't color manage texture previews or icons */
252                 if((id && sp->pr_method==PR_ICON_RENDER) || id_type == ID_TE)
253                         sce->r.color_mgt_flag &= ~R_COLOR_MANAGEMENT;
254                 
255                 if((id && sp->pr_method==PR_ICON_RENDER) && id_type != ID_WO)
256                         sce->r.alphamode= R_ALPHAPREMUL;
257                 else
258                         sce->r.alphamode= R_ADDSKY;
259
260                 sce->r.cfra= scene->r.cfra;
261                 BLI_strncpy(sce->r.engine, scene->r.engine, sizeof(sce->r.engine));
262                 
263                 if(id_type==ID_MA) {
264                         Material *mat= NULL, *origmat= (Material *)id;
265                         
266                         if(origmat) {
267                                 /* work on a copy */
268                                 mat= localize_material(origmat);
269                                 sp->matcopy= mat;
270                                 BLI_addtail(&pr_main->mat, mat);
271                                 
272                                 init_render_material(mat, 0, NULL);             /* call that retrieves mode_l */
273                                 end_render_material(mat);
274                                 
275                                 /* un-useful option */
276                                 if(sp->pr_method==PR_ICON_RENDER)
277                                         mat->shade_flag &= ~MA_OBCOLOR;
278
279                                 /* turn on raytracing if needed */
280                                 if(mat->mode_l & MA_RAYMIRROR)
281                                         sce->r.mode |= R_RAYTRACE;
282                                 if(mat->material_type == MA_TYPE_VOLUME)
283                                         sce->r.mode |= R_RAYTRACE;
284                                 if((mat->mode_l & MA_RAYTRANSP) && (mat->mode_l & MA_TRANSP))
285                                         sce->r.mode |= R_RAYTRACE;
286                                 if(preview_mat_has_sss(mat, NULL))
287                                         sce->r.mode |= R_SSS;
288                                 
289                                 /* turn off fake shadows if needed */
290                                 /* this only works in a specific case where the preview.blend contains
291                                  * an object starting with 'c' which has a material linked to it (not the obdata)
292                                  * and that material has a fake shadow texture in the active texture slot */
293                                 for(base= sce->base.first; base; base= base->next) {
294                                         if(base->object->id.name[2]=='c') {
295                                                 Material *shadmat= give_current_material(base->object, base->object->actcol);
296                                                 if(shadmat) {
297                                                         if (mat->mode & MA_SHADBUF) shadmat->septex = 0;
298                                                         else shadmat->septex |= 1;
299                                                 }
300                                         }
301                                 }
302                                 
303                                 /* turn off bounce lights for volume, 
304                                  * doesn't make much visual difference and slows it down too */
305                                 if(mat->material_type == MA_TYPE_VOLUME) {
306                                         for(base= sce->base.first; base; base= base->next) {
307                                                 if(base->object->type == OB_LAMP) {
308                                                         /* if doesn't match 'Lamp.002' --> main key light */
309                                                         if( strcmp(base->object->id.name+2, "Lamp.002") != 0 ) {
310                                                                 base->object->restrictflag |= OB_RESTRICT_RENDER;
311                                                         }
312                                                 }
313                                         }
314                                 }
315
316                                 
317                                 if(sp->pr_method==PR_ICON_RENDER) {
318                                         if (mat->material_type == MA_TYPE_HALO) {
319                                                 sce->lay= 1<<MA_FLAT;
320                                         } 
321                                         else {
322                                                 sce->lay= 1<<MA_SPHERE_A;
323                                         }
324                                 }
325                                 else {
326                                         sce->lay= 1<<mat->pr_type;
327                                         if(mat->nodetree && sp->pr_method==PR_NODE_RENDER) {
328                                                 /* two previews, they get copied by wmJob */
329                                                 ntreeInitPreview(mat->nodetree, sp->sizex, sp->sizey);
330                                                 ntreeInitPreview(origmat->nodetree, sp->sizex, sp->sizey);
331                                         }
332                                 }
333                         }
334                         else {
335                                 sce->r.mode &= ~(R_OSA|R_RAYTRACE|R_SSS);
336                                 
337                         }
338                         
339                         for(base= sce->base.first; base; base= base->next) {
340                                 if(base->object->id.name[2]=='p') {
341                                         /* copy over object color, in case material uses it */
342                                         copy_v4_v4(base->object->col, sp->col);
343                                         
344                                         if(OB_TYPE_SUPPORT_MATERIAL(base->object->type)) {
345                                                 /* don't use assign_material, it changed mat->id.us, which shows in the UI */
346                                                 Material ***matar= give_matarar(base->object);
347                                                 int actcol= MAX2(base->object->actcol > 0, 1) - 1;
348
349                                                 if(matar && actcol < base->object->totcol)
350                                                         (*matar)[actcol]= mat;
351                                         } else if (base->object->type == OB_LAMP) {
352                                                 base->object->restrictflag &= ~OB_RESTRICT_RENDER;
353                                         }
354                                 }
355                         }
356                 }
357                 else if(id_type==ID_TE) {
358                         Tex *tex= NULL, *origtex= (Tex *)id;
359                         
360                         if(origtex) {
361                                 tex= localize_texture(origtex);
362                                 sp->texcopy= tex;
363                                 BLI_addtail(&pr_main->tex, tex);
364                         }                       
365                         sce->lay= 1<<MA_TEXTURE;
366                         
367                         for(base= sce->base.first; base; base= base->next) {
368                                 if(base->object->id.name[2]=='t') {
369                                         Material *mat= give_current_material(base->object, base->object->actcol);
370                                         if(mat && mat->mtex[0]) {
371                                                 mat->mtex[0]->tex= tex;
372                                                 
373                                                 if(tex && sp->slot)
374                                                         mat->mtex[0]->which_output = sp->slot->which_output;
375                                                 
376                                                 /* show alpha in this case */
377                                                 if(tex==NULL || (tex->flag & TEX_PRV_ALPHA)) {
378                                                         mat->mtex[0]->mapto |= MAP_ALPHA;
379                                                         mat->alpha= 0.0f;
380                                                 }
381                                                 else {
382                                                         mat->mtex[0]->mapto &= ~MAP_ALPHA;
383                                                         mat->alpha= 1.0f;
384                                                 }
385                                         }
386                                 }
387                         }
388
389                         if(tex && tex->nodetree && sp->pr_method==PR_NODE_RENDER) {
390                                 /* two previews, they get copied by wmJob */
391                                 ntreeInitPreview(origtex->nodetree, sp->sizex, sp->sizey);
392                                 ntreeInitPreview(tex->nodetree, sp->sizex, sp->sizey);
393                         }
394                 }
395                 else if(id_type==ID_LA) {
396                         Lamp *la= NULL, *origla= (Lamp *)id;
397
398                         /* work on a copy */
399                         if(origla) {
400                                 la= localize_lamp(origla);
401                                 sp->lampcopy= la;
402                                 BLI_addtail(&pr_main->lamp, la);
403                         }
404                         
405                         if(la && la->type==LA_SUN && (la->sun_effect_type & LA_SUN_EFFECT_SKY)) {
406                                 sce->lay= 1<<MA_ATMOS;
407                                 sce->world= scene->world;
408                                 sce->camera= (Object *)BLI_findstring(&pr_main->object, "CameraAtmo", offsetof(ID, name)+2);
409                         }
410                         else {
411                                 sce->lay= 1<<MA_LAMP;
412                                 sce->world= NULL;
413                                 sce->camera= (Object *)BLI_findstring(&pr_main->object, "Camera", offsetof(ID, name)+2);
414                         }
415                         sce->r.mode &= ~R_SHADOW;
416                         
417                         for(base= sce->base.first; base; base= base->next) {
418                                 if(base->object->id.name[2]=='p') {
419                                         if(base->object->type==OB_LAMP)
420                                                 base->object->data= la;
421                                 }
422                         }
423                 }
424                 else if(id_type==ID_WO) {
425                         World *wrld= NULL, *origwrld= (World *)id;
426
427                         if(origwrld) {
428                                 wrld= localize_world(origwrld);
429                                 sp->worldcopy= wrld;
430                                 BLI_addtail(&pr_main->world, wrld);
431                         }
432
433                         sce->lay= 1<<MA_SKY;
434                         sce->world= wrld;
435                 }
436                 
437                 return sce;
438         }
439         
440         return NULL;
441 }
442
443 /* new UI convention: draw is in pixel space already. */
444 /* uses ROUNDBOX button in block to get the rect */
445 static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int first, rcti *rect, rcti *newrect)
446 {
447         Render *re;
448         RenderResult rres;
449         char name[32];
450         int do_gamma_correct=0;
451         int offx=0, newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
452
453         if (id && GS(id->name) != ID_TE) {
454                 /* exception: don't color manage texture previews - show the raw values */
455                 if (sce) do_gamma_correct = sce->r.color_mgt_flag & R_COLOR_MANAGEMENT;
456         }
457
458         if(!split || first) sprintf(name, "Preview %p", (void *)sa);
459         else sprintf(name, "SecondPreview %p", (void *)sa);
460
461         if(split) {
462                 if(first) {
463                         offx= 0;
464                         newx= newx/2;
465                 }
466                 else {
467                         offx= newx/2;
468                         newx= newx - newx/2;
469                 }
470         }
471
472         re= RE_GetRender(name);
473         RE_AcquireResultImage(re, &rres);
474
475         if(rres.rectf) {
476                 
477                 if(ABS(rres.rectx-newx)<2 && ABS(rres.recty-newy)<2) {
478                         newrect->xmax= MAX2(newrect->xmax, rect->xmin + rres.rectx + offx);
479                         newrect->ymax= MAX2(newrect->ymax, rect->ymin + rres.recty);
480
481                         glaDrawPixelsSafe_to32(rect->xmin+offx, rect->ymin, rres.rectx, rres.recty, rres.rectx, rres.rectf, do_gamma_correct);
482
483                         RE_ReleaseResultImage(re);
484                         return 1;
485                 }
486         }
487
488         RE_ReleaseResultImage(re);
489         return 0;
490 }
491
492 void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, rcti *rect)
493 {
494         if(idp) {
495                 ScrArea *sa= CTX_wm_area(C);
496                 Scene *sce = CTX_data_scene(C);
497                 ID *id = (ID *)idp;
498                 ID *parent= (ID *)parentp;
499                 MTex *slot= (MTex *)slotp;
500                 SpaceButs *sbuts= sa->spacedata.first;
501                 rcti newrect;
502                 int ok;
503                 int newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
504
505                 newrect.xmin= rect->xmin;
506                 newrect.xmax= rect->xmin;
507                 newrect.ymin= rect->ymin;
508                 newrect.ymax= rect->ymin;
509
510                 if(parent) {
511                         ok = ed_preview_draw_rect(sa, sce, id, 1, 1, rect, &newrect);
512                         ok &= ed_preview_draw_rect(sa, sce, parent, 1, 0, rect, &newrect);
513                 }
514                 else
515                         ok = ed_preview_draw_rect(sa, sce, id, 0, 0, rect, &newrect);
516
517                 if(ok)
518                         *rect= newrect;
519
520                 /* check for spacetype... */
521                 if(sbuts->spacetype==SPACE_BUTS && sbuts->preview) {
522                         sbuts->preview= 0;
523                         ok= 0;
524                 }
525         
526                 if(ok==0) {
527                         ED_preview_shader_job(C, sa, id, parent, slot, newx, newy, PR_BUTS_RENDER);
528                 }
529         }       
530 }
531
532 /* **************************** new shader preview system ****************** */
533
534 /* inside thread, called by renderer, sets job update value */
535 static void shader_preview_draw(void *spv, RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect))
536 {
537         ShaderPreview *sp= spv;
538         
539         *(sp->do_update)= 1;
540 }
541
542 /* called by renderer, checks job value */
543 static int shader_preview_break(void *spv)
544 {
545         ShaderPreview *sp= spv;
546
547         return *(sp->stop);
548 }
549
550 /* outside thread, called before redraw notifiers, it moves finished preview over */
551 static void shader_preview_updatejob(void *spv)
552 {
553         ShaderPreview *sp= spv;
554         
555         if(sp->id) {
556                 if(sp->pr_method==PR_NODE_RENDER) {
557                         if( GS(sp->id->name) == ID_MA) {
558                                 Material *mat= (Material *)sp->id;
559                                 
560                                 if(sp->matcopy && mat->nodetree && sp->matcopy->nodetree)
561                                         ntreeLocalSync(sp->matcopy->nodetree, mat->nodetree);
562                         }
563                         else if( GS(sp->id->name) == ID_TE) {
564                                 Tex *tex= (Tex *)sp->id;
565                                 
566                                 if(sp->texcopy && tex->nodetree && sp->texcopy->nodetree)
567                                         ntreeLocalSync(sp->texcopy->nodetree, tex->nodetree);
568                         }
569                 }               
570         }
571 }
572
573 static void shader_preview_render(ShaderPreview *sp, ID *id, int split, int first)
574 {
575         Render *re;
576         Scene *sce;
577         float oldlens;
578         short idtype= GS(id->name);
579         char name[32];
580         int sizex;
581         
582         /* get the stuff from the builtin preview dbase */
583         sce= preview_prepare_scene(sp->scene, id, idtype, sp); // XXX sizex
584         if(sce==NULL) return;
585         
586         if(!split || first) sprintf(name, "Preview %p", sp->owner);
587         else sprintf(name, "SecondPreview %p", sp->owner);
588         re= RE_GetRender(name);
589         
590         /* full refreshed render from first tile */
591         if(re==NULL)
592                 re= RE_NewRender(name);
593                 
594         /* sce->r gets copied in RE_InitState! */
595         sce->r.scemode &= ~(R_MATNODE_PREVIEW|R_TEXNODE_PREVIEW);
596         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
597
598         if(sp->pr_method==PR_ICON_RENDER) {
599                 sce->r.scemode |= R_NO_IMAGE_LOAD;
600                 sce->r.mode |= R_OSA;
601         }
602         else if(sp->pr_method==PR_NODE_RENDER) {
603                 if(idtype == ID_MA) sce->r.scemode |= R_MATNODE_PREVIEW;
604                 else if(idtype == ID_TE) sce->r.scemode |= R_TEXNODE_PREVIEW;
605                 sce->r.mode &= ~R_OSA;
606         }
607         else {  /* PR_BUTS_RENDER */
608                 sce->r.mode |= R_OSA;
609         }
610
611         /* in case of split preview, use border render */
612         if(split) {
613                 if(first) sizex= sp->sizex/2;
614                 else sizex= sp->sizex - sp->sizex/2;
615         }
616         else sizex= sp->sizex;
617
618         /* allocates or re-uses render result */
619         sce->r.xsch= sizex;
620         sce->r.ysch= sp->sizey;
621         sce->r.size= 100;
622
623         /* callbacs are cleared on GetRender() */
624         if(ELEM(sp->pr_method, PR_BUTS_RENDER, PR_NODE_RENDER)) {
625                 RE_display_draw_cb(re, sp, shader_preview_draw);
626         }
627         /* set this for all previews, default is react to G.afbreek still */
628         RE_test_break_cb(re, sp, shader_preview_break);
629         
630         /* lens adjust */
631         oldlens= ((Camera *)sce->camera->data)->lens;
632         if(sizex > sp->sizey)
633                 ((Camera *)sce->camera->data)->lens *= (float)sp->sizey/(float)sizex;
634
635         /* entire cycle for render engine */
636         RE_PreviewRender(re, pr_main, sce);
637
638         ((Camera *)sce->camera->data)->lens= oldlens;
639
640         /* handle results */
641         if(sp->pr_method==PR_ICON_RENDER) {
642                 // char *rct= (char *)(sp->pr_rect + 32*16 + 16);
643                 
644                 if(sp->pr_rect)
645                         RE_ResultGet32(re, sp->pr_rect);
646         }
647         else {
648                 /* validate owner */
649                 //if(ri->rect==NULL)
650                 //      ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
651                 //RE_ResultGet32(re, ri->rect);
652         }
653
654         /* unassign the pointers, reset vars */
655         preview_prepare_scene(sp->scene, NULL, GS(id->name), sp);
656         
657         /* XXX bad exception, end-exec is not being called in render, because it uses local main */
658 //      if(idtype == ID_TE) {
659 //              Tex *tex= (Tex *)id;
660 //              if(tex->use_nodes && tex->nodetree)
661 //                      ntreeEndExecTree(tex->nodetree);
662 //      }
663
664 }
665
666 /* runs inside thread for material and icons */
667 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
668 {
669         ShaderPreview *sp= customdata;
670
671         sp->stop= stop;
672         sp->do_update= do_update;
673
674         if(sp->parent) {
675                 shader_preview_render(sp, sp->id, 1, 1);
676                 shader_preview_render(sp, sp->parent, 1, 0);
677         }
678         else
679                 shader_preview_render(sp, sp->id, 0, 0);
680
681         *do_update= 1;
682 }
683
684 static void shader_preview_free(void *customdata)
685 {
686         ShaderPreview *sp= customdata;
687         
688         if(sp->matcopy) {
689                 struct IDProperty *properties;
690                 int a;
691                 
692                 /* node previews */
693                 shader_preview_updatejob(sp);
694                 
695                 /* get rid of copied material */
696                 BLI_remlink(&pr_main->mat, sp->matcopy);
697                 
698                 /* free_material decrements texture, prevent this. hack alert! */
699                 for(a=0; a<MAX_MTEX; a++) {
700                         MTex *mtex= sp->matcopy->mtex[a];
701                         if(mtex && mtex->tex) mtex->tex= NULL;
702                 }
703                 
704                 free_material(sp->matcopy);
705
706                 properties= IDP_GetProperties((ID *)sp->matcopy, FALSE);
707                 if (properties) {
708                         IDP_FreeProperty(properties);
709                         MEM_freeN(properties);
710                 }
711                 MEM_freeN(sp->matcopy);
712         }
713         if(sp->texcopy) {
714                 struct IDProperty *properties;
715                 /* node previews */
716                 shader_preview_updatejob(sp);
717                 
718                 /* get rid of copied texture */
719                 BLI_remlink(&pr_main->tex, sp->texcopy);
720                 free_texture(sp->texcopy);
721                 
722                 properties= IDP_GetProperties((ID *)sp->texcopy, FALSE);
723                 if (properties) {
724                         IDP_FreeProperty(properties);
725                         MEM_freeN(properties);
726                 }
727                 MEM_freeN(sp->texcopy);
728         }
729         if(sp->worldcopy) {
730                 struct IDProperty *properties;
731                 /* node previews */
732                 shader_preview_updatejob(sp);
733                 
734                 /* get rid of copied world */
735                 BLI_remlink(&pr_main->world, sp->worldcopy);
736                 free_world(sp->worldcopy);
737                 
738                 properties= IDP_GetProperties((ID *)sp->worldcopy, FALSE);
739                 if (properties) {
740                         IDP_FreeProperty(properties);
741                         MEM_freeN(properties);
742                 }
743                 MEM_freeN(sp->worldcopy);
744         }
745         if(sp->lampcopy) {
746                 struct IDProperty *properties;
747                 /* node previews */
748                 shader_preview_updatejob(sp);
749                 
750                 /* get rid of copied lamp */
751                 BLI_remlink(&pr_main->lamp, sp->lampcopy);
752                 free_lamp(sp->lampcopy);
753                 
754                 properties= IDP_GetProperties((ID *)sp->lampcopy, FALSE);
755                 if (properties) {
756                         IDP_FreeProperty(properties);
757                         MEM_freeN(properties);
758                 }
759                 MEM_freeN(sp->lampcopy);
760         }
761         
762         MEM_freeN(sp);
763 }
764
765 /* ************************* icon preview ********************** */
766
767 static void icon_copy_rect(ImBuf *ibuf, unsigned int w, unsigned int h, unsigned int *rect)
768 {
769         struct ImBuf *ima;
770         unsigned int *drect, *srect;
771         float scaledx, scaledy;
772         short ex, ey, dx, dy;
773
774         /* paranoia test */
775         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL))
776                 return;
777         
778         /* waste of cpu cyles... but the imbuf API has no other way to scale fast (ton) */
779         ima = IMB_dupImBuf(ibuf);
780         
781         if (!ima) 
782                 return;
783         
784         if (ima->x > ima->y) {
785                 scaledx = (float)w;
786                 scaledy =  ( (float)ima->y/(float)ima->x )*(float)w;
787         }
788         else {                  
789                 scaledx =  ( (float)ima->x/(float)ima->y )*(float)h;
790                 scaledy = (float)h;
791         }
792         
793         ex = (short)scaledx;
794         ey = (short)scaledy;
795         
796         dx = (w - ex) / 2;
797         dy = (h - ey) / 2;
798         
799         IMB_scalefastImBuf(ima, ex, ey);
800         
801         /* if needed, convert to 32 bits */
802         if(ima->rect==NULL)
803                 IMB_rect_from_float(ima);
804
805         srect = ima->rect;
806         drect = rect;
807
808         drect+= dy*w+dx;
809         for (;ey > 0; ey--){            
810                 memcpy(drect,srect, ex * sizeof(int));
811                 drect += w;
812                 srect += ima->x;
813         }
814
815         IMB_freeImBuf(ima);
816 }
817
818 static void set_alpha(char *cp, int sizex, int sizey, char alpha) 
819 {
820         int a, size= sizex*sizey;
821
822         for(a=0; a<size; a++, cp+=4)
823                 cp[3]= alpha;
824 }
825
826 static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
827 {
828         ShaderPreview *sp= customdata;
829         ID *id= sp->id;
830         short idtype= GS(id->name);
831
832         if(idtype == ID_IM) {
833                 Image *ima= (Image*)id;
834                 ImBuf *ibuf= NULL;
835                 ImageUser iuser= {NULL};
836
837                 /* ima->ok is zero when Image cannot load */
838                 if(ima==NULL || ima->ok==0)
839                         return;
840
841                 /* setup dummy image user */
842                 iuser.ok= iuser.framenr= 1;
843                 iuser.scene= sp->scene;
844                 
845                 /* elubie: this needs to be changed: here image is always loaded if not
846                    already there. Very expensive for large images. Need to find a way to 
847                    only get existing ibuf */
848                 ibuf = BKE_image_get_ibuf(ima, &iuser);
849                 if(ibuf==NULL || ibuf->rect==NULL)
850                         return;
851                 
852                 icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);
853
854                 *do_update= 1;
855         }
856         else if(idtype == ID_BR) {
857                 Brush *br= (Brush*)id;
858
859                 br->icon_imbuf= get_brush_icon(br);
860
861                 memset(sp->pr_rect, 0x888888, sp->sizex*sp->sizey*sizeof(unsigned int));
862
863                 if(!(br->icon_imbuf) || !(br->icon_imbuf->rect))
864                         return;
865
866                 icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);
867
868                 *do_update= 1;
869         }
870         else {
871                 /* re-use shader job */
872                 shader_preview_startjob(customdata, stop, do_update);
873
874                 /* world is rendered with alpha=0, so it wasn't displayed 
875                    this could be render option for sky to, for later */
876                 if(idtype == ID_WO) {
877                         set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
878                 }
879                 else if(idtype == ID_MA) {
880                         Material* ma = (Material*)id;
881
882                         if(ma->material_type == MA_TYPE_HALO)
883                                 set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
884                 }
885         }
886 }
887
888 /* use same function for icon & shader, so the job manager
889    does not run two of them at the same time. */
890
891 static void common_preview_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
892 {
893         ShaderPreview *sp= customdata;
894
895         if(sp->pr_method == PR_ICON_RENDER)
896                 icon_preview_startjob(customdata, stop, do_update);
897         else
898                 shader_preview_startjob(customdata, stop, do_update);
899 }
900
901 static void common_preview_endjob(void *customdata)
902 {
903         ShaderPreview *sp= customdata;
904
905         if(sp->id && GS(sp->id->name) == ID_BR)
906                 WM_main_add_notifier(NC_BRUSH|NA_EDITED, sp->id);
907 }
908
909 /* exported functions */
910
911 void ED_preview_icon_job(const bContext *C, void *owner, ID *id, unsigned int *rect, int sizex, int sizey)
912 {
913         wmJob *steve;
914         ShaderPreview *sp;
915         
916         /* suspended start means it starts after 1 timer step, see WM_jobs_timer below */
917         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Icon Preview", WM_JOB_EXCL_RENDER|WM_JOB_SUSPEND);
918         sp= MEM_callocN(sizeof(ShaderPreview), "shader preview");
919
920         /* customdata for preview thread */
921         sp->scene= CTX_data_scene(C);
922         sp->owner= id;
923         sp->sizex= sizex;
924         sp->sizey= sizey;
925         sp->pr_method= PR_ICON_RENDER;
926         sp->pr_rect= rect;
927         sp->id = id;
928
929         /* setup job */
930         WM_jobs_customdata(steve, sp, shader_preview_free);
931         WM_jobs_timer(steve, 0.25, NC_MATERIAL, NC_MATERIAL);
932         WM_jobs_callbacks(steve, common_preview_startjob, NULL, NULL, common_preview_endjob);
933
934         WM_jobs_start(CTX_wm_manager(C), steve);
935 }
936
937 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, MTex *slot, int sizex, int sizey, int method)
938 {
939         Object *ob= CTX_data_active_object(C);
940         wmJob *steve;
941         ShaderPreview *sp;
942
943         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Shader Preview", WM_JOB_EXCL_RENDER);
944         sp= MEM_callocN(sizeof(ShaderPreview), "shader preview");
945
946         /* customdata for preview thread */
947         sp->scene= CTX_data_scene(C);
948         sp->owner= owner;
949         sp->sizex= sizex;
950         sp->sizey= sizey;
951         sp->pr_method= method;
952         sp->id = id;
953         sp->parent= parent;
954         sp->slot= slot;
955         if(ob && ob->totcol) copy_v4_v4(sp->col, ob->col);
956         else sp->col[0]= sp->col[1]= sp->col[2]= sp->col[3]= 1.0f;
957         
958         /* setup job */
959         WM_jobs_customdata(steve, sp, shader_preview_free);
960         WM_jobs_timer(steve, 0.1, NC_MATERIAL, NC_MATERIAL);
961         WM_jobs_callbacks(steve, common_preview_startjob, NULL, shader_preview_updatejob, NULL);
962         
963         WM_jobs_start(CTX_wm_manager(C), steve);
964 }
965
966 void ED_preview_kill_jobs(const struct bContext *C)
967 {
968         wmWindowManager *wm= CTX_wm_manager(C);
969         if(wm)
970                 WM_jobs_kill(wm, NULL, common_preview_startjob);
971 }
972