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