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