Fixed the texture preview to work with multi-output node-based textures.
[blender.git] / source / blender / editors / preview / previewrender.c
1 /* 
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /* global includes */
31
32 #include <stdlib.h>
33 #include <math.h>
34 #include <string.h>
35
36 #ifndef WIN32
37 #include <unistd.h>
38 #else
39 #include <io.h>
40 #endif   
41 #include "MEM_guardedalloc.h"
42
43 #include "BLO_readfile.h" 
44
45 #include "BLI_arithb.h"
46 #include "BLI_blenlib.h"
47 #include "BLI_threads.h"
48
49 #include "DNA_texture_types.h"
50 #include "DNA_world_types.h"
51 #include "DNA_camera_types.h"
52 #include "DNA_image_types.h"
53 #include "DNA_material_types.h"
54 #include "DNA_node_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_lamp_types.h"
57 #include "DNA_space_types.h"
58 #include "DNA_view3d_types.h"
59 #include "DNA_scene_types.h"
60 #include "DNA_screen_types.h"
61
62 #include "BKE_context.h"
63 #include "BKE_depsgraph.h"
64 #include "BKE_global.h"
65 #include "BKE_image.h"
66 #include "BKE_icons.h"
67 #include "BKE_library.h"
68 #include "BKE_main.h"
69 #include "BKE_texture.h"
70 #include "BKE_material.h"
71 #include "BKE_node.h"
72 #include "BKE_world.h"
73 #include "BKE_texture.h"
74 #include "BKE_utildefines.h"
75
76 #include "IMB_imbuf.h"
77 #include "IMB_imbuf_types.h"
78
79 #include "BIF_gl.h"
80 #include "BIF_glutil.h"
81
82 #include "PIL_time.h"
83
84 #include "RE_pipeline.h"
85
86 #include "GPU_material.h"
87
88 #include "WM_api.h"
89 #include "WM_types.h"
90
91 #include "ED_anim_api.h"
92 #include "ED_previewrender.h"
93 #include "ED_view3d.h"
94
95 #include "UI_interface.h"
96
97 #include "previewrender_intern.h"
98
99 #define PR_XMIN         10
100 #define PR_YMIN         5
101 #define PR_XMAX         200
102 #define PR_YMAX         195
103
104 /* XXX */
105 static int qtest() {return 0;}
106 /* XXX */
107
108 typedef struct ShaderPreview {
109         /* from wmJob */
110         void *owner;
111         short *stop, *do_update;
112         
113         Scene *scene;
114         ID *id;
115         ID *parent;
116         MTex *slot;
117         
118         int sizex, sizey;
119         int *pr_rect;
120         int pr_method;
121         
122 } ShaderPreview;
123
124
125
126 /* unused now */
127 void draw_tex_crop(Tex *tex)
128 {
129         rcti rct;
130         int ret= 0;
131         
132         if(tex==0) return;
133         
134         if(tex->type==TEX_IMAGE) {
135                 if(tex->cropxmin==0.0f) ret++;
136                 if(tex->cropymin==0.0f) ret++;
137                 if(tex->cropxmax==1.0f) ret++;
138                 if(tex->cropymax==1.0f) ret++;
139                 if(ret==4) return;
140                 
141                 rct.xmin= PR_XMIN+2+tex->cropxmin*(PR_XMAX-PR_XMIN-4);
142                 rct.xmax= PR_XMIN+2+tex->cropxmax*(PR_XMAX-PR_XMIN-4);
143                 rct.ymin= PR_YMIN+2+tex->cropymin*(PR_YMAX-PR_YMIN-4);
144                 rct.ymax= PR_YMIN+2+tex->cropymax*(PR_YMAX-PR_YMIN-4);
145
146                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
147
148                 glColor3ub(0, 0, 0);
149                 glRecti(rct.xmin+1,  rct.ymin-1,  rct.xmax+1,  rct.ymax-1); 
150
151                 glColor3ub(255, 255, 255);
152                 glRecti(rct.xmin,  rct.ymin,  rct.xmax,  rct.ymax);
153
154                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);                      
155         }
156         
157 }
158
159 /* temporal abuse; if id_code is -1 it only does texture.... solve! */
160 void BIF_preview_changed(short id_code)
161 {
162 #if 0   
163         ScrArea *sa;
164         
165         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
166                 if(sa->spacetype==SPACE_BUTS) {
167                         SpaceButs *sbuts= sa->spacedata.first;
168                         if(sbuts->mainb==CONTEXT_SHADING) {
169                                 int tab= sbuts->tab[CONTEXT_SHADING];
170                                 if(tab==TAB_SHADING_MAT && (id_code==ID_MA || id_code==ID_TE)) {
171                                         if (sbuts->ri) sbuts->ri->curtile= 0;
172                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
173                                 }
174                                 else if(tab==TAB_SHADING_TEX && (id_code==ID_TE || id_code==-1)) {
175                                         if (sbuts->ri) sbuts->ri->curtile= 0;
176                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
177                                 }
178                                 else if(tab==TAB_SHADING_LAMP && (id_code==ID_LA || id_code==ID_TE)) {
179                                         if (sbuts->ri) sbuts->ri->curtile= 0;
180                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
181                                 }
182                                 else if(tab==TAB_SHADING_WORLD && (id_code==ID_WO || id_code==ID_TE)) {
183                                         if (sbuts->ri) sbuts->ri->curtile= 0;
184                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
185                                 }
186                         }
187                         else if (sbuts->ri) 
188                                 sbuts->ri->curtile= 0;  /* ensure changes always result in re-render when context is restored */
189                 }
190                 else if(sa->spacetype==SPACE_NODE) {
191                         SpaceNode *snode= sa->spacedata.first;
192                         if(snode->treetype==NTREE_SHADER && (id_code==ID_MA || id_code==ID_TE)) {
193                                 snode_tag_dirty(snode);
194                         }
195                 }
196                 else if(sa->spacetype==SPACE_VIEW3D) {
197                         View3D *vd= sa->spacedata.first;
198                         /* if is has a renderinfo, we consider that reason for signalling */
199                         if (vd->ri) {
200                                 vd->ri->curtile= 0;
201                                 addafterqueue(sa->win, RENDERPREVIEW, 1);
202                         }
203                 }
204         }
205
206         if(ELEM4(id_code, ID_MA, ID_TE, ID_LA, ID_WO)) {
207                 Object *ob;
208                 Material *ma;
209
210                 if(id_code == ID_WO) {
211                         for(ma=G.main->mat.first; ma; ma=ma->id.next) {
212                                 if(ma->gpumaterial.first) {
213                                         GPU_material_free(ma);
214                                 }
215                         }
216                 }
217                 else if(id_code == ID_LA) {
218                         for(ob=G.main->object.first; ob; ob=ob->id.next) {
219                                 if(ob->gpulamp.first) {
220                                         GPU_lamp_free(ob);
221                                 }
222                         }
223
224                         for(ma=G.main->mat.first; ma; ma=ma->id.next) {
225                                 if(ma->gpumaterial.first) {
226                                         GPU_material_free(ma);
227                                 }
228                         }
229                 } else if(OBACT) {
230                         Object *ob = OBACT;
231
232                         ma= give_current_material(ob, ob->actcol);
233                         if(ma && ma->gpumaterial.first) {
234                                 GPU_material_free(ma);
235                         }
236                 }
237         }
238 #endif
239 }
240
241 /* *************************** Preview for buttons *********************** */
242
243 static Main *pr_main= NULL;
244
245 void ED_preview_init_dbase(void)
246 {
247         BlendFileData *bfd;
248         extern int datatoc_preview_blend_size;
249         extern char datatoc_preview_blend[];
250         
251         G.fileflags |= G_FILE_NO_UI;
252         bfd= BLO_read_from_memory(datatoc_preview_blend, datatoc_preview_blend_size, NULL);
253         if (bfd) {
254                 pr_main= bfd->main;
255                 
256                 MEM_freeN(bfd);
257         }
258         G.fileflags &= ~G_FILE_NO_UI;
259 }
260
261 void ED_preview_free_dbase(void)
262 {
263         if(pr_main)
264                 free_main(pr_main);
265 }
266
267 static Object *find_object(ListBase *lb, const char *name)
268 {
269         Object *ob;
270         for(ob= lb->first; ob; ob= ob->id.next)
271                 if(strcmp(ob->id.name+2, name)==0)
272                         break;
273         return ob;
274 }
275
276 /* call this with a pointer to initialize preview scene */
277 /* call this with NULL to restore assigned ID pointers in preview scene */
278 static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPreview *sp)
279 {
280         Scene *sce;
281         Base *base;
282         
283         if(pr_main==NULL) return NULL;
284         
285         sce= pr_main->scene.first;
286         if(sce) {
287                 /* this flag tells render to not execute depsgraph or ipos etc */
288                 sce->r.scemode |= R_PREVIEWBUTS;
289                 /* set world always back, is used now */
290                 sce->world= pr_main->world.first;
291                 /* now: exposure copy */
292                 if(scene->world) {
293                         sce->world->exp= scene->world->exp;
294                         sce->world->range= scene->world->range;
295                 }
296                 
297                 sce->r.color_mgt_flag = scene->r.color_mgt_flag;
298                 sce->r.cfra= scene->r.cfra;
299                 
300                 if(id_type==ID_MA) {
301                         Material *mat= (Material *)id;
302                         
303                         if(id) {
304                                 init_render_material(mat, 0, NULL);             /* call that retrieves mode_l */
305                                 end_render_material(mat);
306                                 
307                                 /* turn on raytracing if needed */
308                                 if(mat->mode_l & MA_RAYMIRROR)
309                                         sce->r.mode |= R_RAYTRACE;
310                                 if((mat->mode_l & MA_RAYTRANSP) && (mat->mode_l & MA_TRANSP))
311                                         sce->r.mode |= R_RAYTRACE;
312                                 if(mat->sss_flag & MA_DIFF_SSS)
313                                         sce->r.mode |= R_SSS;
314                                 
315                                 /* turn off fake shadows if needed */
316                                 /* this only works in a specific case where the preview.blend contains
317                                  * an object starting with 'c' which has a material linked to it (not the obdata)
318                                  * and that material has a fake shadow texture in the active texture slot */
319                                 for(base= sce->base.first; base; base= base->next) {
320                                         if(base->object->id.name[2]=='c') {
321                                                 Material *shadmat= give_current_material(base->object, base->object->actcol);
322                                                 if(shadmat) {
323                                                         if (mat->mode & MA_SHADBUF) shadmat->septex = 0;
324                                                         else shadmat->septex |= 1;
325                                                 }
326                                         }
327                                 }
328
329                                 
330                                 if(sp->pr_method==PR_ICON_RENDER) {
331                                         if (mat->material_type == MA_TYPE_HALO) {
332                                                 sce->lay= 1<<MA_FLAT;
333                                         } 
334                                         else {
335                                                 sce->lay= 1<<MA_SPHERE_A;
336                                         }
337                                 }
338                                 else {
339                                         sce->lay= 1<<mat->pr_type;
340                                         if(mat->nodetree)
341                                                 ntreeInitPreview(mat->nodetree, sp->sizex, sp->sizey);
342                                 }
343                         }
344                         else {
345                                 sce->r.mode &= ~(R_OSA|R_RAYTRACE|R_SSS);
346                         }
347                         
348                         for(base= sce->base.first; base; base= base->next) {
349                                 if(base->object->id.name[2]=='p') {
350                                         if(ELEM4(base->object->type, OB_MESH, OB_CURVE, OB_SURF, OB_MBALL))
351                                                 assign_material(base->object, mat, base->object->actcol);
352                                 }
353                         }
354                 }
355                 else if(id_type==ID_TE) {
356                         Tex *tex= (Tex *)id;
357                         
358                         sce->lay= 1<<MA_TEXTURE;
359                         
360                         /* exception: don't color manage texture previews */
361                         sce->r.color_mgt_flag &= ~R_COLOR_MANAGEMENT;
362                         
363                         for(base= sce->base.first; base; base= base->next) {
364                                 if(base->object->id.name[2]=='t') {
365                                         Material *mat= give_current_material(base->object, base->object->actcol);
366                                         if(mat && mat->mtex[0]) {
367                                                 mat->mtex[0]->tex= tex;
368                                                 
369                                                 if(sp && sp->slot)
370                                                         mat->mtex[0]->which_output = sp->slot->which_output;
371                                                 
372                                                 /* show alpha in this case */
373                                                 if(tex==NULL || (tex->flag & TEX_PRV_ALPHA)) {
374                                                         mat->mtex[0]->mapto |= MAP_ALPHA;
375                                                         mat->alpha= 0.0f;
376                                                 }
377                                                 else {
378                                                         mat->mtex[0]->mapto &= ~MAP_ALPHA;
379                                                         mat->alpha= 1.0f;
380                                                 }
381                                         }
382                                 }
383                         }
384                 }
385                 else if(id_type==ID_LA) {
386                         Lamp *la= (Lamp *)id;
387                         
388                         if(la && la->type==LA_SUN && (la->sun_effect_type & LA_SUN_EFFECT_SKY)) {
389                                 sce->lay= 1<<MA_ATMOS;
390                                 sce->world= scene->world;
391                                 sce->camera= (Object *)find_object(&pr_main->object, "CameraAtmo");
392                         }
393                         else {
394                                 sce->lay= 1<<MA_LAMP;
395                                 sce->world= NULL;
396                                 sce->camera= (Object *)find_object(&pr_main->object, "Camera");
397                         }
398                         sce->r.mode &= ~R_SHADOW;
399                         
400                         for(base= sce->base.first; base; base= base->next) {
401                                 if(base->object->id.name[2]=='p') {
402                                         if(base->object->type==OB_LAMP)
403                                                 base->object->data= la;
404                                 }
405                         }
406                 }
407                 else if(id_type==ID_WO) {
408                         sce->lay= 1<<MA_SKY;
409                         sce->world= (World *)id;
410                 }
411                 
412                 return sce;
413         }
414         
415         return NULL;
416 }
417
418 /* new UI convention: draw is in pixel space already. */
419 /* uses ROUNDBOX button in block to get the rect */
420 static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int first, rcti *rect, rcti *newrect)
421 {
422         RenderResult rres;
423         char name[32];
424         int gamma_correct=0;
425         int offx=0, newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
426
427         if (id && GS(id->name) != ID_TE) {
428                 /* exception: don't color manage texture previews - show the raw values */
429                 if (sce) gamma_correct = sce->r.color_mgt_flag & R_COLOR_MANAGEMENT;
430         }
431
432         if(!split || first) sprintf(name, "Preview %p", sa);
433         else sprintf(name, "SecondPreview %p", sa);
434
435         if(split) {
436                 if(first) {
437                         offx= 0;
438                         newx= newx/2;
439                 }
440                 else {
441                         offx= newx/2;
442                         newx= newx - newx/2;
443                 }
444         }
445
446         RE_GetResultImage(RE_GetRender(name), &rres);
447
448         if(rres.rectf) {
449                 
450                 if(ABS(rres.rectx-newx)<2 && ABS(rres.recty-newy)<2) {
451                         newrect->xmax= MAX2(newrect->xmax, rect->xmin + rres.rectx + offx);
452                         newrect->ymax= MAX2(newrect->ymax, rect->ymin + rres.recty);
453
454                         glPushMatrix();
455                         glTranslatef(offx, 0, 0);
456                         glaDrawPixelsSafe_to32(rect->xmin, rect->ymin, rres.rectx, rres.recty, rres.rectx, rres.rectf, gamma_correct);
457                         glPopMatrix();
458                         return 1;
459                 }
460         }
461
462         return 0;
463 }
464
465 void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, rcti *rect)
466 {
467         if(idp) {
468                 ScrArea *sa= CTX_wm_area(C);
469                 Scene *sce = CTX_data_scene(C);
470                 ID *id = (ID *)idp;
471                 ID *parent= (ID *)parentp;
472                 MTex *slot= (MTex *)slotp;
473                 SpaceButs *sbuts= sa->spacedata.first;
474                 rcti newrect;
475                 int ok;
476                 int newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
477
478                 newrect.xmin= rect->xmin;
479                 newrect.xmax= rect->xmin;
480                 newrect.ymin= rect->ymin;
481                 newrect.ymax= rect->ymin;
482
483                 if(parent) {
484                         ok = ed_preview_draw_rect(sa, sce, parent, 1, 1, rect, &newrect);
485                         ok &= ed_preview_draw_rect(sa, sce, id, 1, 0, rect, &newrect);
486                 }
487                 else
488                         ok = ed_preview_draw_rect(sa, sce, id, 0, 0, rect, &newrect);
489
490                 if(ok)
491                         *rect= newrect;
492
493                 /* check for spacetype... */
494                 if(sbuts->spacetype==SPACE_BUTS && sbuts->preview) {
495                         sbuts->preview= 0;
496                         ok= 0;
497                 }
498                 
499                 if(ok==0) {
500                         ED_preview_shader_job(C, sa, id, parent, slot, newx, newy);
501                 }
502         }       
503 }
504
505 /* *************************** Preview for 3d window *********************** */
506
507 void view3d_previewrender_progress(RenderResult *rr, volatile rcti *renrect)
508 {
509 //      ScrArea *sa= NULL; // XXX
510 //      View3D *v3d= NULL; // XXX
511         RenderLayer *rl;
512         int ofsx=0, ofsy=0;
513         
514         if(renrect) return;
515         
516         rl= rr->layers.first;
517         
518         /* this case is when we render envmaps... */
519 //      if(rr->rectx > v3d->ri->pr_rectx || rr->recty > v3d->ri->pr_recty)
520 //              return;
521         
522 //      ofsx= v3d->ri->disprect.xmin + rr->tilerect.xmin;
523 //      ofsy= v3d->ri->disprect.ymin + rr->tilerect.ymin;
524         
525         glDrawBuffer(GL_FRONT);
526 //      glaDefine2DArea(&sa->winrct);
527         glaDrawPixelsSafe_to32(ofsx, ofsy, rr->rectx, rr->recty, rr->rectx, rl->rectf, 0);
528         bglFlush();
529         glDrawBuffer(GL_BACK);
530
531 }
532
533 void BIF_view3d_previewrender_signal(ScrArea *sa, short signal)
534 {
535 #if 0
536         View3D *v3d= sa->spacedata.first;
537         
538         /* this can be called from other window... solve! */
539         if(sa->spacetype!=SPACE_VIEW3D)
540                 return; // XXX
541            
542         if(v3d && v3d->ri) {
543                 RenderInfo *ri= v3d->ri;
544                 ri->status &= ~signal;
545                 ri->curtile= 0;
546                 //printf("preview signal %d\n", signal);
547                 if(ri->re && (signal & PR_DBASE))
548                         RE_Database_Free(ri->re);
549
550 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
551         }
552 #endif
553 }
554
555 void BIF_view3d_previewrender_free(View3D *v3d)
556 {
557 #if 0
558         if(v3d->ri) {
559                 RenderInfo *ri= v3d->ri;
560                 if(ri->re) {
561 //                      printf("free render\n");
562                         RE_Database_Free(ri->re);
563                         RE_FreeRender(ri->re);
564                         ri->re= NULL;
565                 }
566                 if (v3d->ri->rect) MEM_freeN(v3d->ri->rect);
567                 MEM_freeN(v3d->ri);
568                 v3d->ri= NULL;
569         }
570 #endif
571 }
572
573 /* returns 1 if OK, do not call while in panel space!  */
574 static int view3d_previewrender_get_rects(ScrArea *sa, rctf *viewplane, RenderInfo *ri, float *clipsta, float *clipend, int *ortho, float *pixsize)
575 {
576         View3D *v3d= NULL; // XXX
577         RegionView3D *rv3d= NULL; // XXX
578         int rectx, recty;
579 //      uiBlock *block;
580         
581 //      block= uiFindOpenPanelBlockName(&sa->uiblocks, "Preview");
582 //      if(block==NULL) return 0;
583         
584         /* calculate preview rect size */
585 //      BLI_init_rctf(viewplane, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
586 //      uiPanelPush(block);
587 //      ui_graphics_to_window_rct(sa->win, viewplane, &ri->disprect);
588 //      uiPanelPop(block);
589         
590         /* correction for gla draw */
591 //      BLI_translate_rcti(&ri->disprect, -sa->winrct.xmin, -sa->winrct.ymin);
592         
593         *ortho= get_view3d_viewplane(v3d, rv3d, sa->winx, sa->winy, viewplane, clipsta, clipend, pixsize);
594
595         rectx= ri->disprect.xmax - ri->disprect.xmin;
596         recty= ri->disprect.ymax - ri->disprect.ymin;
597         
598         if(rectx<4 || recty<4) return 0;
599         
600         if(ri->rect && (rectx!=ri->pr_rectx || recty!=ri->pr_recty)) {
601                 MEM_freeN(ri->rect);
602                 ri->rect= NULL;
603                 ri->curtile= 0;
604                 printf("changed size\n");
605         }
606         ri->pr_rectx= rectx;
607         ri->pr_recty= recty;
608         
609         return 1;
610 }
611
612 /* called before a panel gets moved/scaled, makes sure we can see through */
613 void BIF_view3d_previewrender_clear(ScrArea *sa)
614 {
615 #if 0
616         View3D *v3d= sa->spacedata.first;
617
618         if(v3d->ri) {
619                 RenderInfo *ri= v3d->ri;
620                 ri->curtile= 0;
621                 if(ri->rect)
622                         MEM_freeN(ri->rect);
623                 ri->rect= NULL;
624         }
625 #endif
626 }
627
628 /* afterqueue call */
629 void BIF_view3d_previewrender(Scene *scene, ScrArea *sa)
630 {
631         bContext *C= NULL;
632         View3D *v3d= sa->spacedata.first;
633         RegionView3D *rv3d= NULL; // XXX
634         Render *re;
635         RenderInfo *ri=NULL;    /* preview struct! */
636         RenderStats *rstats;
637         RenderData rdata;
638         rctf viewplane;
639         float clipsta, clipend, pixsize;
640         int orth;
641         
642         /* first get the render info right */
643 //      if (!v3d->ri) {
644 //              ri= v3d->ri= MEM_callocN(sizeof(RenderInfo), "butsrenderinfo");
645 //              ri->tottile= 10000;
646 //      }
647 //      ri= v3d->ri;
648         
649         if(0==view3d_previewrender_get_rects(sa, &viewplane, ri, &clipsta, &clipend, &orth, &pixsize))
650                 return;
651         
652         /* render is finished, so return */
653         if(ri->tottile && ri->curtile>=ri->tottile) return;
654
655         /* or return with a new event */
656         if(qtest()) {
657 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
658                 return;
659         }
660         //printf("Enter previewrender\n");
661         /* ok, are we rendering all over? */
662         if(ri->re==NULL) {
663                 char name[32];
664                 
665                 ri->status= 0;
666                 
667                 sprintf(name, "View3dPreview %p", sa);
668                 re= ri->re= RE_NewRender(name);
669                 //RE_display_draw_cb(re, view3d_previewrender_progress);
670                 //RE_stats_draw_cb(re, view3d_previewrender_stats);
671                 //RE_test_break_cb(re, qtest);
672                 
673                 /* no osa, blur, seq, layers, etc for preview render */
674                 rdata= scene->r;
675                 rdata.mode &= ~(R_OSA|R_MBLUR);
676                 rdata.scemode &= ~(R_DOSEQ|R_DOCOMP|R_FREE_IMAGE);
677                 rdata.layers.first= rdata.layers.last= NULL;
678                 rdata.renderer= R_INTERN;
679                  
680                 RE_InitState(re, NULL, &rdata, sa->winx, sa->winy, &ri->disprect);
681         
682                 if(orth)
683                         RE_SetOrtho(re, &viewplane, clipsta, clipend);
684                 else
685                         RE_SetWindow(re, &viewplane, clipsta, clipend);
686                 RE_SetPixelSize(re, pixsize);
687                 
688                 /* until here are no escapes */
689                 ri->status |= PR_DISPRECT;
690                 ri->curtile= 0;
691                 //printf("new render\n");
692         }
693
694         re= ri->re;
695         
696         PIL_sleep_ms(100);      /* wait 0.1 second if theres really no event... */
697         if(qtest()==0)  {
698                 
699                 /* check status */
700                 if((ri->status & PR_DISPRECT)==0) {
701                         RE_SetDispRect(ri->re, &ri->disprect);
702                         if(orth)
703                                 RE_SetOrtho(ri->re, &viewplane, clipsta, clipend);
704                         else
705                                 RE_SetWindow(ri->re, &viewplane, clipsta, clipend);
706                         RE_SetPixelSize(re, pixsize);
707                         ri->status |= PR_DISPRECT;
708                         ri->curtile= 0;
709                         //printf("disprect update\n");
710                 }
711                 if((ri->status & PR_DBASE)==0) {
712                         unsigned int lay= scene->lay;
713                         
714                         RE_SetView(re, rv3d->viewmat);
715                         
716                         /* allow localview render for objects with lights in normal layers */
717                         if(v3d->lay & 0xFF000000)
718                                 scene->lay |= v3d->lay;
719                         else scene->lay= v3d->lay;
720                         
721                         RE_Database_FromScene(re, scene, 0);            // 0= dont use camera view
722                         scene->lay= lay;
723                         
724                         rstats= RE_GetStats(re);
725                         if(rstats->convertdone) 
726                                 ri->status |= PR_DBASE|PR_PROJECTED|PR_ROTATED;
727                         ri->curtile= 0;
728                         
729                         /* database can have created render-resol data... */
730                         if(rstats->convertdone) 
731                                 ED_anim_dag_flush_update(C); // <--- only current scene XXX
732                         
733                         //printf("dbase update\n");
734                 }
735                 if((ri->status & PR_PROJECTED)==0) {
736                         if(ri->status & PR_DBASE) {
737                                 if(orth)
738                                         RE_SetOrtho(ri->re, &viewplane, clipsta, clipend);
739                                 else
740                                         RE_SetWindow(ri->re, &viewplane, clipsta, clipend);
741                                 RE_DataBase_ApplyWindow(re);
742                                 ri->status |= PR_PROJECTED;
743                         }
744                         ri->curtile= 0;
745                         //printf("project update\n");
746                 }
747         
748                 /* OK, can we enter render code? */
749                 if(ri->status==(PR_DISPRECT|PR_DBASE|PR_PROJECTED|PR_ROTATED)) {
750                         //printf("curtile %d tottile %d\n", ri->curtile, ri->tottile);
751                         RE_TileProcessor(ri->re, ri->curtile, 0);
752         
753                         if(ri->rect==NULL)
754                                 ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "preview view3d rect");
755                         
756                         RE_ResultGet32(ri->re, ri->rect);
757                 }
758                 
759                 rstats= RE_GetStats(ri->re);
760 //              if(rstats->totpart==rstats->partsdone && rstats->partsdone)
761 //                      addqueue(sa->win, REDRAW, 1);
762 //              else
763 //                      addafterqueue(sa->win, RENDERPREVIEW, 1);
764                 
765                 ri->curtile= rstats->partsdone;
766                 ri->tottile= rstats->totpart;
767         }
768         else {
769 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
770         }
771         
772         //printf("\n");
773 }
774
775 /* in panel space! */
776 static void view3d_previewdraw_rect(ScrArea *sa, uiBlock *block, RenderInfo *ri)
777 {
778 //      rctf dispf;
779         
780         if(ri->rect==NULL)
781                 return;
782         
783 //      BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
784 //      ui_graphics_to_window_rct(sa->win, &dispf, &ri->disprect);
785
786         /* correction for gla draw */
787 //      BLI_translate_rcti(&ri->disprect, -sa->winrct.xmin, -sa->winrct.ymin);
788         
789         /* when panel scale changed, free rect */
790         if(ri->disprect.xmax-ri->disprect.xmin != ri->pr_rectx ||
791            ri->disprect.ymax-ri->disprect.ymin != ri->pr_recty) {
792                 MEM_freeN(ri->rect);
793                 ri->rect= NULL;
794         }
795         else {
796 //              glaDefine2DArea(&sa->winrct);
797                 glaDrawPixelsSafe(ri->disprect.xmin, ri->disprect.ymin, ri->pr_rectx, ri->pr_recty, ri->pr_rectx, GL_RGBA, GL_UNSIGNED_BYTE, ri->rect);
798         }       
799 }
800
801 /* is panel callback, supposed to be called with correct panel offset matrix */
802 void BIF_view3d_previewdraw(struct ScrArea *sa, struct uiBlock *block)
803 {
804         RegionView3D *rv3d= NULL;
805
806 //      if (v3d->ri==NULL || v3d->ri->rect==NULL) 
807 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
808 //      else {
809                 view3d_previewdraw_rect(sa, block, rv3d->ri);
810 //              if(v3d->ri->curtile==0) 
811 //                      addafterqueue(sa->win, RENDERPREVIEW, 1);
812 //      }
813 }
814
815
816 /* **************************** New preview system ****************** */
817
818 /* inside thread, called by renderer, sets job update value */
819 static void shader_preview_draw(void *spv, RenderResult *rr, volatile struct rcti *rect)
820 {
821         ShaderPreview *sp= spv;
822         
823         *(sp->do_update)= 1;
824 }
825
826 /* called by renderer, checks job value */
827 static int shader_preview_break(void *spv)
828 {
829         ShaderPreview *sp= spv;
830         
831         return *(sp->stop);
832 }
833
834 /* outside thread, called before redraw notifiers, it moves finished preview over */
835 static void shader_preview_updatejob(void *spv)
836 {
837 //      ShaderPreview *sp= spv;
838         
839 }
840
841 static void shader_preview_render(ShaderPreview *sp, ID *id, int split, int first)
842 {
843         Render *re;
844         Scene *sce;
845         float oldlens;
846         char name[32];
847         int sizex;
848
849         /* get the stuff from the builtin preview dbase */
850         sce= preview_prepare_scene(sp->scene, id, GS(id->name), sp); // XXX sizex
851         if(sce==NULL) return;
852         
853         if(!split || first) sprintf(name, "Preview %p", sp->owner);
854         else sprintf(name, "SecondPreview %p", sp->owner);
855         re= RE_GetRender(name);
856         
857         /* full refreshed render from first tile */
858         if(re==NULL)
859                 re= RE_NewRender(name);
860                 
861         /* sce->r gets copied in RE_InitState! */
862         if(sp->pr_method==PR_DO_RENDER) {
863                 sce->r.scemode |= R_NODE_PREVIEW;
864                 sce->r.scemode &= ~R_NO_IMAGE_LOAD;
865                 sce->r.mode |= R_OSA;
866         }
867         else {  /* PR_ICON_RENDER */
868                 sce->r.scemode &= ~R_NODE_PREVIEW;
869                 sce->r.scemode |= R_NO_IMAGE_LOAD;
870         }
871
872         /* in case of split preview, use border render */
873         if(split) {
874                 if(first) sizex= sp->sizex/2;
875                 else sizex= sp->sizex - sp->sizex/2;
876         }
877         else sizex= sp->sizex;
878
879         /* allocates or re-uses render result */
880         RE_InitState(re, NULL, &sce->r, sizex, sp->sizey, NULL);
881
882         /* callbacs are cleared on GetRender() */
883         if(sp->pr_method==PR_DO_RENDER) {
884                 RE_display_draw_cb(re, sp, shader_preview_draw);
885                 RE_test_break_cb(re, sp, shader_preview_break);
886         }
887         /* lens adjust */
888         oldlens= ((Camera *)sce->camera->data)->lens;
889         if(sizex > sp->sizey)
890                 ((Camera *)sce->camera->data)->lens *= (float)sp->sizey/(float)sizex;
891
892         /* entire cycle for render engine */
893         RE_SetCamera(re, sce->camera);
894         RE_Database_FromScene(re, sce, 1);
895         RE_TileProcessor(re, 0, 1);     // actual render engine
896         RE_Database_Free(re);
897
898         ((Camera *)sce->camera->data)->lens= oldlens;
899
900         /* handle results */
901         if(sp->pr_method==PR_ICON_RENDER) {
902                 if(sp->pr_rect)
903                         RE_ResultGet32(re, (unsigned int *)sp->pr_rect);
904         }
905         else {
906                 /* validate owner */
907                 //if(ri->rect==NULL)
908                 //      ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
909                 //RE_ResultGet32(re, ri->rect);
910         }
911
912         /* unassign the pointers, reset vars */
913         preview_prepare_scene(sp->scene, NULL, GS(id->name), NULL);
914 }
915
916 /* runs inside thread for material, in foreground for icons */
917 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
918 {
919         ShaderPreview *sp= customdata;
920
921         sp->stop= stop;
922         sp->do_update= do_update;
923
924         if(sp->parent) {
925                 shader_preview_render(sp, sp->parent, 1, 1);
926                 shader_preview_render(sp, sp->id, 1, 0);
927         }
928         else
929                 shader_preview_render(sp, sp->id, 0, 0);
930
931         *do_update= 1;
932 }
933
934 static void shader_preview_free(void *customdata)
935 {
936         ShaderPreview *sp= customdata;
937         
938         MEM_freeN(sp);
939 }
940
941 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, MTex *slot, int sizex, int sizey)
942 {
943         wmJob *steve;
944         ShaderPreview *sp;
945
946         /* XXX ugly global still, but we can't do preview while rendering */
947         if(G.rendering)
948                 return;
949
950         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner);
951         sp= MEM_callocN(sizeof(ShaderPreview), "shader preview");
952
953         /* customdata for preview thread */
954         sp->scene= CTX_data_scene(C);
955         sp->owner= owner;
956         sp->sizex= sizex;
957         sp->sizey= sizey;
958         sp->pr_method= PR_DO_RENDER;
959         sp->id = id;
960         sp->parent= parent;
961         sp->slot= slot;
962         
963         /* setup job */
964         WM_jobs_customdata(steve, sp, shader_preview_free);
965         WM_jobs_timer(steve, 0.1, NC_MATERIAL, NC_MATERIAL);
966         WM_jobs_callbacks(steve, shader_preview_startjob, NULL, shader_preview_updatejob);
967         
968         WM_jobs_start(CTX_wm_manager(C), steve);
969         
970         /* signal to rerender icon in menus */
971         BKE_icon_changed(BKE_icon_getid(id));
972 }
973
974 /* rect should be allocated, sizex/sizy pixels, 32 bits */
975 void ED_preview_iconrender(Scene *scene, ID *id, unsigned int *rect, int sizex, int sizey)
976 {
977         ShaderPreview *sp;
978         short stop=0, do_update=0;
979
980         sp= MEM_callocN(sizeof(ShaderPreview), "ShaderPreview");
981         
982         /* customdata for preview thread */
983         sp->scene= scene;
984         sp->sizex= sizex;
985         sp->sizey= sizey;
986         sp->pr_method= PR_ICON_RENDER;
987         sp->pr_rect= (int *)rect; /* shouldnt pr_rect be unsigned int also? - Campbell */
988         sp->id = id;
989
990         shader_preview_startjob(sp, &stop, &do_update);
991         
992         MEM_freeN(sp);
993 }
994
995
996