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