2.5
[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         
116         int sizex, sizey;
117         int pr_method;
118         
119 } ShaderPreview;
120
121
122 static void set_previewrect(ScrArea *sa, RenderInfo *ri)
123 {
124         ARegion *ar= NULL; // XXX
125         rctf viewplane;
126         
127         BLI_init_rctf(&viewplane, PR_XMIN, PR_XMAX, PR_YMIN, PR_YMAX);
128
129 //      ui_graphics_to_window_rct(ar->win, &viewplane, &ri->disprect);
130         
131         /* correction for gla draw */
132         BLI_translate_rcti(&ri->disprect, -ar->winrct.xmin, -ar->winrct.ymin);
133         
134         glMatrixMode(GL_PROJECTION);
135         glPushMatrix();
136         glMatrixMode(GL_MODELVIEW);
137         glPushMatrix();
138         
139         glaDefine2DArea(&ar->winrct);
140
141         ri->pr_rectx= (ri->disprect.xmax-ri->disprect.xmin);
142         ri->pr_recty= (ri->disprect.ymax-ri->disprect.ymin);
143 }
144
145 static void end_previewrect(ARegion *ar)
146 {
147         glMatrixMode(GL_PROJECTION);
148         glPopMatrix();
149         glMatrixMode(GL_MODELVIEW);
150         glPopMatrix();
151         
152         // restore viewport / scissor which was set by glaDefine2DArea
153         glViewport(ar->winrct.xmin, ar->winrct.ymin, ar->winx, ar->winy);
154         glScissor(ar->winrct.xmin, ar->winrct.ymin, ar->winx, ar->winy);
155
156 }
157
158 /* unused now */
159 void draw_tex_crop(Tex *tex)
160 {
161         rcti rct;
162         int ret= 0;
163         
164         if(tex==0) return;
165         
166         if(tex->type==TEX_IMAGE) {
167                 if(tex->cropxmin==0.0f) ret++;
168                 if(tex->cropymin==0.0f) ret++;
169                 if(tex->cropxmax==1.0f) ret++;
170                 if(tex->cropymax==1.0f) ret++;
171                 if(ret==4) return;
172                 
173                 rct.xmin= PR_XMIN+2+tex->cropxmin*(PR_XMAX-PR_XMIN-4);
174                 rct.xmax= PR_XMIN+2+tex->cropxmax*(PR_XMAX-PR_XMIN-4);
175                 rct.ymin= PR_YMIN+2+tex->cropymin*(PR_YMAX-PR_YMIN-4);
176                 rct.ymax= PR_YMIN+2+tex->cropymax*(PR_YMAX-PR_YMIN-4);
177
178                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
179
180                 glColor3ub(0, 0, 0);
181                 glRecti(rct.xmin+1,  rct.ymin-1,  rct.xmax+1,  rct.ymax-1); 
182
183                 glColor3ub(255, 255, 255);
184                 glRecti(rct.xmin,  rct.ymin,  rct.xmax,  rct.ymax);
185
186                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);                      
187         }
188         
189 }
190
191 /* temporal abuse; if id_code is -1 it only does texture.... solve! */
192 void BIF_preview_changed(short id_code)
193 {
194 #if 0   
195         ScrArea *sa;
196         
197         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
198                 if(sa->spacetype==SPACE_BUTS) {
199                         SpaceButs *sbuts= sa->spacedata.first;
200                         if(sbuts->mainb==CONTEXT_SHADING) {
201                                 int tab= sbuts->tab[CONTEXT_SHADING];
202                                 if(tab==TAB_SHADING_MAT && (id_code==ID_MA || id_code==ID_TE)) {
203                                         if (sbuts->ri) sbuts->ri->curtile= 0;
204                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
205                                 }
206                                 else if(tab==TAB_SHADING_TEX && (id_code==ID_TE || id_code==-1)) {
207                                         if (sbuts->ri) sbuts->ri->curtile= 0;
208                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
209                                 }
210                                 else if(tab==TAB_SHADING_LAMP && (id_code==ID_LA || id_code==ID_TE)) {
211                                         if (sbuts->ri) sbuts->ri->curtile= 0;
212                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
213                                 }
214                                 else if(tab==TAB_SHADING_WORLD && (id_code==ID_WO || id_code==ID_TE)) {
215                                         if (sbuts->ri) sbuts->ri->curtile= 0;
216                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
217                                 }
218                         }
219                         else if (sbuts->ri) 
220                                 sbuts->ri->curtile= 0;  /* ensure changes always result in re-render when context is restored */
221                 }
222                 else if(sa->spacetype==SPACE_NODE) {
223                         SpaceNode *snode= sa->spacedata.first;
224                         if(snode->treetype==NTREE_SHADER && (id_code==ID_MA || id_code==ID_TE)) {
225                                 snode_tag_dirty(snode);
226                         }
227                 }
228                 else if(sa->spacetype==SPACE_VIEW3D) {
229                         View3D *vd= sa->spacedata.first;
230                         /* if is has a renderinfo, we consider that reason for signalling */
231                         if (vd->ri) {
232                                 vd->ri->curtile= 0;
233                                 addafterqueue(sa->win, RENDERPREVIEW, 1);
234                         }
235                 }
236         }
237
238         if(ELEM4(id_code, ID_MA, ID_TE, ID_LA, ID_WO)) {
239                 Object *ob;
240                 Material *ma;
241
242                 if(id_code == ID_WO) {
243                         for(ma=G.main->mat.first; ma; ma=ma->id.next) {
244                                 if(ma->gpumaterial.first) {
245                                         GPU_material_free(ma);
246                                 }
247                         }
248                 }
249                 else if(id_code == ID_LA) {
250                         for(ob=G.main->object.first; ob; ob=ob->id.next) {
251                                 if(ob->gpulamp.first) {
252                                         GPU_lamp_free(ob);
253                                 }
254                         }
255                 } else if(OBACT) {
256                         Object *ob = OBACT;
257
258                         ma= give_current_material(ob, ob->actcol);
259                         if(ma && ma->gpumaterial.first) {
260                                 GPU_material_free(ma);
261                         }
262                 }
263         }
264 #endif
265 }
266
267 /* *************************** Preview for buttons *********************** */
268
269 static Main *pr_main= NULL;
270
271 void ED_preview_init_dbase(void)
272 {
273         BlendFileData *bfd;
274         extern int datatoc_preview_blend_size;
275         extern char datatoc_preview_blend[];
276         
277         G.fileflags |= G_FILE_NO_UI;
278         bfd= BLO_read_from_memory(datatoc_preview_blend, datatoc_preview_blend_size, NULL);
279         if (bfd) {
280                 pr_main= bfd->main;
281                 
282                 MEM_freeN(bfd);
283         }
284         G.fileflags &= ~G_FILE_NO_UI;
285 }
286
287 void ED_preview_free_dbase(void)
288 {
289         if(pr_main)
290                 free_main(pr_main);
291 }
292
293 static Object *find_object(ListBase *lb, const char *name)
294 {
295         Object *ob;
296         for(ob= lb->first; ob; ob= ob->id.next)
297                 if(strcmp(ob->id.name+2, name)==0)
298                         break;
299         return ob;
300 }
301
302 /* call this with a pointer to initialize preview scene */
303 /* call this with NULL to restore assigned ID pointers in preview scene */
304 static Scene *preview_prepare_scene(Scene *scene, int id_type, ShaderPreview *sp)
305 {
306         Scene *sce;
307         Base *base;
308         ID *id= sp?sp->id:NULL;
309         
310         if(pr_main==NULL) return NULL;
311         
312         sce= pr_main->scene.first;
313         if(sce) {
314                 /* this flag tells render to not execute depsgraph or ipos etc */
315                 sce->r.scemode |= R_PREVIEWBUTS;
316                 /* set world always back, is used now */
317                 sce->world= pr_main->world.first;
318                 /* now: exposure copy */
319                 if(scene->world) {
320                         sce->world->exp= scene->world->exp;
321                         sce->world->range= scene->world->range;
322                 }
323                 
324                 sce->r.cfra= scene->r.cfra;
325                 
326                 if(id_type==ID_MA) {
327                         Material *mat= (Material *)id;
328                         
329                         if(id) {
330                                 init_render_material(mat, 0, NULL);             /* call that retrieves mode_l */
331                                 end_render_material(mat);
332                                 
333                                 /* turn on raytracing if needed */
334                                 if(mat->mode_l & (MA_RAYTRANSP|MA_RAYMIRROR))
335                                         sce->r.mode |= R_RAYTRACE;
336                                 if(mat->sss_flag & MA_DIFF_SSS)
337                                         sce->r.mode |= R_SSS;
338                                 
339                                 /* turn off fake shadows if needed */
340                                 /* this only works in a specific case where the preview.blend contains
341                                  * an object starting with 'c' which has a material linked to it (not the obdata)
342                                  * and that material has a fake shadow texture in the active texture slot */
343                                 for(base= sce->base.first; base; base= base->next) {
344                                         if(base->object->id.name[2]=='c') {
345                                                 Material *shadmat= give_current_material(base->object, base->object->actcol);
346                                                 if(shadmat) {
347                                                         if (mat->mode & MA_SHADBUF) shadmat->septex = 0;
348                                                         else shadmat->septex |= 1;
349                                                 }
350                                         }
351                                 }
352
353                                 
354                                 if(sp->pr_method==PR_ICON_RENDER) {
355                                         if (mat->material_type == MA_TYPE_HALO) {
356                                                 sce->lay= 1<<MA_FLAT;
357                                         } 
358                                         else {
359                                                 sce->lay= 1<<MA_SPHERE_A;
360                                         }
361                                 }
362                                 else {
363                                         sce->lay= 1<<mat->pr_type;
364                                         if(mat->nodetree)
365                                                 ntreeInitPreview(mat->nodetree, sp->sizex, sp->sizey);
366                                 }
367                         }
368                         else {
369                                 sce->r.mode &= ~(R_OSA|R_RAYTRACE|R_SSS);
370                         }
371                         
372                         for(base= sce->base.first; base; base= base->next) {
373                                 if(base->object->id.name[2]=='p') {
374                                         if(ELEM4(base->object->type, OB_MESH, OB_CURVE, OB_SURF, OB_MBALL))
375                                                 assign_material(base->object, mat, base->object->actcol);
376                                 }
377                         }
378                 }
379                 else if(id_type==ID_TE) {
380                         Tex *tex= (Tex *)id;
381                         
382                         sce->lay= 1<<MA_TEXTURE;
383                         
384                         for(base= sce->base.first; base; base= base->next) {
385                                 if(base->object->id.name[2]=='t') {
386                                         Material *mat= give_current_material(base->object, base->object->actcol);
387                                         if(mat && mat->mtex[0]) {
388                                                 mat->mtex[0]->tex= tex;
389                                                 /* show alpha in this case */
390                                                 if(tex==NULL || (tex->flag & TEX_PRV_ALPHA)) {
391                                                         mat->mtex[0]->mapto |= MAP_ALPHA;
392                                                         mat->alpha= 0.0f;
393                                                 }
394                                                 else {
395                                                         mat->mtex[0]->mapto &= ~MAP_ALPHA;
396                                                         mat->alpha= 1.0f;
397                                                 }
398                                         }
399                                 }
400                         }
401                 }
402                 else if(id_type==ID_LA) {
403                         Lamp *la= (Lamp *)id;
404                         
405                         if(la && la->type==LA_SUN && (la->sun_effect_type & LA_SUN_EFFECT_SKY)) {
406                                 sce->lay= 1<<MA_ATMOS;
407                                 sce->world= scene->world;
408                                 sce->camera= (Object *)find_object(&pr_main->object, "CameraAtmo");
409                         }
410                         else {
411                                 sce->lay= 1<<MA_LAMP;
412                                 sce->world= NULL;
413                                 sce->camera= (Object *)find_object(&pr_main->object, "Camera");
414                         }
415                         sce->r.mode &= ~R_SHADOW;
416                         
417                         for(base= sce->base.first; base; base= base->next) {
418                                 if(base->object->id.name[2]=='p') {
419                                         if(base->object->type==OB_LAMP)
420                                                 base->object->data= la;
421                                 }
422                         }
423                 }
424                 else if(id_type==ID_WO) {
425                         sce->lay= 1<<MA_SKY;
426                         sce->world= (World *)id;
427                 }
428                 
429                 return sce;
430         }
431         
432         return NULL;
433 }
434
435 void previewrender_progress(void *handle, RenderResult *rr, volatile rcti *renrect)
436 {
437         SpaceButs *sbuts= NULL; // XXX
438         RenderLayer *rl;
439         RenderInfo *ri= sbuts->ri;
440         float ofsx, ofsy;
441         
442         if(renrect) return;
443         
444         rl= rr->layers.first;
445         
446         ofsx= ri->disprect.xmin + rr->tilerect.xmin;
447         ofsy= ri->disprect.ymin + rr->tilerect.ymin;
448         
449         glDrawBuffer(GL_FRONT);
450         glaDrawPixelsSafe_to32(ofsx, ofsy, rr->rectx, rr->recty, rr->rectx, rl->rectf);
451         bglFlush();
452         glDrawBuffer(GL_BACK);
453 }
454
455
456 /* called by interface_icons.c, or by BIF_previewrender_buts or by nodes... */
457 void BIF_previewrender(Scene *scene, struct ID *id, struct RenderInfo *ri, struct ScrArea *area, int pr_method)
458 {
459         SpaceButs *sbuts= NULL; // XXX
460         Render *re;
461         RenderStats *rstats;
462         Scene *sce;
463         int oldx= ri->pr_rectx, oldy= ri->pr_recty;
464         char name [32];
465         
466         if(ri->tottile && ri->curtile>=ri->tottile) return;
467         
468         /* check for return with a new event */
469         if(pr_method!=PR_ICON_RENDER && qtest()) {
470 //              if(area)
471 //                      addafterqueue(area->win, RENDERPREVIEW, 1);
472                 return;
473         }
474         
475         /* get the stuff from the builtin preview dbase */
476 //      sce= preview_prepare_scene(scene, ri, GS(id->name), id, pr_method);
477         if(sce==NULL) return;
478         
479         /* set drawing conditions OK */
480         if(area) {
481                 sbuts= area->spacedata.first;   /* needed for flag */
482                 
483                 set_previewrect(area, ri); // uses UImat
484                 
485                 /* because preview render size can differs */
486                 if(ri->rect && (oldx!=ri->pr_rectx || oldy!=ri->pr_recty)) {
487                         MEM_freeN(ri->rect);
488                         ri->rect= NULL;
489                         ri->curtile= 0;
490                 }
491         }
492         
493 // XXX  sprintf(name, "ButsPreview %d", area?area->win:0);
494         re= RE_GetRender(name);
495         
496         /* full refreshed render from first tile */
497         if(re==NULL || ri->curtile==0) {
498                 
499                 re= RE_NewRender(name);
500                 
501                 /* handle cases */
502                 if(pr_method==PR_DRAW_RENDER) {
503 //                      RE_display_draw_cb(re, previewrender_progress);
504 //                      RE_test_break_cb(re, qtest);
505                         sce->r.scemode |= R_NODE_PREVIEW;
506                         if(sbuts->flag & SB_PRV_OSA)
507                                 sce->r.mode |= R_OSA;
508                         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
509                 }
510                 else if(pr_method==PR_DO_RENDER) {
511 //                      RE_test_break_cb(re, qtest);
512                         sce->r.scemode |= R_NODE_PREVIEW;
513                         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
514                 }
515                 else {  /* PR_ICON_RENDER */
516                         sce->r.scemode &= ~R_NODE_PREVIEW;
517                         sce->r.scemode |= R_NO_IMAGE_LOAD;
518                 }
519                 
520                 /* allocates render result */
521                 RE_InitState(re, NULL, &sce->r, ri->pr_rectx, ri->pr_recty, NULL);
522                 
523                 /* enforce preview image clear */
524                 if(GS(id->name)==ID_MA) {
525                         Material *ma= (Material *)id;
526                         ntreeClearPreview(ma->nodetree);
527                 }
528         }
529         /* entire cycle for render engine */
530         RE_SetCamera(re, sce->camera);
531         RE_Database_FromScene(re, sce, 1);
532         RE_TileProcessor(re, ri->curtile, 0);   // actual render engine
533         RE_Database_Free(re);
534         
535         /* handle results */
536         if(pr_method==PR_ICON_RENDER) {
537                 if(ri->rect==NULL)
538                         ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
539                 RE_ResultGet32(re, ri->rect);
540         }
541         else {
542                 rstats= RE_GetStats(re);
543                 
544                 if(rstats->partsdone!=ri->curtile) {
545                         if(ri->rect==NULL)
546                                 ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
547                         RE_ResultGet32(re, ri->rect);
548                 }
549                 
550                 if(rstats->totpart==rstats->partsdone && rstats->partsdone) {
551                         // allqueues
552                 }
553                 else {
554 //                      if(pr_method==PR_DRAW_RENDER && qtest())
555 //                              addafterqueue(area->win, RENDERPREVIEW, 1);
556                 }
557                 
558                 ri->curtile= rstats->partsdone;
559                 ri->tottile= rstats->totpart;
560         }
561
562         /* unassign the pointers, reset vars */
563 //      preview_prepare_scene(scene, ri, GS(id->name), NULL, 0);
564         
565 }
566
567
568 /* afterqueue call */
569 void BIF_previewrender_buts(Scene *scene, SpaceButs *sbuts)
570 {
571 //      ScrArea *sa= NULL; // XXX
572         ARegion *ar= NULL; // XXX
573         uiBlock *block;
574         struct ID* id = 0;
575 //      struct ID* idfrom = 0;
576         struct ID* idshow = 0;
577         Object *ob;
578         
579         if (!sbuts->ri) return;
580         
581         
582 //      block= uiFindOpenPanelBlockName(&sa->uiblocks, "Preview");
583         if(block==NULL) return;
584         
585         ob= ((scene->basact)? (scene->basact)->object: 0);
586         
587         /* we cant trust this global lockpoin.. for example with headerless window */
588 //      buttons_active_id(&id, &idfrom);
589         sbuts->lockpoin= id;
590         
591         if(sbuts->mainb==CONTEXT_SHADING) {
592                 int tab= TAB_SHADING_MAT; // XXX sbuts->tab[CONTEXT_SHADING];
593                 
594                 if(tab==TAB_SHADING_MAT) 
595                         idshow = sbuts->lockpoin;
596                 else if(tab==TAB_SHADING_TEX) 
597                         idshow = sbuts->lockpoin;
598                 else if(tab==TAB_SHADING_LAMP) {
599                         if(ob && ob->type==OB_LAMP) idshow= ob->data;
600                 }
601                 else if(tab==TAB_SHADING_WORLD)
602                         idshow = sbuts->lockpoin;
603         }
604         else if(sbuts->mainb==CONTEXT_OBJECT) {
605                 if(ob && ob->type==OB_LAMP) idshow = ob->data;
606         }
607         
608         if (idshow) {
609                 BKE_icon_changed(BKE_icon_getid(idshow));
610 //              uiPanelPush(block);
611 //              BIF_previewrender(scene, idshow, sbuts->ri, sbuts->area, PR_DRAW_RENDER);
612 //              uiPanelPop(block);
613                 end_previewrect(ar);
614         }
615         else {
616                 /* no active block to draw. But we do draw black if possible */
617                 if(sbuts->ri->rect) {
618                         memset(sbuts->ri->rect, 0, sizeof(int)*sbuts->ri->pr_rectx*sbuts->ri->pr_recty);
619                         sbuts->ri->tottile= 10000;
620 //                      addqueue(sa->win, REDRAW, 1);
621                 }
622                 return;
623         }
624 }
625
626 /* new UI convention: draw is in pixel space already. */
627 /* uses ROUNDBOX button in block to get the rect */
628 void ED_preview_draw(const bContext *C, void *idp, rcti *rect)
629 {
630         ScrArea *sa= CTX_wm_area(C);
631         SpaceButs *sbuts= sa->spacedata.first;
632         RenderResult rres;
633         int newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
634         int ok= 0;
635         char name[32];
636         
637         sprintf(name, "Preview %p", sa);
638         BLI_lock_malloc_thread();
639         RE_GetResultImage(RE_GetRender(name), &rres);
640
641         if(rres.rectf) {
642                 if(rres.rectx==newx && rres.recty==newy) {
643                         glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
644                         glEnable(GL_BLEND);
645                         
646                         glaDrawPixelsSafe(rect->xmin, rect->ymin, rres.rectx, rres.recty, rres.rectx, GL_RGBA, GL_FLOAT, rres.rectf);
647                         ok= 1;
648                         
649                         glDisable(GL_BLEND);
650                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
651                 }
652         }
653         BLI_unlock_malloc_thread();
654
655         /* check for spacetype... */
656         if(sbuts->spacetype==SPACE_BUTS && sbuts->preview) {
657                 sbuts->preview= 0;
658                 ok= 0;
659         }
660         
661         if(ok==0) {
662                 printf("added shader job\n");
663                 ED_preview_shader_job(C, sa, idp, newx, newy);
664         }
665         
666 }
667
668 /* *************************** Preview for 3d window *********************** */
669
670 void view3d_previewrender_progress(RenderResult *rr, volatile rcti *renrect)
671 {
672 //      ScrArea *sa= NULL; // XXX
673 //      View3D *v3d= NULL; // XXX
674         RenderLayer *rl;
675         int ofsx, ofsy;
676         
677         if(renrect) return;
678         
679         rl= rr->layers.first;
680         
681         /* this case is when we render envmaps... */
682 //      if(rr->rectx > v3d->ri->pr_rectx || rr->recty > v3d->ri->pr_recty)
683 //              return;
684         
685 //      ofsx= v3d->ri->disprect.xmin + rr->tilerect.xmin;
686 //      ofsy= v3d->ri->disprect.ymin + rr->tilerect.ymin;
687         
688         glDrawBuffer(GL_FRONT);
689 //      glaDefine2DArea(&sa->winrct);
690         glaDrawPixelsSafe_to32(ofsx, ofsy, rr->rectx, rr->recty, rr->rectx, rl->rectf);
691         bglFlush();
692         glDrawBuffer(GL_BACK);
693
694 }
695
696 void BIF_view3d_previewrender_signal(ScrArea *sa, short signal)
697 {
698 #if 0
699         View3D *v3d= sa->spacedata.first;
700         
701         /* this can be called from other window... solve! */
702         if(sa->spacetype!=SPACE_VIEW3D)
703                 return; // XXX
704            
705         if(v3d && v3d->ri) {
706                 RenderInfo *ri= v3d->ri;
707                 ri->status &= ~signal;
708                 ri->curtile= 0;
709                 //printf("preview signal %d\n", signal);
710                 if(ri->re && (signal & PR_DBASE))
711                         RE_Database_Free(ri->re);
712
713 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
714         }
715 #endif
716 }
717
718 void BIF_view3d_previewrender_free(View3D *v3d)
719 {
720 #if 0
721         if(v3d->ri) {
722                 RenderInfo *ri= v3d->ri;
723                 if(ri->re) {
724 //                      printf("free render\n");
725                         RE_Database_Free(ri->re);
726                         RE_FreeRender(ri->re);
727                         ri->re= NULL;
728                 }
729                 if (v3d->ri->rect) MEM_freeN(v3d->ri->rect);
730                 MEM_freeN(v3d->ri);
731                 v3d->ri= NULL;
732         }
733 #endif
734 }
735
736 /* returns 1 if OK, do not call while in panel space!  */
737 static int view3d_previewrender_get_rects(ScrArea *sa, rctf *viewplane, RenderInfo *ri, float *clipsta, float *clipend, int *ortho, float *pixsize)
738 {
739         View3D *v3d= NULL; // XXX
740         RegionView3D *rv3d= NULL; // XXX
741         int rectx, recty;
742 //      uiBlock *block;
743         
744 //      block= uiFindOpenPanelBlockName(&sa->uiblocks, "Preview");
745 //      if(block==NULL) return 0;
746         
747         /* calculate preview rect size */
748 //      BLI_init_rctf(viewplane, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
749 //      uiPanelPush(block);
750 //      ui_graphics_to_window_rct(sa->win, viewplane, &ri->disprect);
751 //      uiPanelPop(block);
752         
753         /* correction for gla draw */
754 //      BLI_translate_rcti(&ri->disprect, -sa->winrct.xmin, -sa->winrct.ymin);
755         
756         *ortho= get_view3d_viewplane(v3d, rv3d, sa->winx, sa->winy, viewplane, clipsta, clipend, pixsize);
757
758         rectx= ri->disprect.xmax - ri->disprect.xmin;
759         recty= ri->disprect.ymax - ri->disprect.ymin;
760         
761         if(rectx<4 || recty<4) return 0;
762         
763         if(ri->rect && (rectx!=ri->pr_rectx || recty!=ri->pr_recty)) {
764                 MEM_freeN(ri->rect);
765                 ri->rect= NULL;
766                 ri->curtile= 0;
767                 printf("changed size\n");
768         }
769         ri->pr_rectx= rectx;
770         ri->pr_recty= recty;
771         
772         return 1;
773 }
774
775 /* called before a panel gets moved/scaled, makes sure we can see through */
776 void BIF_view3d_previewrender_clear(ScrArea *sa)
777 {
778 #if 0
779         View3D *v3d= sa->spacedata.first;
780
781         if(v3d->ri) {
782                 RenderInfo *ri= v3d->ri;
783                 ri->curtile= 0;
784                 if(ri->rect)
785                         MEM_freeN(ri->rect);
786                 ri->rect= NULL;
787         }
788 #endif
789 }
790
791 /* afterqueue call */
792 void BIF_view3d_previewrender(Scene *scene, ScrArea *sa)
793 {
794         bContext *C= NULL;
795         View3D *v3d= sa->spacedata.first;
796         RegionView3D *rv3d= NULL; // XXX
797         Render *re;
798         RenderInfo *ri; /* preview struct! */
799         RenderStats *rstats;
800         RenderData rdata;
801         rctf viewplane;
802         float clipsta, clipend, pixsize;
803         int orth;
804         
805         /* first get the render info right */
806 //      if (!v3d->ri) {
807 //              ri= v3d->ri= MEM_callocN(sizeof(RenderInfo), "butsrenderinfo");
808 //              ri->tottile= 10000;
809 //      }
810 //      ri= v3d->ri;
811         
812         if(0==view3d_previewrender_get_rects(sa, &viewplane, ri, &clipsta, &clipend, &orth, &pixsize))
813                 return;
814         
815         /* render is finished, so return */
816         if(ri->tottile && ri->curtile>=ri->tottile) return;
817
818         /* or return with a new event */
819         if(qtest()) {
820 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
821                 return;
822         }
823         //printf("Enter previewrender\n");
824         /* ok, are we rendering all over? */
825         if(ri->re==NULL) {
826                 char name[32];
827                 
828                 ri->status= 0;
829                 
830                 sprintf(name, "View3dPreview %p", sa);
831                 re= ri->re= RE_NewRender(name);
832                 //RE_display_draw_cb(re, view3d_previewrender_progress);
833                 //RE_stats_draw_cb(re, view3d_previewrender_stats);
834                 //RE_test_break_cb(re, qtest);
835                 
836                 /* no osa, blur, seq, layers, etc for preview render */
837                 rdata= scene->r;
838                 rdata.mode &= ~(R_OSA|R_MBLUR);
839                 rdata.scemode &= ~(R_DOSEQ|R_DOCOMP|R_FREE_IMAGE);
840                 rdata.layers.first= rdata.layers.last= NULL;
841                 rdata.renderer= R_INTERN;
842                  
843                 RE_InitState(re, NULL, &rdata, sa->winx, sa->winy, &ri->disprect);
844         
845                 if(orth)
846                         RE_SetOrtho(re, &viewplane, clipsta, clipend);
847                 else
848                         RE_SetWindow(re, &viewplane, clipsta, clipend);
849                 RE_SetPixelSize(re, pixsize);
850                 
851                 /* until here are no escapes */
852                 ri->status |= PR_DISPRECT;
853                 ri->curtile= 0;
854                 //printf("new render\n");
855         }
856
857         re= ri->re;
858         
859         PIL_sleep_ms(100);      /* wait 0.1 second if theres really no event... */
860         if(qtest()==0)  {
861                 
862                 /* check status */
863                 if((ri->status & PR_DISPRECT)==0) {
864                         RE_SetDispRect(ri->re, &ri->disprect);
865                         if(orth)
866                                 RE_SetOrtho(ri->re, &viewplane, clipsta, clipend);
867                         else
868                                 RE_SetWindow(ri->re, &viewplane, clipsta, clipend);
869                         RE_SetPixelSize(re, pixsize);
870                         ri->status |= PR_DISPRECT;
871                         ri->curtile= 0;
872                         //printf("disprect update\n");
873                 }
874                 if((ri->status & PR_DBASE)==0) {
875                         unsigned int lay= scene->lay;
876                         
877                         RE_SetView(re, rv3d->viewmat);
878                         
879                         /* allow localview render for objects with lights in normal layers */
880                         if(v3d->lay & 0xFF000000)
881                                 scene->lay |= v3d->lay;
882                         else scene->lay= v3d->lay;
883                         
884                         RE_Database_FromScene(re, scene, 0);            // 0= dont use camera view
885                         scene->lay= lay;
886                         
887                         rstats= RE_GetStats(re);
888                         if(rstats->convertdone) 
889                                 ri->status |= PR_DBASE|PR_PROJECTED|PR_ROTATED;
890                         ri->curtile= 0;
891                         
892                         /* database can have created render-resol data... */
893                         if(rstats->convertdone) 
894                                 ED_anim_dag_flush_update(C); // <--- only current scene XXX
895                         
896                         //printf("dbase update\n");
897                 }
898                 if((ri->status & PR_PROJECTED)==0) {
899                         if(ri->status & PR_DBASE) {
900                                 if(orth)
901                                         RE_SetOrtho(ri->re, &viewplane, clipsta, clipend);
902                                 else
903                                         RE_SetWindow(ri->re, &viewplane, clipsta, clipend);
904                                 RE_DataBase_ApplyWindow(re);
905                                 ri->status |= PR_PROJECTED;
906                         }
907                         ri->curtile= 0;
908                         //printf("project update\n");
909                 }
910         
911                 /* OK, can we enter render code? */
912                 if(ri->status==(PR_DISPRECT|PR_DBASE|PR_PROJECTED|PR_ROTATED)) {
913                         //printf("curtile %d tottile %d\n", ri->curtile, ri->tottile);
914                         RE_TileProcessor(ri->re, ri->curtile, 0);
915         
916                         if(ri->rect==NULL)
917                                 ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "preview view3d rect");
918                         
919                         RE_ResultGet32(ri->re, ri->rect);
920                 }
921                 
922                 rstats= RE_GetStats(ri->re);
923 //              if(rstats->totpart==rstats->partsdone && rstats->partsdone)
924 //                      addqueue(sa->win, REDRAW, 1);
925 //              else
926 //                      addafterqueue(sa->win, RENDERPREVIEW, 1);
927                 
928                 ri->curtile= rstats->partsdone;
929                 ri->tottile= rstats->totpart;
930         }
931         else {
932 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
933         }
934         
935         //printf("\n");
936 }
937
938 /* in panel space! */
939 static void view3d_previewdraw_rect(ScrArea *sa, uiBlock *block, RenderInfo *ri)
940 {
941 //      rctf dispf;
942         
943         if(ri->rect==NULL)
944                 return;
945         
946 //      BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
947 //      ui_graphics_to_window_rct(sa->win, &dispf, &ri->disprect);
948
949         /* correction for gla draw */
950 //      BLI_translate_rcti(&ri->disprect, -sa->winrct.xmin, -sa->winrct.ymin);
951         
952         /* when panel scale changed, free rect */
953         if(ri->disprect.xmax-ri->disprect.xmin != ri->pr_rectx ||
954            ri->disprect.ymax-ri->disprect.ymin != ri->pr_recty) {
955                 MEM_freeN(ri->rect);
956                 ri->rect= NULL;
957         }
958         else {
959 //              glaDefine2DArea(&sa->winrct);
960                 glaDrawPixelsSafe(ri->disprect.xmin, ri->disprect.ymin, ri->pr_rectx, ri->pr_recty, ri->pr_rectx, GL_RGBA, GL_UNSIGNED_BYTE, ri->rect);
961         }       
962 }
963
964 /* is panel callback, supposed to be called with correct panel offset matrix */
965 void BIF_view3d_previewdraw(struct ScrArea *sa, struct uiBlock *block)
966 {
967         RegionView3D *rv3d= NULL;
968
969 //      if (v3d->ri==NULL || v3d->ri->rect==NULL) 
970 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
971 //      else {
972                 view3d_previewdraw_rect(sa, block, rv3d->ri);
973 //              if(v3d->ri->curtile==0) 
974 //                      addafterqueue(sa->win, RENDERPREVIEW, 1);
975 //      }
976 }
977
978
979 /* **************************** New preview system ****************** */
980
981 /* inside thread, called by renderer, sets job update value */
982 static void shader_preview_draw(void *spv, RenderResult *rr, volatile struct rcti *rect)
983 {
984         ShaderPreview *sp= spv;
985         
986         *(sp->do_update)= 1;
987 }
988
989 /* called by renderer, checks job value */
990 static int shader_preview_break(void *spv)
991 {
992         ShaderPreview *sp= spv;
993         
994         return *(sp->stop);
995 }
996
997 /* outside thread, called before redraw notifiers, it moves finished preview over */
998 static void shader_preview_updatejob(void *spv)
999 {
1000 //      ShaderPreview *sp= spv;
1001         
1002 }
1003
1004 /* runs inside thread */
1005 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
1006 {
1007         ShaderPreview *sp= customdata;
1008         Render *re;
1009         Scene *sce;
1010         float oldlens;
1011         char name [32];
1012
1013         sp->stop= stop;
1014         sp->do_update= do_update;
1015         
1016         /* get the stuff from the builtin preview dbase */
1017         sce= preview_prepare_scene(sp->scene, GS(sp->id->name), sp);
1018         if(sce==NULL) return;
1019         
1020         sprintf(name, "Preview %p", sp->owner);
1021         re= RE_GetRender(name);
1022         
1023         /* full refreshed render from first tile */
1024         if(re==NULL)
1025                 re= RE_NewRender(name);
1026                 
1027         /* sce->r gets copied in RE_InitState! */
1028         if(sp->pr_method==PR_DO_RENDER) {
1029                 sce->r.scemode |= R_NODE_PREVIEW;
1030                 sce->r.scemode &= ~R_NO_IMAGE_LOAD;
1031                 sce->r.mode |= R_OSA;
1032         }
1033         else {  /* PR_ICON_RENDER */
1034                 sce->r.scemode &= ~R_NODE_PREVIEW;
1035                 sce->r.scemode |= R_NO_IMAGE_LOAD;
1036         }
1037
1038         /* allocates or re-uses render result */
1039         RE_InitState(re, NULL, &sce->r, sp->sizex, sp->sizey, NULL);
1040
1041         /* callbacs are cleared on GetRender() */
1042         if(sp->pr_method==PR_DO_RENDER) {
1043                 RE_display_draw_cb(re, sp, shader_preview_draw);
1044                 RE_test_break_cb(re, sp, shader_preview_break);
1045         }
1046         /* lens adjust */
1047         oldlens= ((Camera *)sce->camera->data)->lens;
1048         ((Camera *)sce->camera->data)->lens *= (float)sp->sizey/(float)sp->sizex;
1049
1050         /* entire cycle for render engine */
1051         RE_SetCamera(re, sce->camera);
1052         RE_Database_FromScene(re, sce, 1);
1053         RE_TileProcessor(re, 0, 1);     // actual render engine
1054         RE_Database_Free(re);
1055
1056         ((Camera *)sce->camera->data)->lens= oldlens;
1057         *do_update= 1;
1058
1059         /* handle results */
1060         if(sp->pr_method==PR_ICON_RENDER) {
1061                 //if(ri->rect==NULL)
1062                 //      ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
1063                 //RE_ResultGet32(re, ri->rect);
1064         }
1065         else {
1066                 /* validate owner */
1067                 //if(ri->rect==NULL)
1068                 //      ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
1069                 //RE_ResultGet32(re, ri->rect);
1070         }
1071
1072         /* unassign the pointers, reset vars */
1073         preview_prepare_scene(sp->scene, GS(sp->id->name), NULL);
1074
1075 }
1076
1077 static void shader_preview_free(void *customdata)
1078 {
1079         ShaderPreview *sp= customdata;
1080         
1081         MEM_freeN(sp);
1082 }
1083
1084 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, int sizex, int sizey)
1085 {
1086         wmJob *steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner);
1087         ShaderPreview *sp= MEM_callocN(sizeof(ShaderPreview), "shader preview");
1088
1089         /* customdata for preview thread */
1090         sp->scene= CTX_data_scene(C);
1091         sp->owner= owner;
1092         sp->sizex= sizex;
1093         sp->sizey= sizey;
1094         sp->pr_method= PR_DO_RENDER;
1095         sp->id = id;
1096         
1097         /* setup job */
1098         WM_jobs_customdata(steve, sp, shader_preview_free);
1099         WM_jobs_timer(steve, 0.1, NC_MATERIAL, NC_MATERIAL);
1100         WM_jobs_callbacks(steve, shader_preview_startjob, NULL, shader_preview_updatejob);
1101         
1102         WM_jobs_start(CTX_wm_manager(C), steve);
1103 }
1104
1105