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