This prevents to assign the built-in Images "Render Result" or "Compositor"
[blender.git] / source / blender / src / drawimage.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  */
32
33 #include <math.h>
34 #include <string.h>
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #ifdef WIN32
41 #include <io.h>
42 #else
43 #include <unistd.h>
44 #endif   
45 #include "MEM_guardedalloc.h"
46
47 #include "BLI_arithb.h"
48 #include "BLI_blenlib.h"
49
50 #include "IMB_imbuf.h"
51 #include "IMB_imbuf_types.h"
52
53 #include "DNA_camera_types.h"
54 #include "DNA_color_types.h"
55 #include "DNA_image_types.h"
56 #include "DNA_mesh_types.h"
57 #include "DNA_meshdata_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_packedFile_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_screen_types.h"
62 #include "DNA_space_types.h"
63 #include "DNA_userdef_types.h"
64
65 #include "BKE_colortools.h"
66 #include "BKE_utildefines.h"
67 #include "BKE_global.h"
68 #include "BKE_library.h"
69 #include "BKE_main.h"
70 #include "BKE_mesh.h"
71 #include "BKE_node.h"
72 #include "BKE_image.h"
73 #include "BKE_DerivedMesh.h"
74 #include "BKE_displist.h"
75 #include "BKE_object.h"
76
77 #include "BDR_editface.h"
78 #include "BDR_drawobject.h"
79 #include "BDR_drawmesh.h"
80 #include "BDR_imagepaint.h"
81
82 #include "BIF_cursors.h"
83 #include "BIF_gl.h"
84 #include "BIF_graphics.h"
85 #include "BIF_mywindow.h"
86 #include "BIF_drawimage.h"
87 #include "BIF_resources.h"
88 #include "BIF_interface.h"
89 #include "BIF_interface_icons.h"
90 #include "BIF_editsima.h"
91 #include "BIF_glutil.h"
92 #include "BIF_renderwin.h"
93 #include "BIF_space.h"
94 #include "BIF_screen.h"
95 #include "BIF_transform.h"
96
97 #include "BSE_drawipo.h"
98 #include "BSE_headerbuttons.h"
99 #include "BSE_trans_types.h"
100 #include "BSE_view.h"
101
102 #include "RE_pipeline.h"
103 #include "BMF_Api.h"
104
105 /* Modules used */
106 #include "mydevice.h"
107 #include "blendef.h"
108 #include "butspace.h"  // event codes
109 #include "winlay.h"
110
111 #include "interface.h"  /* bad.... but preview code needs UI info. Will solve... (ton) */
112
113 static unsigned char *alloc_alpha_clone_image(int *width, int *height)
114 {
115         unsigned int size, alpha;
116         unsigned char *rect, *cp;
117
118         if(!Gip.clone.image)
119                 return NULL;
120
121         if(!Gip.clone.image->ibuf)
122                 load_image(Gip.clone.image, IB_rect, G.sce, G.scene->r.cfra);
123
124         if(!Gip.clone.image->ibuf || !Gip.clone.image->ibuf->rect)
125                 return NULL;
126
127         rect= MEM_dupallocN(Gip.clone.image->ibuf->rect);
128
129         if(!rect)
130                 return NULL;
131
132         *width= Gip.clone.image->ibuf->x;
133         *height= Gip.clone.image->ibuf->y;
134
135         size= (*width)*(*height);
136         alpha= (unsigned char)255*Gip.clone.alpha;
137         cp= rect;
138
139         while(size-- > 0) {
140                 cp[3]= alpha;
141                 cp += 4;
142         }
143
144         return rect;
145 }
146
147 static void setcloneimage()
148 {
149         if(G.sima->menunr > 0) {
150                 Image *ima= (Image*)BLI_findlink(&G.main->image, G.sima->menunr-1);
151
152                 if(ima) {
153                         Gip.clone.image= ima;
154                         Gip.clone.offset[0]= Gip.clone.offset[0]= 0.0;
155                 }
156         }
157 }
158
159 static int image_preview_active(ScrArea *sa, float *xim, float *yim)
160 {
161         SpaceImage *sima= sa->spacedata.first;
162         
163         /* only when compositor shows, and image handler set */
164         if(sima->image == (Image *)find_id("IM", "Compositor")) {
165                 short a;
166         
167                 for(a=0; a<SPACE_MAXHANDLER; a+=2) {
168                         if(sima->blockhandler[a] == IMAGE_HANDLER_PREVIEW) {
169                                 if(xim) *xim= (G.scene->r.size*G.scene->r.xsch)/100;
170                                 if(yim) *yim= (G.scene->r.size*G.scene->r.ysch)/100;
171                                 return 1;
172                         }
173                 }
174         }
175         return 0;
176 }
177
178
179 /**
180  * Sets up the fields of the View2D member of the SpaceImage struct
181  * This routine can be called in two modes:
182  * mode == 'f': float mode (0.0 - 1.0)
183  * mode == 'p': pixel mode (0 - size)
184  *
185  * @param     sima  the image space to update
186  * @param     mode  the mode to use for the update
187  * @return    void
188  *   
189  */
190 void calc_image_view(SpaceImage *sima, char mode)
191 {
192         float xim=256, yim=256;
193         float x1, y1;
194         float zoom;
195         
196         if(image_preview_active(curarea, &xim, &yim));
197         else if(sima->image) {
198                 if(sima->image->ibuf) {
199                         xim= sima->image->ibuf->x;
200                         yim= sima->image->ibuf->y;
201                 }
202                 else if( BLI_streq(sima->image->name, "Render Result") ) {
203                         /* not very important, just nice */
204                         xim= (G.scene->r.xsch*G.scene->r.size)/100;
205                         yim= (G.scene->r.ysch*G.scene->r.size)/100;
206                 }
207         }
208                 
209         sima->v2d.tot.xmin= 0;
210         sima->v2d.tot.ymin= 0;
211         sima->v2d.tot.xmax= xim;
212         sima->v2d.tot.ymax= yim;
213         
214         sima->v2d.mask.xmin= sima->v2d.mask.ymin= 0;
215         sima->v2d.mask.xmax= curarea->winx;
216         sima->v2d.mask.ymax= curarea->winy;
217
218
219         /* Which part of the image space do we see? */
220         /* Same calculation as in lrectwrite: area left and down*/
221         x1= curarea->winrct.xmin+(curarea->winx-sima->zoom*xim)/2;
222         y1= curarea->winrct.ymin+(curarea->winy-sima->zoom*yim)/2;
223
224         x1-= sima->zoom*sima->xof;
225         y1-= sima->zoom*sima->yof;
226
227         /* float! */
228         zoom= sima->zoom;
229         
230         /* relative display right */
231         sima->v2d.cur.xmin= ((curarea->winrct.xmin - (float)x1)/zoom);
232         sima->v2d.cur.xmax= sima->v2d.cur.xmin + ((float)curarea->winx/zoom);
233         
234         /* relative display left */
235         sima->v2d.cur.ymin= ((curarea->winrct.ymin-(float)y1)/zoom);
236         sima->v2d.cur.ymax= sima->v2d.cur.ymin + ((float)curarea->winy/zoom);
237         
238         if(mode=='f') {         
239                 sima->v2d.cur.xmin/= xim;
240                 sima->v2d.cur.xmax/= xim;
241                 sima->v2d.cur.ymin/= yim;
242                 sima->v2d.cur.ymax/= yim;
243         }
244 }
245
246 /* check for facelesect, and set active image */
247 void what_image(SpaceImage *sima)
248 {
249         TFace *activetf;
250         Mesh *me;
251                 
252         if(sima->mode==SI_TEXTURE) {
253                 
254                 if(sima->image && BLI_streq(sima->image->name, "Render Result")) {
255                         if(sima->image->ibuf==NULL) {
256                                 RenderResult rres;
257                                 
258                                 /* make ibuf if needed, and initialize it */
259                                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
260                                 if(rres.rectf || rres.rect32) {
261                                         ImBuf *ibuf= sima->image->ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0, 0);
262                                         
263                                         ibuf->x= rres.rectx;
264                                         ibuf->y= rres.recty;
265                                         ibuf->rect= rres.rect32;
266                                         ibuf->rect_float= rres.rectf;
267                                 }
268                         }
269                 }
270                 else if((G.f & G_FACESELECT)) {
271                         
272                         sima->image= NULL;
273                         me= get_mesh(OBACT);
274                         activetf = get_active_tface();
275                         
276                         if(me && me->tface && activetf && activetf->mode & TF_TEX) {
277                                 sima->image= activetf->tpage;
278                                 
279                                 if(sima->flag & SI_EDITTILE);
280                                 else sima->curtile= activetf->tile;
281                                 
282                                 if(sima->image) {
283                                         if(activetf->mode & TF_TILES)
284                                                 sima->image->tpageflag |= IMA_TILES;
285                                         else sima->image->tpageflag &= ~IMA_TILES;
286                                 }
287                         }
288                 }
289                 
290         }
291 }
292
293 /* called to assign images to UV faces */
294 void image_changed(SpaceImage *sima, int dotile)
295 {
296         TFace *tface;
297         Mesh *me;
298         int a;
299         
300         if(sima->mode==SI_TEXTURE) {
301                 
302                 if(G.f & G_FACESELECT) {
303                         
304                         /* exception images, name rules are actually weak... */
305                         if(sima->image) {
306                                 if(BLI_streq(sima->image->name, "Render Result"))
307                                         return;
308                                 if(BLI_streq(sima->image->name, "Composite"))
309                                         return;
310                         }
311                         
312                         me= get_mesh(OBACT);
313                         if(me && me->tface) {
314                                 
315                                 tface= me->tface;
316                                 a= me->totface;
317                                 while(a--) {
318                                         if(tface->flag & TF_SELECT) {
319                                                 
320                                                 if(dotile==2) {
321                                                         tface->mode &= ~TF_TILES;
322                                                 }
323                                                 else {
324                                                         tface->tpage= sima->image;
325                                                         tface->mode |= TF_TEX;
326                                                 
327                                                         if(dotile) tface->tile= sima->curtile;
328                                                 }
329                                                 
330                                                 if(sima->image) {
331                                                         if(sima->image->tpageflag & IMA_TILES) tface->mode |= TF_TILES;
332                                                         else tface->mode &= ~TF_TILES;
333                                                 
334                                                         if(sima->image->id.us==0) sima->image->id.us= 1;
335                                                 }
336                                         }
337                                         tface++;
338                                 }
339
340                                 object_uvs_changed(OBACT);
341                                 allqueue(REDRAWBUTSEDIT, 0);
342                         }
343                 }
344         }
345 }
346
347
348 void uvco_to_areaco(float *vec, short *mval)
349 {
350         float x, y;
351
352         mval[0]= IS_CLIPPED;
353         
354         x= (vec[0] - G.v2d->cur.xmin)/(G.v2d->cur.xmax-G.v2d->cur.xmin);
355         y= (vec[1] - G.v2d->cur.ymin)/(G.v2d->cur.ymax-G.v2d->cur.ymin);
356
357         if(x>=0.0 && x<=1.0) {
358                 if(y>=0.0 && y<=1.0) {          
359                         mval[0]= G.v2d->mask.xmin + x*(G.v2d->mask.xmax-G.v2d->mask.xmin);
360                         mval[1]= G.v2d->mask.ymin + y*(G.v2d->mask.ymax-G.v2d->mask.ymin);
361                 }
362         }
363 }
364
365 void uvco_to_areaco_noclip(float *vec, int *mval)
366 {
367         float x, y;
368
369         mval[0]= IS_CLIPPED;
370         
371         x= (vec[0] - G.v2d->cur.xmin)/(G.v2d->cur.xmax-G.v2d->cur.xmin);
372         y= (vec[1] - G.v2d->cur.ymin)/(G.v2d->cur.ymax-G.v2d->cur.ymin);
373
374         x= G.v2d->mask.xmin + x*(G.v2d->mask.xmax-G.v2d->mask.xmin);
375         y= G.v2d->mask.ymin + y*(G.v2d->mask.ymax-G.v2d->mask.ymin);
376         
377         mval[0]= x;
378         mval[1]= y;
379 }
380
381 void draw_tfaces(void)
382 {
383         TFace *tface,*activetface = NULL;
384         MFace *mface,*activemface = NULL;
385         Mesh *me;
386         int a;
387         char col1[4], col2[4];
388         float pointsize= BIF_GetThemeValuef(TH_VERTEX_SIZE);
389         
390         if(G.f & G_FACESELECT) {
391                 me= get_mesh((G.scene->basact) ? (G.scene->basact->object) : 0);
392                 if(me && me->tface) {
393                         calc_image_view(G.sima, 'f');   /* float */
394                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
395                         glLoadIdentity();
396                         
397                         /* draw shadow mesh */
398                         if((G.sima->flag & SI_DRAWSHADOW) && !(G.obedit==OBACT)){
399                                 int dmNeedsFree;
400                                 DerivedMesh *dm = mesh_get_derived_final(OBACT, &dmNeedsFree);
401
402                                 glColor3ub(112, 112, 112);
403                                 if (dm->drawUVEdges) dm->drawUVEdges(dm);
404
405                                 if (dmNeedsFree) dm->release(dm);
406                         }
407                         else if(G.sima->flag & SI_DRAWSHADOW){          
408                                 tface= me->tface;
409                                 mface= me->mface;
410                                 a= me->totface;                 
411                                 while(a--) {
412                                         if(!(tface->flag & TF_HIDE)) {
413                                                 glColor3ub(112, 112, 112);
414                                                 glBegin(GL_LINE_LOOP);
415                                                 glVertex2fv(tface->uv[0]);
416                                                 glVertex2fv(tface->uv[1]);
417                                                 glVertex2fv(tface->uv[2]);
418                                                 if(mface->v4) glVertex2fv(tface->uv[3]);
419                                                 glEnd();
420                                         } 
421                                         tface++;
422                                         mface++;                                        
423                                 }
424                         }
425                         
426                         /* draw transparent faces */
427                         if(G.f & G_DRAWFACES) {
428                                 BIF_GetThemeColor4ubv(TH_FACE, col1);
429                                 BIF_GetThemeColor4ubv(TH_FACE_SELECT, col2);
430                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
431                                 glEnable(GL_BLEND);
432                                 tface= me->tface;
433                                 mface= me->mface;
434                                 a= me->totface;                 
435                                 while(a--) {
436                                         if(tface->flag & TF_SELECT) {
437                                                 if(!(~tface->flag & (TF_SEL1|TF_SEL2|TF_SEL3)) &&
438                                                    (!mface->v4 || tface->flag & TF_SEL4))
439                                                         glColor4ubv(col2);
440                                                 else
441                                                         glColor4ubv(col1);
442                                                         
443                                                 glBegin(mface->v4?GL_QUADS:GL_TRIANGLES);
444                                                         glVertex2fv(tface->uv[0]);
445                                                         glVertex2fv(tface->uv[1]);
446                                                         glVertex2fv(tface->uv[2]);
447                                                         if(mface->v4) glVertex2fv(tface->uv[3]);
448                                                 glEnd();
449                                         }
450                                         tface++;
451                                         mface++;                                        
452                                 }
453                                 glDisable(GL_BLEND);
454                         }
455
456
457                         tface= me->tface;
458                         mface= me->mface;
459                         a= me->totface;
460                         while(a--) {
461                                 if(tface->flag & TF_SELECT) {
462                                         if(tface->flag & TF_ACTIVE){
463                                                 activetface= tface; 
464                                                 activemface= mface; 
465                                         }
466
467                                         cpack(0x0);
468                                         glBegin(GL_LINE_LOOP);
469                                                 glVertex2fv(tface->uv[0]);
470                                                 glVertex2fv(tface->uv[1]);
471                                                 glVertex2fv(tface->uv[2]);
472                                                 if(mface->v4) glVertex2fv(tface->uv[3]);
473                                         glEnd();
474                                 
475                                         setlinestyle(2);
476                                         cpack(0xFFFFFF);
477                                         glBegin(GL_LINE_STRIP);
478                                                 glVertex2fv(tface->uv[0]);
479                                                 glVertex2fv(tface->uv[1]);
480                                         glEnd();
481
482                                         glBegin(GL_LINE_STRIP);
483                                                 glVertex2fv(tface->uv[0]);
484                                                 if(mface->v4) glVertex2fv(tface->uv[3]);
485                                                 else glVertex2fv(tface->uv[2]);
486                                         glEnd();
487         
488                                         glBegin(GL_LINE_STRIP);
489                                                 glVertex2fv(tface->uv[1]);
490                                                 glVertex2fv(tface->uv[2]);
491                                                 if(mface->v4) glVertex2fv(tface->uv[3]);
492                                         glEnd();
493                                         setlinestyle(0);
494                                 }
495                                         
496                                 tface++;
497                                 mface++;
498                         }
499
500                         /* draw active face edges */
501                         if (activetface){
502                                 /* colors: R=u G=v */
503
504                                 setlinestyle(2);
505                                 tface=activetface; 
506                                 mface=activemface; 
507
508                                 cpack(0x0);
509                                 glBegin(GL_LINE_LOOP);
510                                 glVertex2fv(tface->uv[0]);
511                                         glVertex2fv(tface->uv[1]);
512                                         glVertex2fv(tface->uv[2]);
513                                         if(mface->v4) glVertex2fv(tface->uv[3]);
514                                 glEnd();
515                                         
516                                 cpack(0xFF00);
517                                 glBegin(GL_LINE_STRIP);
518                                         glVertex2fv(tface->uv[0]);
519                                         glVertex2fv(tface->uv[1]);
520                                 glEnd();
521
522                                 cpack(0xFF);
523                                 glBegin(GL_LINE_STRIP);
524                                         glVertex2fv(tface->uv[0]);
525                                         if(mface->v4) glVertex2fv(tface->uv[3]);
526                                         else glVertex2fv(tface->uv[2]);
527                                 glEnd();
528
529                                 cpack(0xFFFFFF);
530                                 glBegin(GL_LINE_STRIP);
531                                         glVertex2fv(tface->uv[1]);
532                                         glVertex2fv(tface->uv[2]);
533                                         if(mface->v4) glVertex2fv(tface->uv[3]);
534                                 glEnd();
535                                 
536                                 setlinestyle(0);
537                         }
538
539             /* unselected uv's */
540                         BIF_ThemeColor(TH_VERTEX);
541                         glPointSize(pointsize);
542
543                         bglBegin(GL_POINTS);
544                         tface= me->tface;
545                         mface= me->mface;
546                         a= me->totface;
547                         while(a--) {
548                                 if(tface->flag & TF_SELECT) {
549                                         
550                                         if(tface->flag & TF_SEL1); else bglVertex2fv(tface->uv[0]);
551                                         if(tface->flag & TF_SEL2); else bglVertex2fv(tface->uv[1]);
552                                         if(tface->flag & TF_SEL3); else bglVertex2fv(tface->uv[2]);
553                                         if(mface->v4) {
554                                                 if(tface->flag & TF_SEL4); else bglVertex2fv(tface->uv[3]);
555                                         }
556                                 }
557                                 tface++;
558                                 mface++;
559                         }
560                         bglEnd();
561
562                         /* pinned uv's */
563                         /* give odd pointsizes odd pin pointsizes */
564                 glPointSize(pointsize*2 + (((int)pointsize % 2)? (-1): 0));
565                         cpack(0xFF);
566
567                         bglBegin(GL_POINTS);
568                         tface= me->tface;
569                         mface= me->mface;
570                         a= me->totface;
571                         while(a--) {
572                                 if(tface->flag & TF_SELECT) {
573                                         
574                                         if(tface->unwrap & TF_PIN1) bglVertex2fv(tface->uv[0]);
575                                         if(tface->unwrap & TF_PIN2) bglVertex2fv(tface->uv[1]);
576                                         if(tface->unwrap & TF_PIN3) bglVertex2fv(tface->uv[2]);
577                                         if(mface->v4) {
578                                                 if(tface->unwrap & TF_PIN4) bglVertex2fv(tface->uv[3]);
579                                         }
580                                 }
581                                 tface++;
582                                 mface++;
583                         }
584                         bglEnd();
585
586                         /* selected uv's */
587                         BIF_ThemeColor(TH_VERTEX_SELECT);
588                 glPointSize(pointsize);
589
590                         bglBegin(GL_POINTS);
591                         tface= me->tface;
592                         mface= me->mface;
593                         a= me->totface;
594                         while(a--) {
595                                 if(tface->flag & TF_SELECT) {
596                                         
597                                         if(tface->flag & TF_SEL1) bglVertex2fv(tface->uv[0]);
598                                         if(tface->flag & TF_SEL2) bglVertex2fv(tface->uv[1]);
599                                         if(tface->flag & TF_SEL3) bglVertex2fv(tface->uv[2]);
600                                         if(mface->v4) {
601                                                 if(tface->flag & TF_SEL4) bglVertex2fv(tface->uv[3]);
602                                         }
603                                 }
604                                 tface++;
605                                 mface++;
606                         }
607                         bglEnd();
608                 }
609         }
610         glPointSize(1.0);
611 }
612
613 static unsigned int *get_part_from_ibuf(ImBuf *ibuf, short startx, short starty, short endx, short endy)
614 {
615         unsigned int *rt, *rp, *rectmain;
616         short y, heigth, len;
617
618         /* the right offset in rectot */
619
620         rt= ibuf->rect+ (starty*ibuf->x+ startx);
621
622         len= (endx-startx);
623         heigth= (endy-starty);
624
625         rp=rectmain= MEM_mallocN(heigth*len*sizeof(int), "rect");
626         
627         for(y=0; y<heigth; y++) {
628                 memcpy(rp, rt, len*4);
629                 rt+= ibuf->x;
630                 rp+= len;
631         }
632         return rectmain;
633 }
634
635 static void draw_image_transform(ImBuf *ibuf)
636 {
637         if(G.moving) {
638                 float aspx, aspy, center[3];
639
640         BIF_drawConstraint();
641
642                 if(ibuf==0 || ibuf->rect==0 || ibuf->x==0 || ibuf->y==0) {
643                         aspx= aspy= 1.0;
644                 }
645                 else {
646                         aspx= 256.0/ibuf->x;
647                         aspy= 256.0/ibuf->y;
648                 }
649
650                 BIF_getPropCenter(center);
651
652                 /* scale and translate the circle into place and draw it */
653                 glPushMatrix();
654                 glScalef(aspx, aspy, 1.0);
655                 glTranslatef((1/aspx)*center[0] - center[0],
656                              (1/aspy)*center[1] - center[1], 0.0);
657
658                 BIF_drawPropCircle();
659
660                 glPopMatrix();
661         }
662 }
663
664 static void draw_image_view_icon(void)
665 {
666         float xPos = 5.0;
667
668         glEnable(GL_BLEND);
669         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
670         
671         if(G.sima->flag & SI_STICKYUVS) {
672                 BIF_icon_draw(xPos, 5.0, ICON_STICKY2_UVS);
673                 xPos = 25.0;
674         }
675         else if(!(G.sima->flag & SI_LOCALSTICKY)) {
676                 BIF_icon_draw(xPos, 5.0, ICON_STICKY_UVS);
677                 xPos = 25.0;
678         }
679
680         if(G.sima->flag & SI_SELACTFACE) {
681                 BIF_icon_draw(xPos, 5.0, ICON_DRAW_UVFACES);
682         }
683         
684         glBlendFunc(GL_ONE,  GL_ZERO); 
685         glDisable(GL_BLEND);
686 }
687
688 static void draw_image_view_tool(void)
689 {
690         ImagePaintTool *tool = &Gip.tool[Gip.current];
691         short mval[2];
692         float radius;
693         int draw= 0;
694
695         if(Gip.flag & IMAGEPAINT_DRAWING) {
696                 if(Gip.flag & IMAGEPAINT_DRAW_TOOL_DRAWING)
697                         draw= 1;
698         }
699         else if(Gip.flag & IMAGEPAINT_DRAW_TOOL)
700                 draw= 1;
701         
702         if(draw) {
703                 getmouseco_areawin(mval);
704
705                 radius= tool->size*G.sima->zoom/2;
706                 fdrawXORcirc(mval[0], mval[1], radius);
707
708                 if (tool->innerradius != 1.0) {
709                         radius *= tool->innerradius;
710                         fdrawXORcirc(mval[0], mval[1], radius);
711                 }
712         }
713 }
714
715 /* ************ panel stuff ************* */
716
717 // button define is local, only events defined here possible
718 #define B_TRANS_IMAGE   1
719
720 /* is used for both read and write... */
721 static void image_editvertex_buts(uiBlock *block)
722 {
723         static float ocent[2];
724         float cent[2]= {0.0, 0.0};
725         int imx, imy;
726         int i, nactive= 0, step, digits;
727         Mesh *me;
728         
729         if( is_uv_tface_editing_allowed_silent()==0 ) return;
730         me= get_mesh(OBACT);
731         
732         if (G.sima->image && G.sima->image->ibuf) {
733                 imx= G.sima->image->ibuf->x;
734                 imy= G.sima->image->ibuf->y;
735         } else
736                 imx= imy= 256;
737         
738         for (i=0; i<me->totface; i++) {
739                 MFace *mf= &((MFace*) me->mface)[i];
740                 TFace *tf= &((TFace*) me->tface)[i];
741                 
742                 if (!(tf->flag & TF_SELECT))
743                         continue;
744                 
745                 if (tf->flag & TF_SEL1) {
746                         cent[0]+= tf->uv[0][0];
747                         cent[1]+= tf->uv[0][1];
748                         nactive++;
749                 }
750                 if (tf->flag & TF_SEL2) {
751                         cent[0]+= tf->uv[1][0];
752                         cent[1]+= tf->uv[1][1];
753                         nactive++;
754                 }
755                 if (tf->flag & TF_SEL3) {
756                         cent[0]+= tf->uv[2][0];
757                         cent[1]+= tf->uv[2][1];
758                         nactive++;
759                 }
760                 if (mf->v4 && (tf->flag & TF_SEL4)) {
761                         cent[0]+= tf->uv[3][0];
762                         cent[1]+= tf->uv[3][1];
763                         nactive++;
764                 }
765         }
766                 
767         if(block) {     // do the buttons
768                 if (nactive) {
769                         ocent[0]= cent[0]/nactive;
770                         ocent[1]= cent[1]/nactive;
771                         if (G.sima->flag & SI_COORDFLOATS) {
772                                 step= 1;
773                                 digits= 3;
774                         }
775                         else {
776                                 ocent[0] *= imx;
777                                 ocent[1] *= imy;
778                                 step= 100;
779                                 digits= 2;
780                         }
781                         
782                         uiDefBut(block, LABEL, 0, "UV Vertex:",10,55,302,19,0,0,0,0,0,"");
783                         uiBlockBeginAlign(block);
784                         if(nactive==1) {
785                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex X:",       10, 35, 290, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
786                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex Y:",       10, 15, 290, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
787                         }
788                         else {
789                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median X:",       10, 35, 290, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
790                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median Y:",       10, 15, 290, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
791                         }
792                         uiBlockEndAlign(block);
793                 }
794         }
795         else {  // apply event
796                 float delta[2];
797                 
798                 cent[0]= cent[0]/nactive;
799                 cent[1]= cent[1]/nactive;
800                         
801                 if (G.sima->flag & SI_COORDFLOATS) {
802                         delta[0]= ocent[0]-cent[0];
803                         delta[1]= ocent[1]-cent[1];
804                 }
805                 else {
806                         delta[0]= ocent[0]/imx - cent[0];
807                         delta[1]= ocent[1]/imy - cent[1];
808                 }
809
810                 for (i=0; i<me->totface; i++) {
811                         MFace *mf= &((MFace*) me->mface)[i];
812                         TFace *tf= &((TFace*) me->tface)[i];
813                 
814                         if (!(tf->flag & TF_SELECT))
815                                 continue;
816                 
817                         if (tf->flag & TF_SEL1) {
818                                 tf->uv[0][0]+= delta[0];
819                                 tf->uv[0][1]+= delta[1];
820                         }
821                         if (tf->flag & TF_SEL2) {
822                                 tf->uv[1][0]+= delta[0];
823                                 tf->uv[1][1]+= delta[1];
824                         }
825                         if (tf->flag & TF_SEL3) {
826                                 tf->uv[2][0]+= delta[0];
827                                 tf->uv[2][1]+= delta[1];
828                         }
829                         if (mf->v4 && (tf->flag & TF_SEL4)) {
830                                 tf->uv[3][0]+= delta[0];
831                                 tf->uv[3][1]+= delta[1];
832                         }
833                 }
834                         
835                 allqueue(REDRAWVIEW3D, 0);
836                 allqueue(REDRAWIMAGE, 0);
837         }
838 }
839
840
841 void do_imagebuts(unsigned short event)
842 {
843         switch(event) {
844         case B_TRANS_IMAGE:
845                 image_editvertex_buts(NULL);
846                 break;
847
848         case B_SIMAGEDRAW:
849                 if(G.f & G_FACESELECT) {
850                         make_repbind(G.sima->image);
851                         image_changed(G.sima, 1);
852                 }
853                 allqueue(REDRAWVIEW3D, 0);
854                 allqueue(REDRAWIMAGE, 0);
855                 break;
856
857         case B_SIMAGEDRAW1:
858                 image_changed(G.sima, 2);               /* 2: only tileflag */
859                 allqueue(REDRAWVIEW3D, 0);
860                 allqueue(REDRAWIMAGE, 0);
861                 break;
862                 
863         case B_TWINANIM:
864                 {
865                         Image *ima;
866                         int nr;
867
868                         ima = G.sima->image;
869                         if (ima) {
870                                 if(ima->flag & IMA_TWINANIM) {
871                                         nr= ima->xrep*ima->yrep;
872                                         if(ima->twsta>=nr) ima->twsta= 1;
873                                         if(ima->twend>=nr) ima->twend= nr-1;
874                                         if(ima->twsta>ima->twend) ima->twsta= 1;
875                                         allqueue(REDRAWIMAGE, 0);
876                                 }
877                         }
878                 }
879                 break;
880
881         case B_SIMACLONEBROWSE:
882                 setcloneimage();
883                 allqueue(REDRAWIMAGE, 0);
884                 break;
885                 
886         case B_SIMACLONEDELETE:
887                 Gip.clone.image= NULL;
888                 allqueue(REDRAWIMAGE, 0);
889                 break;
890
891         case B_SIMABRUSHCHANGE:
892                 allqueue(REDRAWIMAGE, 0);
893                 break;
894                 
895         case B_SIMACURVES:
896                 curvemapping_do_image(G.sima->cumap, G.sima->image);
897                 allqueue(REDRAWIMAGE, 0);
898                 break;
899                 
900         case B_SIMARANGE:
901                 curvemapping_set_black_white(G.sima->cumap, NULL, NULL);
902                 curvemapping_do_image(G.sima->cumap, G.sima->image);
903                 allqueue(REDRAWIMAGE, 0);
904                 break;
905         }
906 }
907
908 static void image_panel_properties(short cntrl) // IMAGE_HANDLER_PROPERTIES
909 {
910         uiBlock *block;
911
912         block= uiNewBlock(&curarea->uiblocks, "image_panel_properties", UI_EMBOSS, UI_HELV, curarea->win);
913         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
914         uiSetPanelHandler(IMAGE_HANDLER_PROPERTIES);  // for close and esc
915         if(uiNewPanel(curarea, block, "Properties", "Image", 10, 10, 318, 204)==0)
916                 return;
917
918         if (G.sima->image && G.sima->image->ibuf) {
919                 char str[64];
920
921                 sprintf(str, "Image: size %d x %d", G.sima->image->ibuf->x, G.sima->image->ibuf->y);
922                 if(G.sima->image->ibuf->rect_float)
923                         strcat(str, " 4x32 bits");
924                 else 
925                         strcat(str, " 4x8 bits");
926                 
927                 uiDefBut(block, LABEL, B_NOP, str,              10,180,300,19, 0, 0, 0, 0, 0, "");
928
929                 uiBlockBeginAlign(block);
930                 uiDefButBitS(block, TOG, IMA_TWINANIM, B_TWINANIM, "Anim", 10,150,140,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Toggles use of animated texture");
931                 uiDefButS(block, NUM, B_TWINANIM, "Start:",             10,130,140,19, &G.sima->image->twsta, 0.0, 128.0, 0, 0, "Displays the start frame of an animated texture");
932                 uiDefButS(block, NUM, B_TWINANIM, "End:",               10,110,140,19, &G.sima->image->twend, 0.0, 128.0, 0, 0, "Displays the end frame of an animated texture");
933                 uiDefButS(block, NUM, B_NOP, "Speed",                           10,90,140,19, &G.sima->image->animspeed, 1.0, 100.0, 0, 0, "Displays Speed of the animation in frames per second");
934                 uiBlockEndAlign(block);
935
936                 uiBlockBeginAlign(block);
937                 uiDefButBitS(block, TOG, IMA_TILES, B_SIMAGEDRAW1, "Tiles",     160,150,140,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Toggles use of tilemode for faces");
938                 uiDefButS(block, NUM, B_SIMAGEDRAW, "X:",               160,130,70,19, &G.sima->image->xrep, 1.0, 16.0, 0, 0, "Sets the degree of repetition in the X direction");
939                 uiDefButS(block, NUM, B_SIMAGEDRAW, "Y:",               230,130,70,19, &G.sima->image->yrep, 1.0, 16.0, 0, 0, "Sets the degree of repetition in the Y direction");
940                 uiBlockBeginAlign(block);
941         }
942
943         image_editvertex_buts(block);
944 }
945
946 static void image_panel_paint(short cntrl)      // IMAGE_HANDLER_PROPERTIES
947 {
948         /* B_SIMABRUSHCHANGE only redraws and eats the mouse messages  */
949         /* so that LEFTMOUSE does not 'punch' through the floating panel */
950         /* B_SIMANOTHING */
951         ImagePaintTool *tool= &Gip.tool[Gip.current];
952         uiBlock *block;
953         ID *id;
954
955         block= uiNewBlock(&curarea->uiblocks, "image_panel_paint", UI_EMBOSS, UI_HELV, curarea->win);
956         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
957         uiSetPanelHandler(IMAGE_HANDLER_PAINT);  // for close and esc
958         if(uiNewPanel(curarea, block, "Image Paint", "Image", 10, 230, 318, 204)==0)
959                 return;
960
961         uiBlockBeginAlign(block);
962         uiDefButF(block, COL, B_VPCOLSLI, "",           979,160,230,19, tool->rgba, 0, 0, 0, 0, "");
963         uiDefButF(block, NUMSLI, B_SIMANOTHING , "Opacity ",            979,140,230,19, tool->rgba+3, 0.0, 1.0, 0, 0, "The amount of pressure on the brush");
964         uiDefButI(block, NUMSLI, B_SIMANOTHING , "Size ",               979,120,230,19, &tool->size, 2, 64, 0, 0, "The size of the brush");
965         uiDefButF(block, NUMSLI, B_SIMANOTHING , "Fall ",               979,100,230,19, &tool->innerradius, 0.0, 1.0, 0, 0, "The fall off radius of the brush");
966
967         if(Gip.current == IMAGEPAINT_BRUSH || Gip.current == IMAGEPAINT_SMEAR)
968                 uiDefButF(block, NUMSLI, B_SIMANOTHING , "Stepsize ",979,80,230,19, &tool->timing, 1.0, 100.0, 0, 0, "Repeating Paint On %of Brush diameter");
969         else
970                 uiDefButF(block, NUMSLI, B_SIMANOTHING , "Flow ",       979,80,230,19, &tool->timing, 1.0, 100.0, 0, 0, "Paint Flow for Air Brush");
971         uiBlockEndAlign(block);
972
973         uiBlockBeginAlign(block);
974         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Brush",               890,160,80,19, &Gip.current, 7.0, IMAGEPAINT_BRUSH, 0, 0, "Brush");
975         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "AirBrush",            890,140,80,19, &Gip.current, 7.0, IMAGEPAINT_AIRBRUSH, 0, 0, "AirBrush");
976         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Soften",              890,120,80,19, &Gip.current, 7.0, IMAGEPAINT_SOFTEN, 0, 0, "Soften");
977         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Aux AB1",             890,100,80,19, &Gip.current, 7.0, IMAGEPAINT_AUX1, 0, 0, "Auxiliary Air Brush1");
978         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Aux AB2",             890,80,80,19, &Gip.current, 7.0, IMAGEPAINT_AUX2, 0, 0, "Auxiliary Air Brush2");        
979         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Smear",               890,60,80,19, &Gip.current, 7.0, IMAGEPAINT_SMEAR, 0, 0, "Smear");      
980         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Clone",               890,40,80,19, &Gip.current, 7.0, IMAGEPAINT_CLONE, 0, 0, "Clone Brush / use RMB to drag source image"); 
981         uiBlockEndAlign(block);
982
983         uiBlockBeginAlign(block);       
984         id= (ID*)Gip.clone.image;
985         std_libbuttons(block, 979, 40, 0, NULL, B_SIMACLONEBROWSE, ID_IM, 0, id, 0, &G.sima->menunr, 0, 0, B_SIMACLONEDELETE, 0, 0);
986         uiDefButF(block, NUMSLI, B_SIMABRUSHCHANGE, "B ",979,20,230,19, &Gip.clone.alpha , 0.0, 1.0, 0, 0, "Blend clone image");
987         uiBlockEndAlign(block);
988
989 #if 0
990         uiDefButBitS(block, TOG|BIT, IMAGEPAINT_DRAW_TOOL_DRAWING, B_SIMABRUSHCHANGE, "TD", 890,1,50,19, &Gip.flag, 0, 0, 0, 0, "Enables tool shape while drawing");
991         uiDefButBitS(block, TOG|BIT, IMAGEPAINT_DRAW_TOOL, B_SIMABRUSHCHANGE, "TP", 940,1,50,19, &Gip.flag, 0, 0, 0, 0, "Enables tool shape while not drawing");
992 #endif
993         uiDefButBitS(block, TOG|BIT, IMAGEPAINT_TORUS, B_SIMABRUSHCHANGE, "Wrap", 890,1,50,19, &Gip.flag, 0, 0, 0, 0, "Enables torus wrapping");
994 }
995
996 static void image_panel_curves_reset(void *cumap_v, void *unused)
997 {
998         CurveMapping *cumap = cumap_v;
999         int a;
1000         
1001         for(a=0; a<CM_TOT; a++)
1002                 curvemap_reset(cumap->cm+a, &cumap->clipr);
1003         
1004         cumap->black[0]=cumap->black[1]=cumap->black[2]= 0.0f;
1005         cumap->white[0]=cumap->white[1]=cumap->white[2]= 1.0f;
1006         curvemapping_set_black_white(cumap, NULL, NULL);
1007         
1008         curvemapping_changed(cumap, 0);
1009         curvemapping_do_image(cumap, G.sima->image);
1010         
1011         allqueue(REDRAWIMAGE, 0);
1012 }
1013
1014
1015 static void image_panel_curves(short cntrl)     // IMAGE_HANDLER_PROPERTIES
1016 {
1017         uiBlock *block;
1018         uiBut *bt;
1019         
1020         block= uiNewBlock(&curarea->uiblocks, "image_panel_curves", UI_EMBOSS, UI_HELV, curarea->win);
1021         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1022         uiSetPanelHandler(IMAGE_HANDLER_CURVES);  // for close and esc
1023         if(uiNewPanel(curarea, block, "Curves", "Image", 10, 450, 318, 204)==0)
1024                 return;
1025         
1026         if (G.sima->image && G.sima->image->ibuf) {
1027                 rctf rect;
1028                 
1029                 if(G.sima->cumap==NULL)
1030                         G.sima->cumap= curvemapping_add(4, 0.0f, 0.0f, 1.0f, 1.0f);
1031                 
1032                 rect.xmin= 110; rect.xmax= 310;
1033                 rect.ymin= 10; rect.ymax= 200;
1034                 curvemap_buttons(block, G.sima->cumap, 'c', B_SIMACURVES, B_SIMAGEDRAW, &rect);
1035                 
1036                 bt=uiDefBut(block, BUT, B_SIMARANGE, "Reset",   10, 160, 90, 19, NULL, 0.0f, 0.0f, 0, 0, "Reset Black/White point and curves");
1037                 uiButSetFunc(bt, image_panel_curves_reset, G.sima->cumap, NULL);
1038                 
1039                 uiBlockBeginAlign(block);
1040                 uiDefButF(block, NUM, B_SIMARANGE, "Min R:",    10, 120, 90, 19, G.sima->cumap->black, -1000.0f, 1000.0f, 10, 2, "Black level");
1041                 uiDefButF(block, NUM, B_SIMARANGE, "Min G:",    10, 100, 90, 19, G.sima->cumap->black+1, -1000.0f, 1000.0f, 10, 2, "Black level");
1042                 uiDefButF(block, NUM, B_SIMARANGE, "Min B:",    10, 80, 90, 19, G.sima->cumap->black+2, -1000.0f, 1000.0f, 10, 2, "Black level");
1043                 
1044                 uiBlockBeginAlign(block);
1045                 uiDefButF(block, NUM, B_SIMARANGE, "Max R:",    10, 50, 90, 19, G.sima->cumap->white, -1000.0f, 1000.0f, 10, 2, "White level");
1046                 uiDefButF(block, NUM, B_SIMARANGE, "Max G:",    10, 30, 90, 19, G.sima->cumap->white+1, -1000.0f, 1000.0f, 10, 2, "White level");
1047                 uiDefButF(block, NUM, B_SIMARANGE, "Max B:",    10, 10, 90, 19, G.sima->cumap->white+2, -1000.0f, 1000.0f, 10, 2, "White level");
1048                 
1049         }
1050 }
1051
1052 /* are there curves? curves visible? and curves do something? */
1053 static int image_curves_active(ScrArea *sa)
1054 {
1055         SpaceImage *sima= sa->spacedata.first;
1056
1057         if(sima->cumap) {
1058                 if(curvemapping_RGBA_does_something(sima->cumap)) {
1059                         short a;
1060                         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1061                                 if(sima->blockhandler[a] == IMAGE_HANDLER_CURVES)
1062                                         return 1;
1063                         }
1064                 }
1065         }
1066         return 0;
1067 }
1068
1069 void image_preview_event(int event)
1070 {
1071         int exec= 0;
1072         
1073
1074         if(event==0) {
1075                 G.scene->r.scemode &= ~R_COMP_CROP;
1076                 exec= 1;
1077         }
1078         else if(event==2 || (G.scene->r.scemode & R_COMP_CROP)==0) {
1079                 if(image_preview_active(curarea, NULL, NULL)) {
1080                         G.scene->r.scemode |= R_COMP_CROP;
1081                         exec= 1;
1082                 }
1083         }
1084         
1085         if(exec) {
1086                 ScrArea *sa;
1087                 
1088                 ntreeCompositTagGenerators(G.scene->nodetree);
1089         
1090                 for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
1091                         if(sa->spacetype==SPACE_NODE) {
1092                                 addqueue(sa->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
1093                                 break;
1094                         }
1095                 }
1096         }       
1097 }
1098
1099
1100 /* nothing drawn here, we use it to store values */
1101 static void preview_cb(struct ScrArea *sa, struct uiBlock *block)
1102 {
1103         rctf dispf;
1104         rcti *disprect= &G.scene->r.disprect;
1105         int winx= (G.scene->r.size*G.scene->r.xsch)/100;
1106         int winy= (G.scene->r.size*G.scene->r.ysch)/100;
1107         short mval[2];
1108         
1109         if(G.scene->r.mode & R_BORDER) {
1110                 winx*= (G.scene->r.border.xmax - G.scene->r.border.xmin);
1111                 winy*= (G.scene->r.border.ymax - G.scene->r.border.ymin);
1112         }
1113         
1114         /* while dragging we don't update the rects */
1115         if(block->panel->flag & PNL_SELECT)
1116                 return;
1117         if(get_mbut() & M_MOUSE)
1118                 return;
1119
1120         BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
1121         ui_graphics_to_window_rct(sa->win, &dispf, disprect);
1122         
1123         /* correction for gla draw */
1124         BLI_translate_rcti(disprect, -curarea->winrct.xmin, -curarea->winrct.ymin);
1125         
1126         calc_image_view(G.sima, 'p');
1127 //      printf("winrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1128         /* map to image space coordinates */
1129         mval[0]= disprect->xmin; mval[1]= disprect->ymin;
1130         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmin, &dispf.ymin);
1131         mval[0]= disprect->xmax; mval[1]= disprect->ymax;
1132         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmax, &dispf.ymax);
1133         
1134         /* map to render coordinates */
1135         disprect->xmin= dispf.xmin;
1136         disprect->xmax= dispf.xmax;
1137         disprect->ymin= dispf.ymin;
1138         disprect->ymax= dispf.ymax;
1139         
1140         CLAMP(disprect->xmin, 0, winx);
1141         CLAMP(disprect->xmax, 0, winx);
1142         CLAMP(disprect->ymin, 0, winy);
1143         CLAMP(disprect->ymax, 0, winy);
1144 //      printf("drawrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1145         
1146         image_preview_event(1);
1147 }
1148
1149 static int is_preview_allowed(ScrArea *cur)
1150 {
1151         ScrArea *sa;
1152
1153         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
1154                 if(sa!=cur && sa->spacetype==SPACE_IMAGE) {
1155                         if(image_preview_active(sa, NULL, NULL))
1156                            return 0;
1157                 }
1158         }
1159         return 1;
1160 }
1161
1162 static void image_panel_preview(ScrArea *sa, short cntrl)       // IMAGE_HANDLER_PREVIEW
1163 {
1164         uiBlock *block;
1165         SpaceImage *sima= sa->spacedata.first;
1166         int ofsx, ofsy;
1167         
1168         if(is_preview_allowed(sa)==0) {
1169                 rem_blockhandler(sa, IMAGE_HANDLER_PREVIEW);
1170                 return;
1171         }
1172         
1173         block= uiNewBlock(&sa->uiblocks, "image_panel_preview", UI_EMBOSS, UI_HELV, sa->win);
1174         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | UI_PNL_SCALE | cntrl);
1175         uiSetPanelHandler(IMAGE_HANDLER_PREVIEW);  // for close and esc
1176         
1177         ofsx= -150+(sa->winx/2)/sima->blockscale;
1178         ofsy= -100+(sa->winy/2)/sima->blockscale;
1179         if(uiNewPanel(sa, block, "Preview", "Image", ofsx, ofsy, 300, 200)==0) return;
1180         
1181         uiBlockSetDrawExtraFunc(block, preview_cb);
1182         
1183 }
1184
1185 static void image_blockhandlers(ScrArea *sa)
1186 {
1187         SpaceImage *sima= sa->spacedata.first;
1188         short a;
1189
1190         /* warning; blocks need to be freed each time, handlers dont remove  */
1191         uiFreeBlocksWin(&sa->uiblocks, sa->win);
1192         
1193         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1194                 switch(sima->blockhandler[a]) {
1195
1196                 case IMAGE_HANDLER_PROPERTIES:
1197                         image_panel_properties(sima->blockhandler[a+1]);
1198                         break;
1199                 case IMAGE_HANDLER_PAINT:
1200                         image_panel_paint(sima->blockhandler[a+1]);
1201                         break;          
1202                 case IMAGE_HANDLER_CURVES:
1203                         image_panel_curves(sima->blockhandler[a+1]);
1204                         break;          
1205                 case IMAGE_HANDLER_PREVIEW:
1206                         image_panel_preview(sa, sima->blockhandler[a+1]);
1207                         break;          
1208                 }
1209                 /* clear action value for event */
1210                 sima->blockhandler[a+1]= 0;
1211         }
1212         uiDrawBlocksPanels(sa, 0);
1213 }
1214
1215 static void imagespace_grid(SpaceImage *sima)
1216 {
1217         float gridsize, gridstep= 1.0f/32.0f;
1218         float fac, blendfac;
1219         
1220         gridsize= sima->zoom;
1221         
1222         calc_image_view(sima, 'f');
1223         myortho2(sima->v2d.cur.xmin, sima->v2d.cur.xmax, sima->v2d.cur.ymin, sima->v2d.cur.ymax);
1224         
1225         BIF_ThemeColorShade(TH_BACK, 20);
1226         glRectf(0.0, 0.0, 1.0, 1.0);
1227         
1228         if(gridsize<=0.0f) return;
1229         
1230         if(gridsize<1.0f) {
1231                 while(gridsize<1.0f) {
1232                         gridsize*= 4.0;
1233                         gridstep*= 4.0;
1234                 }
1235         }
1236         else {
1237                 while(gridsize>=4.0f) {
1238                         gridsize/= 4.0;
1239                         gridstep/= 4.0;
1240                 }
1241         }
1242         
1243         /* the fine resolution level */
1244         blendfac= 0.25*gridsize - floor(0.25*gridsize);
1245         CLAMP(blendfac, 0.0, 1.0);
1246         BIF_ThemeColorShade(TH_BACK, (int)(20.0*(1.0-blendfac)));
1247         
1248         fac= 0.0f;
1249         glBegin(GL_LINES);
1250         while(fac<1.0) {
1251                 glVertex2f(0.0f, fac);
1252                 glVertex2f(1.0f, fac);
1253                 glVertex2f(fac, 0.0f);
1254                 glVertex2f(fac, 1.0f);
1255                 fac+= gridstep;
1256         }
1257         
1258         /* the large resolution level */
1259         BIF_ThemeColor(TH_BACK);
1260         
1261         fac= 0.0f;
1262         while(fac<1.0) {
1263                 glVertex2f(0.0f, fac);
1264                 glVertex2f(1.0f, fac);
1265                 glVertex2f(fac, 0.0f);
1266                 glVertex2f(fac, 1.0f);
1267                 fac+= 4.0*gridstep;
1268         }
1269         glEnd();
1270         
1271 }
1272
1273 static void sima_draw_alpha_backdrop(SpaceImage *sima, float x1, float y1, float xsize, float ysize)
1274 {
1275         float tile= sima->zoom*15.0f;
1276         float x, y, maxx, maxy;
1277         
1278         glColor3ub(100, 100, 100);
1279         glRectf(x1, y1, x1 + sima->zoom*xsize, y1 + sima->zoom*ysize);
1280         glColor3ub(160, 160, 160);
1281         
1282         maxx= x1+sima->zoom*xsize;
1283         maxy= y1+sima->zoom*ysize;
1284         
1285         for(x=0; x<xsize; x+=30) {
1286                 for(y=0; y<ysize; y+=30) {
1287                         float fx= x1 + sima->zoom*x;
1288                         float fy= y1 + sima->zoom*y;
1289                         float tilex= tile, tiley= tile;
1290                         
1291                         if(fx+tile > maxx)
1292                                 tilex= maxx-fx;
1293                         if(fy+tile > maxy)
1294                                 tiley= maxy-fy;
1295                         
1296                         glRectf(fx, fy, fx + tilex, fy + tiley);
1297                 }
1298         }
1299         for(x=15; x<xsize; x+=30) {
1300                 for(y=15; y<ysize; y+=30) {
1301                         float fx= x1 + sima->zoom*x;
1302                         float fy= y1 + sima->zoom*y;
1303                         float tilex= tile, tiley= tile;
1304                         
1305                         if(fx+tile > maxx)
1306                                 tilex= maxx-fx;
1307                         if(fy+tile > maxy)
1308                                 tiley= maxy-fy;
1309                         
1310                         glRectf(fx, fy, fx + tilex, fy + tiley);
1311                 }
1312         }
1313 }
1314
1315 static void sima_draw_alpha_pixels(float x1, float y1, int rectx, int recty, unsigned int *recti)
1316 {
1317         
1318         /* swap bytes, so alpha is most significant one, then just draw it as luminance int */
1319         if(G.order==B_ENDIAN)
1320                 glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
1321         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_UNSIGNED_INT, recti);
1322         glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
1323 }
1324
1325 static void sima_draw_alpha_pixelsf(float x1, float y1, int rectx, int recty, float *rectf)
1326 {
1327         float *trectf= MEM_mallocN(rectx*recty*4, "temp");
1328         int a, b;
1329         
1330         for(a= rectx*recty -1, b= 4*a+3; a>=0; a--, b-=4)
1331                 trectf[a]= rectf[b];
1332         
1333         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, trectf);
1334         MEM_freeN(trectf);
1335         /* ogl trick below is slower... (on ATI 9600) */
1336 //      glColorMask(1, 0, 0, 0);
1337 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+3);
1338 //      glColorMask(0, 1, 0, 0);
1339 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+2);
1340 //      glColorMask(0, 0, 1, 0);
1341 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+1);
1342 //      glColorMask(1, 1, 1, 1);
1343 }
1344
1345 static void sima_draw_zbuf_pixels(float x1, float y1, int rectx, int recty, int *recti)
1346 {
1347         if(recti==NULL)
1348                 return;
1349         
1350         /* zbuffer values are signed, so we need to shift color range */
1351         glPixelTransferf(GL_RED_SCALE, 0.5f);
1352         glPixelTransferf(GL_GREEN_SCALE, 0.5f);
1353         glPixelTransferf(GL_BLUE_SCALE, 0.5f);
1354         glPixelTransferf(GL_RED_BIAS, 0.5f);
1355         glPixelTransferf(GL_GREEN_BIAS, 0.5f);
1356         glPixelTransferf(GL_BLUE_BIAS, 0.5f);
1357         
1358         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_INT, recti);
1359         
1360         glPixelTransferf(GL_RED_SCALE, 1.0f);
1361         glPixelTransferf(GL_GREEN_SCALE, 1.0f);
1362         glPixelTransferf(GL_BLUE_SCALE, 1.0f);
1363         glPixelTransferf(GL_RED_BIAS, 0.0f);
1364         glPixelTransferf(GL_GREEN_BIAS, 0.0f);
1365         glPixelTransferf(GL_BLUE_BIAS, 0.0f);
1366 }
1367
1368 static void sima_draw_zbuffloat_pixels(float x1, float y1, int rectx, int recty, float *rect_float)
1369 {
1370         float bias, scale, *rectf, clipend;
1371         int a;
1372         
1373         if(rect_float==NULL)
1374                 return;
1375         
1376         if(G.scene->camera && G.scene->camera->type==OB_CAMERA) {
1377                 bias= ((Camera *)G.scene->camera->data)->clipsta;
1378                 clipend= ((Camera *)G.scene->camera->data)->clipend;
1379                 scale= 1.0f/(clipend-bias);
1380         }
1381         else {
1382                 bias= 0.1f;
1383                 scale= 0.01f;
1384                 clipend= 100.0f;
1385         }
1386         
1387         rectf= MEM_mallocN(rectx*recty*4, "temp");
1388         for(a= rectx*recty -1; a>=0; a--) {
1389                 if(rect_float[a]>clipend)
1390                         rectf[a]= 0.0f;
1391                 else if(rect_float[a]<bias)
1392                         rectf[a]= 1.0f;
1393                 else {
1394                         rectf[a]= 1.0f - (rect_float[a]-bias)*scale;
1395                         rectf[a]*= rectf[a];
1396                 }
1397         }
1398         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, rectf);
1399         
1400         MEM_freeN(rectf);
1401 }
1402
1403 static void imagewindow_draw_renderinfo(ScrArea *sa)
1404 {
1405         SpaceImage *sima= sa->spacedata.first;
1406         rcti rect;
1407         float colf[3];
1408         
1409         if(sima->info_str==NULL)
1410                 return;
1411         
1412         rect= sa->winrct;
1413         rect.ymin= rect.ymax-RW_HEADERY;
1414         
1415         glaDefine2DArea(&rect);
1416         
1417         /* clear header rect */
1418         BIF_GetThemeColor3fv(TH_BACK, colf);
1419         glClearColor(colf[0]+0.1f, colf[1]+0.1f, colf[2]+0.1f, 1.0); 
1420         glClear(GL_COLOR_BUFFER_BIT);
1421         
1422         BIF_ThemeColor(TH_TEXT_HI);
1423         glRasterPos2i(12, 5);
1424         BMF_DrawString(G.fonts, sima->info_str);
1425 }
1426
1427 void drawimagespace(ScrArea *sa, void *spacedata)
1428 {
1429         SpaceImage *sima= spacedata;
1430         ImBuf *ibuf= NULL;
1431         float col[3];
1432         unsigned int *rect;
1433         float x1, y1;
1434         short sx, sy, dx, dy, show_render= 0;
1435         
1436                 /* If derived data is used then make sure that object
1437                  * is up-to-date... might not be the case because updates
1438                  * are normally done in drawview and could get here before
1439                  * drawing a View3D.
1440                  */
1441         if (!G.obedit && OBACT && (sima->flag & SI_DRAWSHADOW)) {
1442                 object_handle_update(OBACT);
1443         }
1444
1445         BIF_GetThemeColor3fv(TH_BACK, col);
1446         glClearColor(col[0], col[1], col[2], 0.0);
1447         glClear(GL_COLOR_BUFFER_BIT);
1448
1449         bwin_clear_viewmat(sa->win);    /* clear buttons view */
1450         glLoadIdentity();
1451         
1452         if(sima->image && BLI_streq(sima->image->name, "Render Result") )
1453                 show_render= 1;
1454         
1455         what_image(sima);
1456         
1457         if(sima->image) {
1458                 if(sima->image->ibuf==NULL) {
1459                         load_image(sima->image, IB_rect, G.sce, G.scene->r.cfra);
1460                         scrarea_queue_headredraw(sa);   /* update header for image options */
1461                 }
1462                 
1463                 tag_image_time(sima->image);
1464                 ibuf= sima->image->ibuf;
1465         }
1466         
1467         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL)) {
1468                 imagespace_grid(sima);
1469                 if(show_render==0)
1470                         draw_tfaces();
1471         }
1472         else {
1473                 float xim, yim, xoffs=0.0f, yoffs= 0.0f;
1474                 
1475                 if(image_preview_active(sa, &xim, &yim)) {
1476                         xoffs= G.scene->r.disprect.xmin;
1477                         yoffs= G.scene->r.disprect.ymin;
1478                         glColor3ub(0,0,0);
1479                         calc_image_view(sima, 'f');     
1480                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
1481                         glRectf(0.0f, 0.0f, 1.0f, 1.0f);
1482                         glLoadIdentity();
1483                 }
1484                 else {
1485                         xim= ibuf->x; yim= ibuf->y;
1486                 }
1487                 
1488                 /* calc location */
1489                 x1= sima->zoom*xoffs + ((float)sa->winx - sima->zoom*(float)xim)/2.0f;
1490                 y1= sima->zoom*yoffs + ((float)sa->winy - sima->zoom*(float)yim)/2.0f;
1491         
1492                 x1-= sima->zoom*sima->xof;
1493                 y1-= sima->zoom*sima->yof;
1494                 
1495                 /* needed for gla draw */
1496                 if(show_render) { 
1497                         rcti rct= sa->winrct; 
1498                         
1499                         imagewindow_draw_renderinfo(sa);        /* calls glaDefine2DArea too */
1500                         
1501                         rct.ymax-=RW_HEADERY; 
1502                         glaDefine2DArea(&rct);
1503                 }
1504                 else glaDefine2DArea(&sa->winrct);
1505                 
1506                 glPixelZoom((float)sima->zoom, (float)sima->zoom);
1507                                 
1508                 if(sima->flag & SI_EDITTILE) {
1509                         glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1510                         
1511                         glPixelZoom(1.0, 1.0);
1512                         
1513                         dx= ibuf->x/sima->image->xrep;
1514                         dy= ibuf->y/sima->image->yrep;
1515                         sy= (sima->curtile / sima->image->xrep);
1516                         sx= sima->curtile - sy*sima->image->xrep;
1517         
1518                         sx*= dx;
1519                         sy*= dy;
1520                         
1521                         calc_image_view(sima, 'p');     /* pixel */
1522                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
1523                         
1524                         cpack(0x0);
1525                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx,  sy,  sx+dx-1,  sy+dy-1); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1526                         cpack(0xFFFFFF);
1527                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx+1,  sy+1,  sx+dx,  sy+dy); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1528                 }
1529                 else if(sima->mode==SI_TEXTURE) {
1530                         
1531                         if(sima->image->tpageflag & IMA_TILES) {
1532                                 
1533                                 /* just leave this a while */
1534                                 if(sima->image->xrep<1) return;
1535                                 if(sima->image->yrep<1) return;
1536                                 
1537                                 if(sima->curtile >= sima->image->xrep*sima->image->yrep) 
1538                                         sima->curtile = sima->image->xrep*sima->image->yrep - 1; 
1539                                 
1540                                 dx= ibuf->x/sima->image->xrep;
1541                                 dy= ibuf->y/sima->image->yrep;
1542                                 
1543                                 sy= (sima->curtile / sima->image->xrep);
1544                                 sx= sima->curtile - sy*sima->image->xrep;
1545                 
1546                                 sx*= dx;
1547                                 sy*= dy;
1548                                 
1549                                 rect= get_part_from_ibuf(ibuf, sx, sy, sx+dx, sy+dy);
1550                                 
1551                                 /* rect= ibuf->rect; */
1552                                 for(sy= 0; sy+dy<=ibuf->y; sy+= dy) {
1553                                         for(sx= 0; sx+dx<=ibuf->x; sx+= dx) {
1554                                                 glaDrawPixelsSafe(x1+sx*sima->zoom, y1+sy*sima->zoom, dx, dy, dx, GL_RGBA, GL_UNSIGNED_BYTE, rect);
1555                                         }
1556                                 }
1557                                 
1558                                 MEM_freeN(rect);
1559                         }
1560                         else {
1561                                 /* this part is generic image display */
1562                                 if(sima->flag & SI_SHOW_ALPHA) {
1563                                         if(ibuf->rect)
1564                                                 sima_draw_alpha_pixels(x1, y1, ibuf->x, ibuf->y, ibuf->rect);
1565                                         else if(ibuf->rect_float)
1566                                                 sima_draw_alpha_pixelsf(x1, y1, ibuf->x, ibuf->y, ibuf->rect_float);
1567                                 }
1568                                 else if(sima->flag & SI_SHOW_ZBUF) {
1569                                         if(ibuf->zbuf)
1570                                                 sima_draw_zbuf_pixels(x1, y1, ibuf->x, ibuf->y, ibuf->zbuf);
1571                                         else
1572                                                 sima_draw_zbuffloat_pixels(x1, y1, ibuf->x, ibuf->y, ibuf->zbuf_float);
1573                                 }
1574                                 else {
1575                                         if(sima->flag & SI_USE_ALPHA) {
1576                                                 sima_draw_alpha_backdrop(sima, x1, y1, (float)ibuf->x, (float)ibuf->y);
1577                                                 glEnable(GL_BLEND);
1578                                         }
1579                                         
1580                                         /* detect if we need to redo the curve map. 
1581                                            ibuf->rect is zero for compositor and render results after change 
1582                                            convert to 32 bits always... drawing float rects isnt supported well (atis)
1583                                         */
1584                                         if(ibuf->rect_float) {
1585                                                 if(ibuf->rect==NULL) {
1586                                                         if(image_curves_active(sa))
1587                                                                 curvemapping_do_image(G.sima->cumap, G.sima->image);
1588                                                         else 
1589                                                                 IMB_rect_from_float(ibuf);
1590                                                 }
1591                                         }
1592
1593                                         if(ibuf->rect)
1594                                                 glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1595 //                                      else
1596 //                                              glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_FLOAT, ibuf->rect_float);
1597                                         
1598                                         if(sima->flag & SI_USE_ALPHA)
1599                                                 glDisable(GL_BLEND);
1600                                 }
1601                         }
1602                         
1603                         if(Gip.current == IMAGEPAINT_CLONE) {
1604                                 int w, h;
1605                                 unsigned char *clonerect;
1606
1607                                 /* this is not very efficient, but glDrawPixels doesn't allow
1608                                    drawing with alpha */
1609                                 clonerect= alloc_alpha_clone_image(&w, &h);
1610
1611                                 if(clonerect) {
1612                                         int offx, offy;
1613                                         offx = sima->zoom*ibuf->x * + Gip.clone.offset[0];
1614                                         offy = sima->zoom*ibuf->y * + Gip.clone.offset[1];
1615
1616                                         glEnable(GL_BLEND);
1617                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1618                                         glaDrawPixelsSafe(x1 + offx, y1 + offy, w, h, w, GL_RGBA, GL_UNSIGNED_BYTE, clonerect);
1619                                         glDisable(GL_BLEND);
1620
1621                                         MEM_freeN(clonerect);
1622                                 }
1623                         }
1624                         
1625                         glPixelZoom(1.0, 1.0);
1626                         
1627                         if(show_render==0) 
1628                                 draw_tfaces();
1629                 }
1630
1631                 glPixelZoom(1.0, 1.0);
1632
1633                 calc_image_view(sima, 'f');     /* float */
1634         }
1635
1636         draw_image_transform(ibuf);
1637
1638         mywinset(sa->win);      /* restore scissor after gla call... */
1639         myortho2(-0.375, sa->winx-0.375, -0.375, sa->winy-0.375);
1640
1641         if(G.rendering==0) {
1642                 draw_image_view_tool();
1643                 draw_image_view_icon();
1644         }
1645         draw_area_emboss(sa);
1646
1647         /* it is important to end a view in a transform compatible with buttons */
1648         bwin_scalematrix(sa->win, sima->blockscale, sima->blockscale, sima->blockscale);
1649         if(!(G.rendering && show_render))
1650                 image_blockhandlers(sa);
1651
1652         sa->win_swap= WIN_BACK_OK;
1653 }
1654
1655 static void image_zoom_power_of_two(void)
1656 {
1657         /* Make zoom a power of 2 */
1658
1659         G.sima->zoom = 1 / G.sima->zoom;
1660         G.sima->zoom = log(G.sima->zoom) / log(2);
1661         G.sima->zoom = ceil(G.sima->zoom);
1662         G.sima->zoom = pow(2, G.sima->zoom);
1663         G.sima->zoom = 1 / G.sima->zoom;
1664 }
1665
1666 static void image_zoom_set_factor(float zoomfac)
1667 {
1668         SpaceImage *sima= curarea->spacedata.first;
1669         int width, height;
1670
1671         if (zoomfac <= 0.0f)
1672                 return;
1673
1674         sima->zoom *= zoomfac;
1675
1676         if (sima->zoom > 0.1f && sima->zoom < 4.0f)
1677                 return;
1678
1679         /* check zoom limits */
1680
1681         calc_image_view(G.sima, 'p');
1682         width= 256;
1683         height= 256;
1684         if (sima->image) {
1685                 if (sima->image->ibuf) {
1686                         float xim, yim;
1687                         /* I know a bit weak... but preview uses not actual image size */
1688                         if(image_preview_active(curarea, &xim, &yim)) {
1689                                 width= (int) xim;
1690                                 height= (int) yim;
1691                         }
1692                         else {
1693                                 width= sima->image->ibuf->x;
1694                                 height= sima->image->ibuf->y;
1695                         }
1696                 }
1697         }
1698         width *= sima->zoom;
1699         height *= sima->zoom;
1700
1701         if ((width < 4) && (height < 4))
1702                 sima->zoom /= zoomfac;
1703         else if((curarea->winrct.xmax - curarea->winrct.xmin) <= sima->zoom)
1704                 sima->zoom /= zoomfac;
1705         else if((curarea->winrct.ymax - curarea->winrct.ymin) <= sima->zoom)
1706                 sima->zoom /= zoomfac;
1707 }
1708
1709 void image_viewmove(int mode)
1710 {
1711         short mval[2], mvalo[2], zoom0;
1712         int oldcursor;
1713         Window *win;
1714         
1715         getmouseco_sc(mvalo);
1716         zoom0= G.sima->zoom;
1717         
1718         oldcursor=get_cursor();
1719         win=winlay_get_active_window();
1720         
1721         SetBlenderCursor(BC_NSEW_SCROLLCURSOR);
1722         
1723         while(get_mbut()&(L_MOUSE|M_MOUSE)) {
1724
1725                 getmouseco_sc(mval);
1726
1727                 if(mvalo[0]!=mval[0] || mvalo[1]!=mval[1]) {
1728                 
1729                         if(mode==0) {
1730                                 G.sima->xof += (mvalo[0]-mval[0])/G.sima->zoom;
1731                                 G.sima->yof += (mvalo[1]-mval[1])/G.sima->zoom;
1732                         }
1733                         else if (mode==1) {
1734                                 float factor;
1735
1736                                 factor= 1.0+(float)(mvalo[0]-mval[0]+mvalo[1]-mval[1])/300.0;
1737                                 image_zoom_set_factor(factor);
1738                         }
1739
1740                         mvalo[0]= mval[0];
1741                         mvalo[1]= mval[1];
1742                         
1743                         scrarea_do_windraw(curarea);
1744                         screen_swapbuffers();
1745                 }
1746                 else BIF_wait_for_statechange();
1747         }
1748         window_set_cursor(win, oldcursor);
1749         
1750         if(image_preview_active(curarea, NULL, NULL)) {
1751                 /* recalculates new preview rect */
1752                 scrarea_do_windraw(curarea);
1753                 image_preview_event(2);
1754         }
1755 }
1756
1757 void image_viewzoom(unsigned short event, int invert)
1758 {
1759         SpaceImage *sima= curarea->spacedata.first;
1760
1761         if(event==WHEELDOWNMOUSE || event==PADMINUS)
1762                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 1.25: 0.8);
1763         else if(event==WHEELUPMOUSE || event==PADPLUSKEY)
1764                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 0.8: 1.25);
1765         else if(event==PAD1)
1766                 sima->zoom= 1.0;
1767         else if(event==PAD2)
1768                 sima->zoom= (invert)? 2.0: 0.5;
1769         else if(event==PAD4)
1770                 sima->zoom= (invert)? 4.0: 0.25;
1771         else if(event==PAD8)
1772                 sima->zoom= (invert)? 8.0: 0.125;
1773         
1774         /* ensure pixel exact locations for draw */
1775         sima->xof= (int)sima->xof;
1776         sima->yof= (int)sima->yof;
1777         
1778         if(image_preview_active(curarea, NULL, NULL)) {
1779                 /* recalculates new preview rect */
1780                 scrarea_do_windraw(curarea);
1781                 image_preview_event(2);
1782         }
1783 }
1784
1785 /**
1786  * Updates the fields of the View2D member of the SpaceImage struct.
1787  * Default behavior is to reset the position of the image and set the zoom to 1
1788  * If the image will not fit within the window rectangle, the zoom is adjusted
1789  *
1790  * @return    void
1791  *   
1792  */
1793 void image_home(void)
1794 {
1795         int width, height, imgwidth, imgheight;
1796         float zoomX, zoomY;
1797
1798         if (curarea->spacetype != SPACE_IMAGE) return;
1799
1800         if ((G.sima->image == NULL) || (G.sima->image->ibuf == NULL)) {
1801                 imgwidth = 256;
1802                 imgheight = 256;
1803         }
1804         else {
1805                 imgwidth = G.sima->image->ibuf->x;
1806                 imgheight = G.sima->image->ibuf->y;
1807         }
1808
1809         /* Check if the image will fit in the image with zoom==1 */
1810         width = curarea->winx;
1811         height = curarea->winy;
1812         if (((imgwidth >= width) || (imgheight >= height)) && 
1813                 ((width > 0) && (height > 0))) {
1814                 /* Find the zoom value that will fit the image in the image space */
1815                 zoomX = ((float)width) / ((float)imgwidth);
1816                 zoomY = ((float)height) / ((float)imgheight);
1817                 G.sima->zoom= MIN2(zoomX, zoomY);
1818
1819                 image_zoom_power_of_two();
1820         }
1821         else {
1822                 G.sima->zoom= 1.0f;
1823         }
1824
1825         G.sima->xof= G.sima->yof= 0.0f;
1826         
1827         calc_image_view(G.sima, 'p');
1828         
1829         scrarea_queue_winredraw(curarea);
1830 }
1831
1832 void image_viewcentre(void)
1833 {
1834         float size, min[2], max[2], d[2], xim=256.0f, yim=256.0f;
1835
1836         if( is_uv_tface_editing_allowed()==0 ) return;
1837
1838         if (!minmax_tface_uv(min, max)) return;
1839
1840         if(G.sima->image && G.sima->image->ibuf) {
1841                 xim= G.sima->image->ibuf->x;
1842                 yim= G.sima->image->ibuf->y;
1843         }
1844
1845         G.sima->xof= (int) (((min[0] + max[0])*0.5f - 0.5f)*xim);
1846         G.sima->yof= (int) (((min[1] + max[1])*0.5f - 0.5f)*yim);
1847
1848         d[0] = max[0] - min[0];
1849         d[1] = max[1] - min[1];
1850         size= 0.5*MAX2(d[0], d[1])*MAX2(xim, yim)/256.0f;
1851         
1852         if(size<=0.01) size= 0.01;
1853
1854         G.sima->zoom= 0.7/size;
1855
1856         calc_image_view(G.sima, 'p');
1857
1858         scrarea_queue_winredraw(curarea);
1859 }
1860
1861
1862 /* *********************** render callbacks ***************** */
1863
1864 /* set on initialize render, only one render output to imagewindow can exist, so the global isnt dangerous yet :) */
1865 static ScrArea *image_area= NULL;
1866
1867 /* can get as well the full picture, as the parts while rendering */
1868 static void imagewindow_progress(ScrArea *sa, RenderResult *rr, volatile rcti *renrect)
1869 {
1870         SpaceImage *sima= sa->spacedata.first;
1871         float x1, y1, *rectf= NULL;
1872         unsigned int *rect32= NULL;
1873         int ymin, ymax, xmin, xmax;
1874         
1875         /* if renrect argument, we only display scanlines */
1876         if(renrect) {
1877                 /* if ymax==recty, rendering of layer is ready, we should not draw, other things happen... */
1878                 if(rr->renlay==NULL || renrect->ymax>=rr->recty)
1879                         return;
1880                 
1881                 /* xmin here is first subrect x coord, xmax defines subrect width */
1882                 xmin = renrect->xmin;
1883                 xmax = renrect->xmax - xmin;
1884                 if (xmax<2) return;
1885                 
1886                 ymin= renrect->ymin;
1887                 ymax= renrect->ymax - ymin;
1888                 if(ymax<2)
1889                         return;
1890                 renrect->ymin= renrect->ymax;
1891         }
1892         else {
1893                 xmin = ymin = 0;
1894                 xmax = rr->rectx - 2*rr->crop;
1895                 ymax = rr->recty - 2*rr->crop;
1896         }
1897         
1898         /* image window cruft */
1899         
1900         /* find current float rect for display, first case is after composit... still weak */
1901         if(rr->rectf)
1902                 rectf= rr->rectf;
1903         else {
1904                 if(rr->rect32)
1905                         rect32= rr->rect32;
1906                 else {
1907                         if(rr->renlay==NULL || rr->renlay->rectf==NULL) return;
1908                         rectf= rr->renlay->rectf;
1909                 }
1910         }
1911         if(rectf) {
1912                 /* if scanline updates... */
1913                 rectf+= 4*(rr->rectx*ymin + xmin);
1914                 
1915                 /* when rendering more pixels than needed, we crop away cruft */
1916                 if(rr->crop)
1917                         rectf+= 4*(rr->crop*rr->rectx + rr->crop);
1918         }
1919         
1920         /* tilerect defines drawing offset from (0,0) */
1921         /* however, tilerect (xmin, ymin) is first pixel */
1922         x1 = sima->centx + (rr->tilerect.xmin + rr->crop + xmin)*sima->zoom;
1923         y1 = sima->centy + (rr->tilerect.ymin + rr->crop + ymin)*sima->zoom;
1924         
1925         /* needed for gla draw */
1926         { rcti rct= sa->winrct; rct.ymax-= RW_HEADERY; glaDefine2DArea(&rct);}
1927
1928         glPixelZoom((float)sima->zoom, (float)sima->zoom);
1929         
1930         if(rect32)
1931                 glaDrawPixelsSafe(x1, y1, xmax, ymax, rr->rectx, GL_RGBA, GL_UNSIGNED_BYTE, rect32);
1932         else
1933                 glaDrawPixelsSafe(x1, y1, xmax, ymax, rr->rectx, GL_RGBA, GL_FLOAT, rectf);
1934         
1935         glPixelZoom(1.0, 1.0);
1936         
1937 }
1938
1939
1940 /* in render window; display a couple of scanlines of rendered image */
1941 static void imagewindow_progress_display_cb(RenderResult *rr, volatile rcti *rect)
1942 {
1943         
1944         if (image_area) {
1945                 imagewindow_progress(image_area, rr, rect);
1946                 image_area->win_swap= WIN_BACK_OK;
1947                 screen_swapbuffers();
1948         }
1949 }
1950
1951 /* unused, init_display_cb is called on each render */
1952 static void imagewindow_clear_display_cb(RenderResult *rr)
1953 {
1954         if (image_area) {
1955         }
1956 }
1957
1958 static ScrArea *biggest_non_image_area(void)
1959 {
1960         ScrArea *sa, *big= NULL;
1961         int size, maxsize= 0;
1962         
1963         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1964                 if(sa->spacetype!=SPACE_IMAGE) {
1965                         size= sa->winx*sa->winy;
1966                         if(sa->winx > 10 && sa->winy > 10 && size > maxsize) {
1967                                 maxsize= size;
1968                                 big= sa;
1969                         }
1970                 }
1971         }
1972         return big;
1973 }
1974
1975 static ScrArea *biggest_area(void)
1976 {
1977         ScrArea *sa, *big= NULL;
1978         int size, maxsize= 0;
1979         
1980         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1981                 size= sa->winx*sa->winy;
1982                 if(size > maxsize) {
1983                         maxsize= size;
1984                         big= sa;
1985                 }
1986         }
1987         return big;
1988 }
1989
1990
1991 /* if R_DISPLAYIMAGE
1992       use Image Window showing Render Result
1993           else: turn largest non-image area into Image Window (not to frustrate texture or composite usage)
1994           else: then we use Image Window anyway...
1995    if R_DISPSCREEN
1996       make a new temp fullscreen area with Image Window
1997 */
1998
1999 static ScrArea *imagewindow_set_render_display(void)
2000 {
2001         ScrArea *sa;
2002         SpaceImage *sima;
2003         
2004         /* find an imagewindow showing render result */
2005         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2006                 if(sa->spacetype==SPACE_IMAGE) {
2007                         sima= sa->spacedata.first;
2008                         
2009                         if(sima->image && BLI_streq(sima->image->name, "Render Result") )
2010                                 break;
2011                 }
2012         }
2013         if(sa==NULL) {
2014                 /* find largest open non-image area */
2015                 sa= biggest_non_image_area();
2016                 if(sa) {
2017                         newspace(sa, SPACE_IMAGE);
2018                         sima= sa->spacedata.first;
2019                         
2020                         /* makes ESC go back to prev space */
2021                         sima->flag |= SI_PREVSPACE;
2022                 }
2023                 else {
2024                         /* use any area of decent size */
2025                         sa= biggest_area();
2026                         if(sa->spacetype!=SPACE_IMAGE) {
2027                                 newspace(sa, SPACE_IMAGE);
2028                                 sima= sa->spacedata.first;
2029                                 
2030                                 /* makes ESC go back to prev space */
2031                                 sima->flag |= SI_PREVSPACE;
2032                         }
2033                 }
2034         }
2035         
2036         sima= sa->spacedata.first;
2037         
2038         /* get the correct image, and scale it */
2039         sima->image = (Image *)find_id("IM", "Render Result");
2040         
2041         if(sima->image==NULL) {
2042                 Image *ima= alloc_libblock(&G.main->image, ID_IM, "Render Result");
2043                 strcpy(ima->name, "Render Result");
2044                 ima->ok= 1;
2045                 ima->xrep= ima->yrep= 1;
2046                 sima->image= ima;
2047         }
2048         else if(sima->image->id.us==0)  /* well... happens on reload, dunno yet what todo, imagewindow cannot be user when hidden*/
2049                 sima->image->id.us= 1;
2050         
2051         IMB_freeImBuf(sima->image->ibuf);
2052         sima->image->ibuf= NULL;
2053         
2054         if(G.displaymode==R_DISPLAYSCREEN) {
2055                 if(sa->full==0) {
2056                         sima->flag |= SI_FULLWINDOW;
2057                         /* fullscreen works with lousy curarea */
2058                         curarea= sa;
2059                         area_fullscreen();
2060                         sa= curarea;
2061                 }
2062         }
2063         
2064         return sa;
2065 }
2066
2067 static void imagewindow_init_display_cb(RenderResult *rr)
2068 {
2069         
2070         image_area= imagewindow_set_render_display();
2071         
2072         if(image_area) {
2073                 SpaceImage *sima= image_area->spacedata.first;
2074                 
2075                 areawinset(image_area->win);
2076                 
2077                 /* calc location using original size (tiles don't tell) */
2078                 sima->centx= (image_area->winx - sima->zoom*(float)rr->rectx)/2.0f;
2079                 sima->centy= (image_area->winy - sima->zoom*(float)rr->recty)/2.0f;
2080                 
2081                 sima->centx-= sima->zoom*sima->xof;
2082                 sima->centy-= sima->zoom*sima->yof;
2083                 
2084                 drawimagespace(image_area, sima);
2085                 if(image_area->headertype) scrarea_do_headdraw(image_area);
2086                 screen_swapbuffers();
2087                 
2088                 allqueue(REDRAWIMAGE, 0);       /* redraw in end */
2089         }
2090 }
2091
2092 /* coming from BIF_toggle_render_display() */
2093 void imagewindow_toggle_render(void)
2094 {
2095         ScrArea *sa;
2096         
2097         /* check if any imagewindow is showing temporal render output */
2098         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2099                 if(sa->spacetype==SPACE_IMAGE) {
2100                         SpaceImage *sima= sa->spacedata.first;
2101                         
2102                         if(sima->image && BLI_streq(sima->image->name, "Render Result") )
2103                                 if(sima->flag & (SI_PREVSPACE|SI_FULLWINDOW))
2104                                         break;
2105                 }
2106         }
2107         if(sa) {
2108                 addqueue(sa->win, ESCKEY, 1);   /* also returns from fullscreen */
2109         }
2110         else {
2111                 sa= imagewindow_set_render_display();
2112                 scrarea_queue_headredraw(sa);
2113                 scrarea_queue_winredraw(sa);
2114         }
2115 }
2116
2117 static void imagewindow_renderinfo_cb(RenderStats *rs)
2118 {
2119         
2120         if(image_area) {
2121                 SpaceImage *sima= image_area->spacedata.first;
2122                 
2123                 if(sima->info_str==NULL)
2124                         sima->info_str= MEM_callocN(RW_MAXTEXT, "info str imagewin");
2125                 
2126                 if(rs)
2127                         make_renderinfo_string(rs, sima->info_str);
2128
2129                 imagewindow_draw_renderinfo(image_area);
2130                 
2131                 image_area->win_swap= WIN_BACK_OK;
2132                 screen_swapbuffers();
2133         }
2134 }
2135
2136
2137 void imagewindow_render_callbacks(Render *re)
2138 {
2139         RE_display_init_cb(re, imagewindow_init_display_cb);
2140         RE_display_draw_cb(re, imagewindow_progress_display_cb);
2141         RE_display_clear_cb(re, imagewindow_clear_display_cb);
2142         RE_stats_draw_cb(re, imagewindow_renderinfo_cb);        
2143 }
2144