Sunsky / Atmoshphere:
[blender-staging.git] / source / blender / src / 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) 2001-2002 by NaN Holding BV.
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 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #ifndef WIN32
41 #include <unistd.h>
42 #else
43 #include <io.h>
44 #endif   
45 #include "MEM_guardedalloc.h"
46
47 #include "BLI_arithb.h"
48 #include "BLI_blenlib.h"
49
50 #include "MTC_matrixops.h"
51
52 #include "DNA_texture_types.h"
53 #include "DNA_world_types.h"
54 #include "DNA_camera_types.h"
55 #include "DNA_image_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_screen_types.h"
64
65 #include "BKE_depsgraph.h"
66 #include "BKE_global.h"
67 #include "BKE_image.h"
68 #include "BKE_icons.h"
69 #include "BKE_library.h"
70 #include "BKE_main.h"
71 #include "BKE_texture.h"
72 #include "BKE_material.h"
73 #include "BKE_node.h"
74 #include "BKE_world.h"
75 #include "BKE_texture.h"
76 #include "BKE_utildefines.h"
77
78 #include "IMB_imbuf.h"
79 #include "IMB_imbuf_types.h"
80
81 #include "BSE_headerbuttons.h"
82 #include "BSE_node.h"
83 #include "BSE_view.h"
84
85 #include "BIF_gl.h"
86 #include "BIF_screen.h"
87 #include "BIF_space.h"          /* allqueue */
88 #include "BIF_butspace.h"       
89 #include "BIF_mywindow.h"
90 #include "BIF_interface.h"
91 #include "BIF_glutil.h"
92
93 #include "BIF_previewrender.h"  /* include ourself for prototypes */
94
95 #include "PIL_time.h"
96
97 #include "RE_pipeline.h"
98 #include "BLO_readfile.h" 
99
100 #include "GPU_material.h"
101
102 #include "blendef.h"    /* CLAMP */
103 #include "interface.h"  /* ui_graphics_to_window(),  SOLVE! (ton) */
104 #include "mydevice.h"
105
106
107 #define PR_XMIN         10
108 #define PR_YMIN         5
109 #define PR_XMAX         200
110 #define PR_YMAX         195
111
112
113 static void set_previewrect(RenderInfo *ri, int win)
114 {
115         rctf viewplane;
116         
117         BLI_init_rctf(&viewplane, PR_XMIN, PR_XMAX, PR_YMIN, PR_YMAX);
118
119         ui_graphics_to_window_rct(win, &viewplane, &ri->disprect);
120         
121         /* correction for gla draw */
122         BLI_translate_rcti(&ri->disprect, -curarea->winrct.xmin, -curarea->winrct.ymin);
123         
124         glMatrixMode(GL_PROJECTION);
125         glPushMatrix();
126         glMatrixMode(GL_MODELVIEW);
127         glPushMatrix();
128         
129         glaDefine2DArea(&curarea->winrct);
130
131         ri->pr_rectx= (ri->disprect.xmax-ri->disprect.xmin);
132         ri->pr_recty= (ri->disprect.ymax-ri->disprect.ymin);
133 }
134
135 static void end_previewrect(void)
136 {
137         glMatrixMode(GL_PROJECTION);
138         glPopMatrix();
139         glMatrixMode(GL_MODELVIEW);
140         glPopMatrix();
141         
142         // restore viewport / scissor which was set by glaDefine2DArea
143         glViewport(curarea->winrct.xmin, curarea->winrct.ymin, curarea->winx, curarea->winy);
144         glScissor(curarea->winrct.xmin, curarea->winrct.ymin, curarea->winx, curarea->winy);
145
146 }
147
148 /* unused now */
149 void draw_tex_crop(Tex *tex)
150 {
151         rcti rct;
152         int ret= 0;
153         
154         if(tex==0) return;
155         
156         if(tex->type==TEX_IMAGE) {
157                 if(tex->cropxmin==0.0f) ret++;
158                 if(tex->cropymin==0.0f) ret++;
159                 if(tex->cropxmax==1.0f) ret++;
160                 if(tex->cropymax==1.0f) ret++;
161                 if(ret==4) return;
162                 
163                 rct.xmin= PR_XMIN+2+tex->cropxmin*(PR_XMAX-PR_XMIN-4);
164                 rct.xmax= PR_XMIN+2+tex->cropxmax*(PR_XMAX-PR_XMIN-4);
165                 rct.ymin= PR_YMIN+2+tex->cropymin*(PR_YMAX-PR_YMIN-4);
166                 rct.ymax= PR_YMIN+2+tex->cropymax*(PR_YMAX-PR_YMIN-4);
167
168                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
169
170                 glColor3ub(0, 0, 0);
171                 glRecti(rct.xmin+1,  rct.ymin-1,  rct.xmax+1,  rct.ymax-1); 
172
173                 glColor3ub(255, 255, 255);
174                 glRecti(rct.xmin,  rct.ymin,  rct.xmax,  rct.ymax);
175
176                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);                      
177         }
178         
179 }
180
181 /* temporal abuse; if id_code is -1 it only does texture.... solve! */
182 void BIF_preview_changed(short id_code)
183 {
184         ScrArea *sa;
185         
186         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
187                 if(sa->spacetype==SPACE_BUTS) {
188                         SpaceButs *sbuts= sa->spacedata.first;
189                         if(sbuts->mainb==CONTEXT_SHADING) {
190                                 int tab= sbuts->tab[CONTEXT_SHADING];
191                                 if(tab==TAB_SHADING_MAT && (id_code==ID_MA || id_code==ID_TE)) {
192                                         if (sbuts->ri) sbuts->ri->curtile= 0;
193                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
194                                 }
195                                 else if(tab==TAB_SHADING_TEX && (id_code==ID_TE || id_code==-1)) {
196                                         if (sbuts->ri) sbuts->ri->curtile= 0;
197                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
198                                 }
199                                 else if(tab==TAB_SHADING_LAMP && (id_code==ID_LA || id_code==ID_TE)) {
200                                         if (sbuts->ri) sbuts->ri->curtile= 0;
201                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
202                                 }
203                                 else if(tab==TAB_SHADING_WORLD && (id_code==ID_WO || id_code==ID_TE)) {
204                                         if (sbuts->ri) sbuts->ri->curtile= 0;
205                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
206                                 }
207                         }
208                         else if (sbuts->ri) 
209                                 sbuts->ri->curtile= 0;  /* ensure changes always result in re-render when context is restored */
210                 }
211                 else if(sa->spacetype==SPACE_NODE) {
212                         SpaceNode *snode= sa->spacedata.first;
213                         if(snode->treetype==NTREE_SHADER && (id_code==ID_MA || id_code==ID_TE)) {
214                                 snode_tag_dirty(snode);
215                         }
216                 }
217                 else if(sa->spacetype==SPACE_VIEW3D) {
218                         View3D *vd= sa->spacedata.first;
219                         /* if is has a renderinfo, we consider that reason for signalling */
220                         if (vd->ri) {
221                                 vd->ri->curtile= 0;
222                                 addafterqueue(sa->win, RENDERPREVIEW, 1);
223                         }
224                 }
225         }
226
227         if(ELEM4(id_code, ID_MA, ID_TE, ID_LA, ID_WO)) {
228                 Object *ob;
229                 Material *ma;
230
231                 if(id_code == ID_WO) {
232                         for(ma=G.main->mat.first; ma; ma=ma->id.next) {
233                                 if(ma->gpumaterial.first) {
234                                         GPU_material_free(ma);
235                                         allqueue(REDRAWVIEW3D, 0);
236                                 }
237                         }
238                 }
239                 else if(id_code == ID_LA) {
240                         for(ob=G.main->object.first; ob; ob=ob->id.next) {
241                                 if(ob->gpulamp.first) {
242                                         GPU_lamp_free(ob);
243                                         allqueue(REDRAWVIEW3D, 0);
244                                 }
245                         }
246                 } else if(OBACT) {
247                         Object *ob = OBACT;
248
249                         ma= give_current_material(ob, ob->actcol);
250                         if(ma && ma->gpumaterial.first) {
251                                 GPU_material_free(ma);
252                                 allqueue(REDRAWVIEW3D, 0);
253                         }
254                 }
255         }
256 }
257
258 /* *************************** Preview for buttons *********************** */
259
260 static Main *pr_main= NULL;
261
262 void BIF_preview_init_dbase(void)
263 {
264         BlendReadError bre;
265         BlendFileData *bfd;
266         extern int datatoc_preview_blend_size;
267         extern char datatoc_preview_blend[];
268         
269         G.fileflags |= G_FILE_NO_UI;
270         bfd= BLO_read_from_memory(datatoc_preview_blend, datatoc_preview_blend_size, &bre);
271         if (bfd) {
272                 pr_main= bfd->main;
273                 
274                 MEM_freeN(bfd);
275         }
276         G.fileflags &= ~G_FILE_NO_UI;
277 }
278
279 void BIF_preview_free_dbase(void)
280 {
281         if(pr_main)
282                 free_main(pr_main);
283 }
284
285 static Object *find_object(ListBase *lb, const char *name)
286 {
287         Object *ob;
288         for(ob= lb->first; ob; ob= ob->id.next)
289                 if(strcmp(ob->id.name+2, name)==0)
290                         break;
291         return ob;
292 }
293
294 /* call this with an ID pointer to initialize preview scene */
295 /* call this with ID NULL to restore assigned ID pointers in preview scene */
296 static Scene *preview_prepare_scene(RenderInfo *ri, int id_type, ID *id, int pr_method)
297 {
298         Scene *sce;
299         Base *base;
300         
301         if(pr_main==NULL) return NULL;
302         
303         sce= pr_main->scene.first;
304         if(sce) {
305                 /* this flag tells render to not execute depsgraph or ipos etc */
306                 sce->r.scemode |= R_PREVIEWBUTS;
307                 /* set world always back, is used now */
308                 sce->world= pr_main->world.first;
309                 /* now: exposure copy */
310                 if(G.scene->world) {
311                         sce->world->exp= G.scene->world->exp;
312                         sce->world->range= G.scene->world->range;
313                 }
314                 
315                 sce->r.cfra= G.scene->r.cfra;
316                 
317                 if(id_type==ID_MA) {
318                         Material *mat= (Material *)id;
319                         
320                         if(id) {
321                                 init_render_material(mat, 0, NULL);             /* call that retrieves mode_l */
322                                 end_render_material(mat);
323                                 
324                                 /* turn on raytracing if needed */
325                                 if(mat->mode_l & (MA_RAYTRANSP|MA_RAYMIRROR))
326                                         sce->r.mode |= R_RAYTRACE;
327                                 if(mat->sss_flag & MA_DIFF_SSS)
328                                         sce->r.mode |= R_SSS;
329                                 
330                                 /* turn off fake shadows if needed */
331                                 /* this only works in a specific case where the preview.blend contains
332                                  * an object starting with 'c' which has a material linked to it (not the obdata)
333                                  * and that material has a fake shadow texture in the active texture slot */
334                                 for(base= sce->base.first; base; base= base->next) {
335                                         if(base->object->id.name[2]=='c') {
336                                                 Material *shadmat= give_current_material(base->object, base->object->actcol);
337                                                 if(shadmat) {
338                                                         if (mat->mode & MA_SHADBUF) shadmat->septex = 0;
339                                                         else shadmat->septex |= 1;
340                                                 }
341                                         }
342                                 }
343
344                                 
345                                 if(pr_method==PR_ICON_RENDER) {
346                                         if (mat->mode & MA_HALO) {
347                                                 sce->lay= 1<<MA_FLAT;
348                                         } 
349                                         else {
350                                                 sce->lay= 1<<MA_SPHERE_A;
351                                         }
352                                 }
353                                 else {
354                                         sce->lay= 1<<mat->pr_type;
355                                         if(mat->nodetree)
356                                                 ntreeInitPreview(mat->nodetree, ri->pr_rectx, ri->pr_recty);
357                                 }
358                         }
359                         else {
360                                 sce->r.mode &= ~(R_OSA|R_RAYTRACE|R_SSS);
361                         }
362                         
363                         for(base= sce->base.first; base; base= base->next) {
364                                 if(base->object->id.name[2]=='p') {
365                                         if(ELEM4(base->object->type, OB_MESH, OB_CURVE, OB_SURF, OB_MBALL))
366                                                 assign_material(base->object, mat, base->object->actcol);
367                                 }
368                         }
369                 }
370                 else if(id_type==ID_TE) {
371                         Tex *tex= (Tex *)id;
372                         
373                         sce->lay= 1<<MA_TEXTURE;
374                         
375                         for(base= sce->base.first; base; base= base->next) {
376                                 if(base->object->id.name[2]=='t') {
377                                         Material *mat= give_current_material(base->object, base->object->actcol);
378                                         if(mat && mat->mtex[0]) {
379                                                 mat->mtex[0]->tex= tex;
380                                                 /* show alpha in this case */
381                                                 if(tex==NULL || (tex->flag & TEX_PRV_ALPHA)) {
382                                                         mat->mtex[0]->mapto |= MAP_ALPHA;
383                                                         mat->alpha= 0.0f;
384                                                 }
385                                                 else {
386                                                         mat->mtex[0]->mapto &= ~MAP_ALPHA;
387                                                         mat->alpha= 1.0f;
388                                                 }
389                                         }
390                                 }
391                         }
392                 }
393                 else if(id_type==ID_LA) {
394                         Lamp *la= (Lamp *)id;
395                         
396                         if(la && la->type==LA_SUN && (la->sun_effect_type & LA_SUN_EFFECT_SKY)) {
397                                 sce->lay= 1<<MA_ATMOS;
398                                 sce->world= G.scene->world;
399                                 sce->camera= (Object *)find_object(&pr_main->object, "CameraAtmo");
400                         }
401                         else {
402                                 sce->lay= 1<<MA_LAMP;
403                                 sce->world= NULL;
404                                 sce->camera= (Object *)find_object(&pr_main->object, "Camera");
405                         }
406                         sce->r.mode &= ~R_SHADOW;
407                         
408                         for(base= sce->base.first; base; base= base->next) {
409                                 if(base->object->id.name[2]=='p') {
410                                         if(base->object->type==OB_LAMP)
411                                                 base->object->data= la;
412                                 }
413                         }
414                 }
415                 else if(id_type==ID_WO) {
416                         sce->lay= 1<<MA_SKY;
417                         sce->world= (World *)id;
418                 }
419                 
420                 return sce;
421         }
422         
423         return NULL;
424 }
425
426 static void previewrender_progress(RenderResult *rr, volatile rcti *renrect)
427 {
428         RenderLayer *rl;
429         RenderInfo *ri= G.buts->ri;
430         float ofsx, ofsy;
431         
432         if(renrect) return;
433         
434         rl= rr->layers.first;
435         
436         ofsx= ri->disprect.xmin + rr->tilerect.xmin;
437         ofsy= ri->disprect.ymin + rr->tilerect.ymin;
438         
439         glDrawBuffer(GL_FRONT);
440         glaDrawPixelsSafe_to32(ofsx, ofsy, rr->rectx, rr->recty, rr->rectx, rl->rectf);
441         bglFlush();
442         glDrawBuffer(GL_BACK);
443 }
444
445
446 /* called by interface_icons.c, or by BIF_previewrender_buts or by nodes... */
447 void BIF_previewrender(struct ID *id, struct RenderInfo *ri, struct ScrArea *area, int pr_method)
448 {
449         Render *re;
450         RenderStats *rstats;
451         Scene *sce;
452         SpaceButs *sbuts= NULL;
453         int oldx= ri->pr_rectx, oldy= ri->pr_recty;
454         char name [32];
455         
456         if(ri->tottile && ri->curtile>=ri->tottile) return;
457         
458         /* check for return with a new event */
459         if(pr_method!=PR_ICON_RENDER && qtest()) {
460                 if(area)
461                         addafterqueue(area->win, RENDERPREVIEW, 1);
462                 return;
463         }
464         
465         /* get the stuff from the builtin preview dbase */
466         sce= preview_prepare_scene(ri, GS(id->name), id, pr_method);
467         if(sce==NULL) return;
468         
469         /* set drawing conditions OK */
470         if(area) {
471                 sbuts= area->spacedata.first;   /* needed for flag */
472                 
473                 set_previewrect(ri, area->win); // uses UImat
474                 
475                 /* because preview render size can differs */
476                 if(ri->rect && (oldx!=ri->pr_rectx || oldy!=ri->pr_recty)) {
477                         MEM_freeN(ri->rect);
478                         ri->rect= NULL;
479                         ri->curtile= 0;
480                 }
481         }
482         
483         sprintf(name, "ButsPreview %d", area?area->win:0);
484         re= RE_GetRender(name);
485         
486         /* full refreshed render from first tile */
487         if(re==NULL || ri->curtile==0) {
488                 
489                 re= RE_NewRender(name);
490                 
491                 /* handle cases */
492                 if(pr_method==PR_DRAW_RENDER) {
493                         RE_display_draw_cb(re, previewrender_progress);
494                         RE_test_break_cb(re, qtest);
495                         sce->r.scemode |= R_NODE_PREVIEW;
496                         if(sbuts->flag & SB_PRV_OSA)
497                                 sce->r.mode |= R_OSA;
498                         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
499                 }
500                 else if(pr_method==PR_DO_RENDER) {
501                         RE_test_break_cb(re, qtest);
502                         sce->r.scemode |= R_NODE_PREVIEW;
503                         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
504                 }
505                 else {  /* PR_ICON_RENDER */
506                         sce->r.scemode &= ~R_NODE_PREVIEW;
507                         sce->r.scemode |= R_NO_IMAGE_LOAD;
508                 }
509                 
510                 /* allocates render result */
511                 RE_InitState(re, NULL, &sce->r, ri->pr_rectx, ri->pr_recty, NULL);
512                 
513                 /* enforce preview image clear */
514                 if(GS(id->name)==ID_MA) {
515                         Material *ma= (Material *)id;
516                         ntreeClearPreview(ma->nodetree);
517                 }
518         }
519         /* entire cycle for render engine */
520         RE_SetCamera(re, sce->camera);
521         RE_Database_FromScene(re, sce, 1);
522         RE_TileProcessor(re, ri->curtile, 0);   // actual render engine
523         RE_Database_Free(re);
524         
525         /* handle results */
526         if(pr_method==PR_ICON_RENDER) {
527                 if(ri->rect==NULL)
528                         ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
529                 RE_ResultGet32(re, ri->rect);
530         }
531         else {
532                 rstats= RE_GetStats(re);
533                 
534                 if(rstats->partsdone!=ri->curtile) {
535                         if(ri->rect==NULL)
536                                 ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
537                         RE_ResultGet32(re, ri->rect);
538                 }
539                 
540                 if(rstats->totpart==rstats->partsdone && rstats->partsdone) {
541                         if(GS(id->name)==ID_MA && ((Material *)id)->use_nodes)
542                                 allqueue(REDRAWNODE, 0);
543                         allqueue(REDRAWBUTSSHADING, 0);
544                 }
545                 else {
546                         if(pr_method==PR_DRAW_RENDER && qtest())
547                                 addafterqueue(area->win, RENDERPREVIEW, 1);
548                 }
549                 
550                 ri->curtile= rstats->partsdone;
551                 ri->tottile= rstats->totpart;
552         }
553
554         /* unassign the pointers, reset vars */
555         preview_prepare_scene(ri, GS(id->name), NULL, 0);
556         
557 }
558
559
560 /* afterqueue call */
561 void BIF_previewrender_buts(SpaceButs *sbuts)
562 {
563         uiBlock *block;
564         struct ID* id = 0;
565         struct ID* idfrom = 0;
566         struct ID* idshow = 0;
567         Object *ob;
568         
569         if (!sbuts->ri) return;
570         
571         /* we safely assume curarea has panel "preview" */
572         /* quick hack for now, later on preview should become uiBlock itself */
573         
574         block= uiFindOpenPanelBlockName(&curarea->uiblocks, "Preview");
575         if(block==NULL) return;
576         
577         ob= ((G.scene->basact)? (G.scene->basact)->object: 0);
578         
579         /* we cant trust this global lockpoin.. for example with headerless window */
580         buttons_active_id(&id, &idfrom);
581         G.buts->lockpoin= id;
582         
583         if(sbuts->mainb==CONTEXT_SHADING) {
584                 int tab= sbuts->tab[CONTEXT_SHADING];
585                 
586                 if(tab==TAB_SHADING_MAT) 
587                         idshow = sbuts->lockpoin;
588                 else if(tab==TAB_SHADING_TEX) 
589                         idshow = sbuts->lockpoin;
590                 else if(tab==TAB_SHADING_LAMP) {
591                         if(ob && ob->type==OB_LAMP) idshow= ob->data;
592                 }
593                 else if(tab==TAB_SHADING_WORLD)
594                         idshow = sbuts->lockpoin;
595         }
596         else if(sbuts->mainb==CONTEXT_OBJECT) {
597                 if(ob && ob->type==OB_LAMP) idshow = ob->data;
598         }
599         
600         if (idshow) {
601                 BKE_icon_changed(BKE_icon_getid(idshow));
602                 uiPanelPush(block);
603                 BIF_previewrender(idshow, sbuts->ri, sbuts->area, PR_DRAW_RENDER);
604                 uiPanelPop(block);
605                 end_previewrect();
606         }
607         else {
608                 /* no active block to draw. But we do draw black if possible */
609                 if(sbuts->ri->rect) {
610                         memset(sbuts->ri->rect, 0, sizeof(int)*sbuts->ri->pr_rectx*sbuts->ri->pr_recty);
611                         sbuts->ri->tottile= 10000;
612                         addqueue(curarea->win, REDRAW, 1);
613                 }
614                 return;
615         }
616 }
617
618
619 /* is panel callback, supposed to be called with correct panel offset matrix */
620 void BIF_previewdraw(ScrArea *sa, uiBlock *block)
621 {
622         SpaceButs *sbuts= sa->spacedata.first;
623         short id_code= 0;
624         
625         if(sbuts->lockpoin) {
626                 ID *id= sbuts->lockpoin;
627                 id_code= GS(id->name);
628         }
629         
630         if (!sbuts->ri) {
631                 sbuts->ri= MEM_callocN(sizeof(RenderInfo), "butsrenderinfo");
632                 sbuts->ri->tottile = 10000;
633         }
634         
635         if (sbuts->ri->rect==NULL) BIF_preview_changed(id_code);
636         else {
637                 RenderInfo *ri= sbuts->ri;
638                 int oldx= ri->pr_rectx, oldy= ri->pr_recty;
639                 
640                 /* we now do scalable previews! */
641                 set_previewrect(ri, sa->win);
642                 if( ABS(oldx-ri->pr_rectx)<2 && ABS(oldy-ri->pr_recty)<2 ) {
643                         /* restore old values for drawing! */
644                         ri->pr_rectx= oldx;
645                         ri->pr_recty= oldy;
646                         glaDrawPixelsSafe(ri->disprect.xmin, ri->disprect.ymin, ri->pr_rectx, ri->pr_recty, ri->pr_rectx, GL_RGBA, GL_UNSIGNED_BYTE, ri->rect);
647                 }
648                 else {
649                         MEM_freeN(ri->rect);
650                         ri->rect= NULL;
651                         sbuts->ri->curtile= 0;
652                 }
653                 end_previewrect();
654         }
655         if(sbuts->ri->curtile==0) BIF_preview_changed(id_code);
656         
657 }
658
659 /* *************************** Preview for 3d window *********************** */
660 static void view3d_previewrender_stats(RenderStats *rs)
661 {
662 //      if(rs->convertdone) 
663 //              printf("rendered %d %.3f\n", rs->partsdone, rs->lastframetime);
664 }
665
666 static void view3d_previewrender_progress(RenderResult *rr, volatile rcti *renrect)
667 {
668         RenderLayer *rl;
669         int ofsx, ofsy;
670         
671         if(renrect) return;
672         
673         rl= rr->layers.first;
674         
675         /* this case is when we render envmaps... */
676         if(rr->rectx>G.vd->ri->pr_rectx || rr->recty>G.vd->ri->pr_recty)
677                 return;
678         
679         ofsx= G.vd->ri->disprect.xmin + rr->tilerect.xmin;
680         ofsy= G.vd->ri->disprect.ymin + rr->tilerect.ymin;
681         
682         glDrawBuffer(GL_FRONT);
683         glaDefine2DArea(&curarea->winrct);
684         glaDrawPixelsSafe_to32(ofsx, ofsy, rr->rectx, rr->recty, rr->rectx, rl->rectf);
685         bglFlush();
686         glDrawBuffer(GL_BACK);
687
688 }
689
690 void BIF_view3d_previewrender_signal(ScrArea *sa, short signal)
691 {
692         View3D *v3d= sa->spacedata.first;
693         
694         /* this can be called from other window... solve! */
695         if(sa->spacetype!=SPACE_VIEW3D)
696                 v3d= G.vd;
697            
698         if(v3d && v3d->ri) {
699                 RenderInfo *ri= v3d->ri;
700                 ri->status &= ~signal;
701                 ri->curtile= 0;
702                 //printf("preview signal %d\n", signal);
703                 if(ri->re && (signal & PR_DBASE))
704                         RE_Database_Free(ri->re);
705
706                 addafterqueue(sa->win, RENDERPREVIEW, 1);
707         }
708 }
709
710 void BIF_view3d_previewrender_free(View3D *v3d)
711 {
712
713         if(v3d->ri) {
714                 RenderInfo *ri= v3d->ri;
715                 if(ri->re) {
716 //                      printf("free render\n");
717                         RE_Database_Free(ri->re);
718                         RE_FreeRender(ri->re);
719                         ri->re= NULL;
720                 }
721                 if (v3d->ri->rect) MEM_freeN(v3d->ri->rect);
722                 MEM_freeN(v3d->ri);
723                 v3d->ri= NULL;
724         }
725 }
726
727 /* returns 1 if OK, do not call while in panel space!  */
728 static int view3d_previewrender_get_rects(ScrArea *sa, rctf *viewplane, RenderInfo *ri, float *clipsta, float *clipend, int *ortho, float *pixsize)
729 {
730         int rectx, recty;
731         uiBlock *block;
732         
733         block= uiFindOpenPanelBlockName(&curarea->uiblocks, "Preview");
734         if(block==NULL) return 0;
735         
736         /* calculate preview rect size */
737         BLI_init_rctf(viewplane, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
738         uiPanelPush(block);
739         ui_graphics_to_window_rct(sa->win, viewplane, &ri->disprect);
740         uiPanelPop(block);
741         
742         /* correction for gla draw */
743         BLI_translate_rcti(&ri->disprect, -sa->winrct.xmin, -sa->winrct.ymin);
744         
745         *ortho= get_view3d_viewplane(sa->winx, sa->winy, viewplane, clipsta, clipend, pixsize);
746
747         rectx= ri->disprect.xmax - ri->disprect.xmin;
748         recty= ri->disprect.ymax - ri->disprect.ymin;
749         
750         if(rectx<4 || recty<4) return 0;
751         
752         if(ri->rect && (rectx!=ri->pr_rectx || recty!=ri->pr_recty)) {
753                 MEM_freeN(ri->rect);
754                 ri->rect= NULL;
755                 ri->curtile= 0;
756                 printf("changed size\n");
757         }
758         ri->pr_rectx= rectx;
759         ri->pr_recty= recty;
760         
761         return 1;
762 }
763
764 /* called before a panel gets moved/scaled, makes sure we can see through */
765 void BIF_view3d_previewrender_clear(ScrArea *sa)
766 {
767         View3D *v3d= sa->spacedata.first;
768
769         if(v3d->ri) {
770                 RenderInfo *ri= v3d->ri;
771                 ri->curtile= 0;
772                 if(ri->rect)
773                         MEM_freeN(ri->rect);
774                 ri->rect= NULL;
775         }
776 }
777
778 /* afterqueue call */
779 void BIF_view3d_previewrender(ScrArea *sa)
780 {
781         View3D *v3d= sa->spacedata.first;
782         Render *re;
783         RenderInfo *ri; /* preview struct! */
784         RenderStats *rstats;
785         RenderData rdata;
786         rctf viewplane;
787         float clipsta, clipend, pixsize;
788         int orth;
789         
790         /* first get the render info right */
791         if (!v3d->ri) {
792                 ri= v3d->ri= MEM_callocN(sizeof(RenderInfo), "butsrenderinfo");
793                 ri->tottile= 10000;
794         }
795         ri= v3d->ri;
796         
797         if(0==view3d_previewrender_get_rects(sa, &viewplane, ri, &clipsta, &clipend, &orth, &pixsize))
798                 return;
799         
800         /* render is finished, so return */
801         if(ri->tottile && ri->curtile>=ri->tottile) return;
802
803         /* or return with a new event */
804         if(qtest()) {
805                 addafterqueue(curarea->win, RENDERPREVIEW, 1);
806                 return;
807         }
808         //printf("Enter previewrender\n");
809         /* ok, are we rendering all over? */
810         if(ri->re==NULL) {
811                 char name[32];
812                 
813                 ri->status= 0;
814                 
815                 sprintf(name, "View3dPreview %d", sa->win);
816                 re= ri->re= RE_NewRender(name);
817                 RE_display_draw_cb(re, view3d_previewrender_progress);
818                 RE_stats_draw_cb(re, view3d_previewrender_stats);
819                 RE_test_break_cb(re, qtest);
820                 
821                 /* no osa, blur, seq, layers, etc for preview render */
822                 rdata= G.scene->r;
823                 rdata.mode &= ~(R_OSA|R_MBLUR);
824                 rdata.scemode &= ~(R_DOSEQ|R_DOCOMP|R_FREE_IMAGE);
825                 rdata.layers.first= rdata.layers.last= NULL;
826                 rdata.renderer= R_INTERN;
827                  
828                 RE_InitState(re, NULL, &rdata, sa->winx, sa->winy, &ri->disprect);
829         
830                 if(orth)
831                         RE_SetOrtho(re, &viewplane, clipsta, clipend);
832                 else
833                         RE_SetWindow(re, &viewplane, clipsta, clipend);
834                 RE_SetPixelSize(re, pixsize);
835                 
836                 /* until here are no escapes */
837                 ri->status |= PR_DISPRECT;
838                 ri->curtile= 0;
839                 //printf("new render\n");
840         }
841
842         re= ri->re;
843         
844         PIL_sleep_ms(100);      /* wait 0.1 second if theres really no event... */
845         if(qtest()==0)  {
846                 
847                 /* check status */
848                 if((ri->status & PR_DISPRECT)==0) {
849                         RE_SetDispRect(ri->re, &ri->disprect);
850                         if(orth)
851                                 RE_SetOrtho(ri->re, &viewplane, clipsta, clipend);
852                         else
853                                 RE_SetWindow(ri->re, &viewplane, clipsta, clipend);
854                         RE_SetPixelSize(re, pixsize);
855                         ri->status |= PR_DISPRECT;
856                         ri->curtile= 0;
857                         //printf("disprect update\n");
858                 }
859                 if((ri->status & PR_DBASE)==0) {
860                         unsigned int lay= G.scene->lay;
861                         
862                         RE_SetView(re, G.vd->viewmat);
863                         
864                         /* allow localview render for objects with lights in normal layers */
865                         if(v3d->lay & 0xFF000000)
866                                 G.scene->lay |= v3d->lay;
867                         else G.scene->lay= v3d->lay;
868                         
869                         RE_Database_FromScene(re, G.scene, 0);          // 0= dont use camera view
870                         G.scene->lay= lay;
871                         
872                         rstats= RE_GetStats(re);
873                         if(rstats->convertdone) 
874                                 ri->status |= PR_DBASE|PR_PROJECTED|PR_ROTATED;
875                         ri->curtile= 0;
876                         
877                         /* database can have created render-resol data... */
878                         if(rstats->convertdone) 
879                                 DAG_scene_update_flags(G.scene, screen_view3d_layers());
880                         
881                         //printf("dbase update\n");
882                 }
883                 if((ri->status & PR_PROJECTED)==0) {
884                         if(ri->status & PR_DBASE) {
885                                 if(orth)
886                                         RE_SetOrtho(ri->re, &viewplane, clipsta, clipend);
887                                 else
888                                         RE_SetWindow(ri->re, &viewplane, clipsta, clipend);
889                                 RE_DataBase_ApplyWindow(re);
890                                 ri->status |= PR_PROJECTED;
891                         }
892                         ri->curtile= 0;
893                         //printf("project update\n");
894                 }
895         
896                 /* OK, can we enter render code? */
897                 if(ri->status==(PR_DISPRECT|PR_DBASE|PR_PROJECTED|PR_ROTATED)) {
898                         //printf("curtile %d tottile %d\n", ri->curtile, ri->tottile);
899                         RE_TileProcessor(ri->re, ri->curtile, 0);
900         
901                         if(ri->rect==NULL)
902                                 ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "preview view3d rect");
903                         
904                         RE_ResultGet32(ri->re, ri->rect);
905                 }
906                 
907                 rstats= RE_GetStats(ri->re);
908                 if(rstats->totpart==rstats->partsdone && rstats->partsdone)
909                         addqueue(sa->win, REDRAW, 1);
910                 else
911                         addafterqueue(curarea->win, RENDERPREVIEW, 1);
912                 
913                 ri->curtile= rstats->partsdone;
914                 ri->tottile= rstats->totpart;
915         }
916         else {
917                 addafterqueue(curarea->win, RENDERPREVIEW, 1);
918         }
919         
920         //printf("\n");
921 }
922
923 /* in panel space! */
924 static void view3d_previewdraw_rect(ScrArea *sa, uiBlock *block, RenderInfo *ri)
925 {
926         rctf dispf;
927         
928         if(ri->rect==NULL)
929                 return;
930         
931         BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
932         ui_graphics_to_window_rct(sa->win, &dispf, &ri->disprect);
933
934         /* correction for gla draw */
935         BLI_translate_rcti(&ri->disprect, -curarea->winrct.xmin, -curarea->winrct.ymin);
936         
937         /* when panel scale changed, free rect */
938         if(ri->disprect.xmax-ri->disprect.xmin != ri->pr_rectx ||
939            ri->disprect.ymax-ri->disprect.ymin != ri->pr_recty) {
940                 MEM_freeN(ri->rect);
941                 ri->rect= NULL;
942         }
943         else {
944                 glaDefine2DArea(&sa->winrct);
945                 glaDrawPixelsSafe(ri->disprect.xmin, ri->disprect.ymin, ri->pr_rectx, ri->pr_recty, ri->pr_rectx, GL_RGBA, GL_UNSIGNED_BYTE, ri->rect);
946         }       
947 }
948
949 /* is panel callback, supposed to be called with correct panel offset matrix */
950 void BIF_view3d_previewdraw(struct ScrArea *sa, struct uiBlock *block)
951 {
952         View3D *v3d= sa->spacedata.first;
953
954         if (v3d->ri==NULL || v3d->ri->rect==NULL) 
955                 addafterqueue(sa->win, RENDERPREVIEW, 1);
956         else {
957                 view3d_previewdraw_rect(sa, block, v3d->ri);
958                 if(v3d->ri->curtile==0) 
959                         addafterqueue(sa->win, RENDERPREVIEW, 1);
960         }
961 }
962