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