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