Potential fix for bug #4459:
[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(xPos, 5.0, ICON_STICKY2_UVS);
678                 xPos = 25.0;
679         }
680         else if(!(G.sima->flag & SI_LOCALSTICKY)) {
681                 BIF_icon_draw(xPos, 5.0, ICON_STICKY_UVS);
682                 xPos = 25.0;
683         }
684
685         if(G.sima->flag & SI_SELACTFACE) {
686                 BIF_icon_draw(xPos, 5.0, ICON_DRAW_UVFACES);
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                 char str[64];
925
926                 sprintf(str, "Image: size %d x %d", G.sima->image->ibuf->x, G.sima->image->ibuf->y);
927                 if(G.sima->image->ibuf->rect_float)
928                         strcat(str, " 4x32 bits");
929                 else 
930                         strcat(str, " 4x8 bits");
931                 
932                 uiDefBut(block, LABEL, B_NOP, str,              10,180,300,19, 0, 0, 0, 0, 0, "");
933
934                 uiBlockBeginAlign(block);
935                 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");
936                 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");
937                 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");
938                 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");
939                 uiBlockEndAlign(block);
940
941                 uiBlockBeginAlign(block);
942                 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");
943                 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");
944                 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");
945                 uiBlockBeginAlign(block);
946         }
947
948         image_editvertex_buts(block);
949 }
950
951 static void image_panel_paint(short cntrl)      // IMAGE_HANDLER_PROPERTIES
952 {
953         /* B_SIMABRUSHCHANGE only redraws and eats the mouse messages  */
954         /* so that LEFTMOUSE does not 'punch' through the floating panel */
955         /* B_SIMANOTHING */
956         ImagePaintTool *tool= &Gip.tool[Gip.current];
957         uiBlock *block;
958         ID *id;
959
960         block= uiNewBlock(&curarea->uiblocks, "image_panel_paint", UI_EMBOSS, UI_HELV, curarea->win);
961         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
962         uiSetPanelHandler(IMAGE_HANDLER_PAINT);  // for close and esc
963         if(uiNewPanel(curarea, block, "Image Paint", "Image", 10, 230, 318, 204)==0)
964                 return;
965
966         uiBlockBeginAlign(block);
967         uiDefButF(block, COL, B_VPCOLSLI, "",           979,160,230,19, tool->rgba, 0, 0, 0, 0, "");
968         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");
969         uiDefButI(block, NUMSLI, B_SIMANOTHING , "Size ",               979,120,230,19, &tool->size, 2, 64, 0, 0, "The size of the brush");
970         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");
971
972         if(Gip.current == IMAGEPAINT_BRUSH || Gip.current == IMAGEPAINT_SMEAR)
973                 uiDefButF(block, NUMSLI, B_SIMANOTHING , "Stepsize ",979,80,230,19, &tool->timing, 1.0, 100.0, 0, 0, "Repeating Paint On %of Brush diameter");
974         else
975                 uiDefButF(block, NUMSLI, B_SIMANOTHING , "Flow ",       979,80,230,19, &tool->timing, 1.0, 100.0, 0, 0, "Paint Flow for Air Brush");
976         uiBlockEndAlign(block);
977
978         uiBlockBeginAlign(block);
979         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Brush",               890,160,80,19, &Gip.current, 7.0, IMAGEPAINT_BRUSH, 0, 0, "Brush");
980         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "AirBrush",            890,140,80,19, &Gip.current, 7.0, IMAGEPAINT_AIRBRUSH, 0, 0, "AirBrush");
981         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Soften",              890,120,80,19, &Gip.current, 7.0, IMAGEPAINT_SOFTEN, 0, 0, "Soften");
982         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Aux AB1",             890,100,80,19, &Gip.current, 7.0, IMAGEPAINT_AUX1, 0, 0, "Auxiliary Air Brush1");
983         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Aux AB2",             890,80,80,19, &Gip.current, 7.0, IMAGEPAINT_AUX2, 0, 0, "Auxiliary Air Brush2");        
984         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Smear",               890,60,80,19, &Gip.current, 7.0, IMAGEPAINT_SMEAR, 0, 0, "Smear");      
985         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"); 
986         uiBlockEndAlign(block);
987
988         uiBlockBeginAlign(block);       
989         id= (ID*)Gip.clone.image;
990         std_libbuttons(block, 979, 40, 0, NULL, B_SIMACLONEBROWSE, ID_IM, 0, id, 0, &G.sima->menunr, 0, 0, B_SIMACLONEDELETE, 0, 0);
991         uiDefButF(block, NUMSLI, B_SIMABRUSHCHANGE, "B ",979,20,230,19, &Gip.clone.alpha , 0.0, 1.0, 0, 0, "Blend clone image");
992         uiBlockEndAlign(block);
993
994 #if 0
995         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");
996         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");
997 #endif
998         uiDefButBitS(block, TOG|BIT, IMAGEPAINT_TORUS, B_SIMABRUSHCHANGE, "Wrap", 890,1,50,19, &Gip.flag, 0, 0, 0, 0, "Enables torus wrapping");
999 }
1000
1001 static void image_panel_curves_reset(void *cumap_v, void *unused)
1002 {
1003         CurveMapping *cumap = cumap_v;
1004         int a;
1005         
1006         for(a=0; a<CM_TOT; a++)
1007                 curvemap_reset(cumap->cm+a, &cumap->clipr);
1008         
1009         cumap->black[0]=cumap->black[1]=cumap->black[2]= 0.0f;
1010         cumap->white[0]=cumap->white[1]=cumap->white[2]= 1.0f;
1011         curvemapping_set_black_white(cumap, NULL, NULL);
1012         
1013         curvemapping_changed(cumap, 0);
1014         curvemapping_do_image(cumap, G.sima->image);
1015         
1016         allqueue(REDRAWIMAGE, 0);
1017 }
1018
1019
1020 static void image_panel_curves(short cntrl)     // IMAGE_HANDLER_PROPERTIES
1021 {
1022         uiBlock *block;
1023         uiBut *bt;
1024         
1025         block= uiNewBlock(&curarea->uiblocks, "image_panel_curves", UI_EMBOSS, UI_HELV, curarea->win);
1026         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1027         uiSetPanelHandler(IMAGE_HANDLER_CURVES);  // for close and esc
1028         if(uiNewPanel(curarea, block, "Curves", "Image", 10, 450, 318, 204)==0)
1029                 return;
1030         
1031         if (G.sima->image && G.sima->image->ibuf) {
1032                 rctf rect;
1033                 
1034                 if(G.sima->cumap==NULL)
1035                         G.sima->cumap= curvemapping_add(4, 0.0f, 0.0f, 1.0f, 1.0f);
1036                 
1037                 rect.xmin= 110; rect.xmax= 310;
1038                 rect.ymin= 10; rect.ymax= 200;
1039                 curvemap_buttons(block, G.sima->cumap, 'c', B_SIMACURVES, B_SIMAGEDRAW, &rect);
1040                 
1041                 bt=uiDefBut(block, BUT, B_SIMARANGE, "Reset",   10, 160, 90, 19, NULL, 0.0f, 0.0f, 0, 0, "Reset Black/White point and curves");
1042                 uiButSetFunc(bt, image_panel_curves_reset, G.sima->cumap, NULL);
1043                 
1044                 uiBlockBeginAlign(block);
1045                 uiDefButF(block, NUM, B_SIMARANGE, "Min R:",    10, 120, 90, 19, G.sima->cumap->black, -1000.0f, 1000.0f, 10, 2, "Black level");
1046                 uiDefButF(block, NUM, B_SIMARANGE, "Min G:",    10, 100, 90, 19, G.sima->cumap->black+1, -1000.0f, 1000.0f, 10, 2, "Black level");
1047                 uiDefButF(block, NUM, B_SIMARANGE, "Min B:",    10, 80, 90, 19, G.sima->cumap->black+2, -1000.0f, 1000.0f, 10, 2, "Black level");
1048                 
1049                 uiBlockBeginAlign(block);
1050                 uiDefButF(block, NUM, B_SIMARANGE, "Max R:",    10, 50, 90, 19, G.sima->cumap->white, -1000.0f, 1000.0f, 10, 2, "White level");
1051                 uiDefButF(block, NUM, B_SIMARANGE, "Max G:",    10, 30, 90, 19, G.sima->cumap->white+1, -1000.0f, 1000.0f, 10, 2, "White level");
1052                 uiDefButF(block, NUM, B_SIMARANGE, "Max B:",    10, 10, 90, 19, G.sima->cumap->white+2, -1000.0f, 1000.0f, 10, 2, "White level");
1053                 
1054         }
1055 }
1056
1057 /* are there curves? curves visible? and curves do something? */
1058 static int image_curves_active(ScrArea *sa)
1059 {
1060         SpaceImage *sima= sa->spacedata.first;
1061
1062         if(sima->cumap) {
1063                 if(curvemapping_RGBA_does_something(sima->cumap)) {
1064                         short a;
1065                         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1066                                 if(sima->blockhandler[a] == IMAGE_HANDLER_CURVES)
1067                                         return 1;
1068                         }
1069                 }
1070         }
1071         return 0;
1072 }
1073
1074 void image_preview_event(int event)
1075 {
1076         int exec= 0;
1077         
1078
1079         if(event==0) {
1080                 G.scene->r.scemode &= ~R_COMP_CROP;
1081                 exec= 1;
1082         }
1083         else if(event==2 || (G.scene->r.scemode & R_COMP_CROP)==0) {
1084                 if(image_preview_active(curarea, NULL, NULL)) {
1085                         G.scene->r.scemode |= R_COMP_CROP;
1086                         exec= 1;
1087                 }
1088         }
1089         
1090         if(exec) {
1091                 ScrArea *sa;
1092                 
1093                 ntreeCompositTagGenerators(G.scene->nodetree);
1094         
1095                 for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
1096                         if(sa->spacetype==SPACE_NODE) {
1097                                 addqueue(sa->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
1098                                 break;
1099                         }
1100                 }
1101         }       
1102 }
1103
1104
1105 /* nothing drawn here, we use it to store values */
1106 static void preview_cb(struct ScrArea *sa, struct uiBlock *block)
1107 {
1108         rctf dispf;
1109         rcti *disprect= &G.scene->r.disprect;
1110         int winx= (G.scene->r.size*G.scene->r.xsch)/100;
1111         int winy= (G.scene->r.size*G.scene->r.ysch)/100;
1112         short mval[2];
1113         
1114         if(G.scene->r.mode & R_BORDER) {
1115                 winx*= (G.scene->r.border.xmax - G.scene->r.border.xmin);
1116                 winy*= (G.scene->r.border.ymax - G.scene->r.border.ymin);
1117         }
1118         
1119         /* while dragging we don't update the rects */
1120         if(block->panel->flag & PNL_SELECT)
1121                 return;
1122         if(get_mbut() & M_MOUSE)
1123                 return;
1124
1125         BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
1126         ui_graphics_to_window_rct(sa->win, &dispf, disprect);
1127         
1128         /* correction for gla draw */
1129         BLI_translate_rcti(disprect, -curarea->winrct.xmin, -curarea->winrct.ymin);
1130         
1131         calc_image_view(G.sima, 'p');
1132 //      printf("winrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1133         /* map to image space coordinates */
1134         mval[0]= disprect->xmin; mval[1]= disprect->ymin;
1135         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmin, &dispf.ymin);
1136         mval[0]= disprect->xmax; mval[1]= disprect->ymax;
1137         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmax, &dispf.ymax);
1138         
1139         /* map to render coordinates */
1140         disprect->xmin= dispf.xmin;
1141         disprect->xmax= dispf.xmax;
1142         disprect->ymin= dispf.ymin;
1143         disprect->ymax= dispf.ymax;
1144         
1145         CLAMP(disprect->xmin, 0, winx);
1146         CLAMP(disprect->xmax, 0, winx);
1147         CLAMP(disprect->ymin, 0, winy);
1148         CLAMP(disprect->ymax, 0, winy);
1149 //      printf("drawrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1150         
1151         image_preview_event(1);
1152 }
1153
1154 static int is_preview_allowed(ScrArea *cur)
1155 {
1156         ScrArea *sa;
1157
1158         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
1159                 if(sa!=cur && sa->spacetype==SPACE_IMAGE) {
1160                         if(image_preview_active(sa, NULL, NULL))
1161                            return 0;
1162                 }
1163         }
1164         return 1;
1165 }
1166
1167 static void image_panel_preview(ScrArea *sa, short cntrl)       // IMAGE_HANDLER_PREVIEW
1168 {
1169         uiBlock *block;
1170         SpaceImage *sima= sa->spacedata.first;
1171         int ofsx, ofsy;
1172         
1173         if(is_preview_allowed(sa)==0) {
1174                 rem_blockhandler(sa, IMAGE_HANDLER_PREVIEW);
1175                 return;
1176         }
1177         
1178         block= uiNewBlock(&sa->uiblocks, "image_panel_preview", UI_EMBOSS, UI_HELV, sa->win);
1179         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | UI_PNL_SCALE | cntrl);
1180         uiSetPanelHandler(IMAGE_HANDLER_PREVIEW);  // for close and esc
1181         
1182         ofsx= -150+(sa->winx/2)/sima->blockscale;
1183         ofsy= -100+(sa->winy/2)/sima->blockscale;
1184         if(uiNewPanel(sa, block, "Preview", "Image", ofsx, ofsy, 300, 200)==0) return;
1185         
1186         uiBlockSetDrawExtraFunc(block, preview_cb);
1187         
1188 }
1189
1190 static void image_blockhandlers(ScrArea *sa)
1191 {
1192         SpaceImage *sima= sa->spacedata.first;
1193         short a;
1194
1195         /* warning; blocks need to be freed each time, handlers dont remove  */
1196         uiFreeBlocksWin(&sa->uiblocks, sa->win);
1197         
1198         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1199                 switch(sima->blockhandler[a]) {
1200
1201                 case IMAGE_HANDLER_PROPERTIES:
1202                         image_panel_properties(sima->blockhandler[a+1]);
1203                         break;
1204                 case IMAGE_HANDLER_PAINT:
1205                         image_panel_paint(sima->blockhandler[a+1]);
1206                         break;          
1207                 case IMAGE_HANDLER_CURVES:
1208                         image_panel_curves(sima->blockhandler[a+1]);
1209                         break;          
1210                 case IMAGE_HANDLER_PREVIEW:
1211                         image_panel_preview(sa, sima->blockhandler[a+1]);
1212                         break;          
1213                 }
1214                 /* clear action value for event */
1215                 sima->blockhandler[a+1]= 0;
1216         }
1217         uiDrawBlocksPanels(sa, 0);
1218 }
1219
1220 static void imagespace_grid(SpaceImage *sima)
1221 {
1222         float gridsize, gridstep= 1.0f/32.0f;
1223         float fac, blendfac;
1224         
1225         gridsize= sima->zoom;
1226         
1227         calc_image_view(sima, 'f');
1228         myortho2(sima->v2d.cur.xmin, sima->v2d.cur.xmax, sima->v2d.cur.ymin, sima->v2d.cur.ymax);
1229         
1230         BIF_ThemeColorShade(TH_BACK, 20);
1231         glRectf(0.0, 0.0, 1.0, 1.0);
1232         
1233         if(gridsize<=0.0f) return;
1234         
1235         if(gridsize<1.0f) {
1236                 while(gridsize<1.0f) {
1237                         gridsize*= 4.0;
1238                         gridstep*= 4.0;
1239                 }
1240         }
1241         else {
1242                 while(gridsize>=4.0f) {
1243                         gridsize/= 4.0;
1244                         gridstep/= 4.0;
1245                 }
1246         }
1247         
1248         /* the fine resolution level */
1249         blendfac= 0.25*gridsize - floor(0.25*gridsize);
1250         CLAMP(blendfac, 0.0, 1.0);
1251         BIF_ThemeColorShade(TH_BACK, (int)(20.0*(1.0-blendfac)));
1252         
1253         fac= 0.0f;
1254         glBegin(GL_LINES);
1255         while(fac<1.0) {
1256                 glVertex2f(0.0f, fac);
1257                 glVertex2f(1.0f, fac);
1258                 glVertex2f(fac, 0.0f);
1259                 glVertex2f(fac, 1.0f);
1260                 fac+= gridstep;
1261         }
1262         
1263         /* the large resolution level */
1264         BIF_ThemeColor(TH_BACK);
1265         
1266         fac= 0.0f;
1267         while(fac<1.0) {
1268                 glVertex2f(0.0f, fac);
1269                 glVertex2f(1.0f, fac);
1270                 glVertex2f(fac, 0.0f);
1271                 glVertex2f(fac, 1.0f);
1272                 fac+= 4.0*gridstep;
1273         }
1274         glEnd();
1275         
1276 }
1277
1278 static void sima_draw_alpha_backdrop(SpaceImage *sima, float x1, float y1, float xsize, float ysize)
1279 {
1280         float tile= sima->zoom*15.0f;
1281         float x, y, maxx, maxy;
1282         
1283         glColor3ub(100, 100, 100);
1284         glRectf(x1, y1, x1 + sima->zoom*xsize, y1 + sima->zoom*ysize);
1285         glColor3ub(160, 160, 160);
1286         
1287         maxx= x1+sima->zoom*xsize;
1288         maxy= y1+sima->zoom*ysize;
1289         
1290         for(x=0; x<xsize; x+=30) {
1291                 for(y=0; y<ysize; y+=30) {
1292                         float fx= x1 + sima->zoom*x;
1293                         float fy= y1 + sima->zoom*y;
1294                         float tilex= tile, tiley= tile;
1295                         
1296                         if(fx+tile > maxx)
1297                                 tilex= maxx-fx;
1298                         if(fy+tile > maxy)
1299                                 tiley= maxy-fy;
1300                         
1301                         glRectf(fx, fy, fx + tilex, fy + tiley);
1302                 }
1303         }
1304         for(x=15; x<xsize; x+=30) {
1305                 for(y=15; y<ysize; y+=30) {
1306                         float fx= x1 + sima->zoom*x;
1307                         float fy= y1 + sima->zoom*y;
1308                         float tilex= tile, tiley= tile;
1309                         
1310                         if(fx+tile > maxx)
1311                                 tilex= maxx-fx;
1312                         if(fy+tile > maxy)
1313                                 tiley= maxy-fy;
1314                         
1315                         glRectf(fx, fy, fx + tilex, fy + tiley);
1316                 }
1317         }
1318 }
1319
1320 static void sima_draw_alpha_pixels(float x1, float y1, int rectx, int recty, unsigned int *recti)
1321 {
1322         
1323         /* swap bytes, so alpha is most significant one, then just draw it as luminance int */
1324         if(G.order==B_ENDIAN)
1325                 glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
1326         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_UNSIGNED_INT, recti);
1327         glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
1328 }
1329
1330 static void sima_draw_alpha_pixelsf(float x1, float y1, int rectx, int recty, float *rectf)
1331 {
1332         float *trectf= MEM_mallocN(rectx*recty*4, "temp");
1333         int a, b;
1334         
1335         for(a= rectx*recty -1, b= 4*a+3; a>=0; a--, b-=4)
1336                 trectf[a]= rectf[b];
1337         
1338         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, trectf);
1339         MEM_freeN(trectf);
1340         /* ogl trick below is slower... (on ATI 9600) */
1341 //      glColorMask(1, 0, 0, 0);
1342 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+3);
1343 //      glColorMask(0, 1, 0, 0);
1344 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+2);
1345 //      glColorMask(0, 0, 1, 0);
1346 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+1);
1347 //      glColorMask(1, 1, 1, 1);
1348 }
1349
1350 static void sima_draw_zbuf_pixels(float x1, float y1, int rectx, int recty, int *recti)
1351 {
1352         if(recti==NULL)
1353                 return;
1354         
1355         /* zbuffer values are signed, so we need to shift color range */
1356         glPixelTransferf(GL_RED_SCALE, 0.5f);
1357         glPixelTransferf(GL_GREEN_SCALE, 0.5f);
1358         glPixelTransferf(GL_BLUE_SCALE, 0.5f);
1359         glPixelTransferf(GL_RED_BIAS, 0.5f);
1360         glPixelTransferf(GL_GREEN_BIAS, 0.5f);
1361         glPixelTransferf(GL_BLUE_BIAS, 0.5f);
1362         
1363         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_INT, recti);
1364         
1365         glPixelTransferf(GL_RED_SCALE, 1.0f);
1366         glPixelTransferf(GL_GREEN_SCALE, 1.0f);
1367         glPixelTransferf(GL_BLUE_SCALE, 1.0f);
1368         glPixelTransferf(GL_RED_BIAS, 0.0f);
1369         glPixelTransferf(GL_GREEN_BIAS, 0.0f);
1370         glPixelTransferf(GL_BLUE_BIAS, 0.0f);
1371 }
1372
1373 static void sima_draw_zbuffloat_pixels(float x1, float y1, int rectx, int recty, float *rect_float)
1374 {
1375         float bias, scale, *rectf, clipend;
1376         int a;
1377         
1378         if(rect_float==NULL)
1379                 return;
1380         
1381         if(G.scene->camera && G.scene->camera->type==OB_CAMERA) {
1382                 bias= ((Camera *)G.scene->camera->data)->clipsta;
1383                 clipend= ((Camera *)G.scene->camera->data)->clipend;
1384                 scale= 1.0f/(clipend-bias);
1385         }
1386         else {
1387                 bias= 0.1f;
1388                 scale= 0.01f;
1389                 clipend= 100.0f;
1390         }
1391         
1392         rectf= MEM_mallocN(rectx*recty*4, "temp");
1393         for(a= rectx*recty -1; a>=0; a--) {
1394                 if(rect_float[a]>clipend)
1395                         rectf[a]= 0.0f;
1396                 else if(rect_float[a]<bias)
1397                         rectf[a]= 1.0f;
1398                 else {
1399                         rectf[a]= 1.0f - (rect_float[a]-bias)*scale;
1400                         rectf[a]*= rectf[a];
1401                 }
1402         }
1403         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, rectf);
1404         
1405         MEM_freeN(rectf);
1406 }
1407
1408 static void imagewindow_draw_renderinfo(ScrArea *sa)
1409 {
1410         SpaceImage *sima= sa->spacedata.first;
1411         rcti rect;
1412         float colf[3];
1413         
1414         if(sima->info_str==NULL)
1415                 return;
1416         
1417         rect= sa->winrct;
1418         rect.ymin= rect.ymax-RW_HEADERY;
1419         
1420         glaDefine2DArea(&rect);
1421         
1422         /* clear header rect */
1423         BIF_GetThemeColor3fv(TH_BACK, colf);
1424         glClearColor(colf[0]+0.1f, colf[1]+0.1f, colf[2]+0.1f, 1.0); 
1425         glClear(GL_COLOR_BUFFER_BIT);
1426         
1427         BIF_ThemeColor(TH_TEXT_HI);
1428         glRasterPos2i(12, 5);
1429         BMF_DrawString(G.fonts, sima->info_str);
1430 }
1431
1432 void drawimagespace(ScrArea *sa, void *spacedata)
1433 {
1434         SpaceImage *sima= spacedata;
1435         ImBuf *ibuf= NULL;
1436         float col[3];
1437         unsigned int *rect;
1438         float x1, y1;
1439         short sx, sy, dx, dy, show_render= 0;
1440         
1441                 /* If derived data is used then make sure that object
1442                  * is up-to-date... might not be the case because updates
1443                  * are normally done in drawview and could get here before
1444                  * drawing a View3D.
1445                  */
1446         if (!G.obedit && OBACT && (sima->flag & SI_DRAWSHADOW)) {
1447                 object_handle_update(OBACT);
1448         }
1449
1450         BIF_GetThemeColor3fv(TH_BACK, col);
1451         glClearColor(col[0], col[1], col[2], 0.0);
1452         glClear(GL_COLOR_BUFFER_BIT);
1453
1454         bwin_clear_viewmat(sa->win);    /* clear buttons view */
1455         glLoadIdentity();
1456         
1457         if(sima->image && BLI_streq(sima->image->id.name+2, "Render Result") )
1458                 show_render= 1;
1459         
1460         what_image(sima);
1461         
1462         if(sima->image) {
1463                 if(sima->image->ibuf==NULL && show_render==0) {
1464                         load_image(sima->image, IB_rect, G.sce, G.scene->r.cfra);
1465                         scrarea_queue_headredraw(sa);   /* update header for image options */
1466                 }
1467                 
1468                 tag_image_time(sima->image);
1469                 ibuf= sima->image->ibuf;
1470         }
1471         
1472         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL)) {
1473                 imagespace_grid(sima);
1474                 if(show_render==0)
1475                         draw_tfaces();
1476         }
1477         else {
1478                 float xim, yim, xoffs=0.0f, yoffs= 0.0f;
1479                 
1480                 if(image_preview_active(sa, &xim, &yim)) {
1481                         xoffs= G.scene->r.disprect.xmin;
1482                         yoffs= G.scene->r.disprect.ymin;
1483                         glColor3ub(0,0,0);
1484                         calc_image_view(sima, 'f');     
1485                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
1486                         glRectf(0.0f, 0.0f, 1.0f, 1.0f);
1487                         glLoadIdentity();
1488                 }
1489                 else {
1490                         xim= ibuf->x; yim= ibuf->y;
1491                 }
1492                 
1493                 /* calc location */
1494                 x1= sima->zoom*xoffs + ((float)sa->winx - sima->zoom*(float)xim)/2.0f;
1495                 y1= sima->zoom*yoffs + ((float)sa->winy - sima->zoom*(float)yim)/2.0f;
1496         
1497                 x1-= sima->zoom*sima->xof;
1498                 y1-= sima->zoom*sima->yof;
1499                 
1500                 /* needed for gla draw */
1501                 if(show_render) { 
1502                         rcti rct= sa->winrct; 
1503                         
1504                         imagewindow_draw_renderinfo(sa);        /* calls glaDefine2DArea too */
1505                         
1506                         rct.ymax-=RW_HEADERY; 
1507                         glaDefine2DArea(&rct);
1508                 }
1509                 else glaDefine2DArea(&sa->winrct);
1510                 
1511                 glPixelZoom((float)sima->zoom, (float)sima->zoom);
1512                                 
1513                 if(sima->flag & SI_EDITTILE) {
1514                         glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1515                         
1516                         glPixelZoom(1.0, 1.0);
1517                         
1518                         dx= ibuf->x/sima->image->xrep;
1519                         dy= ibuf->y/sima->image->yrep;
1520                         sy= (sima->curtile / sima->image->xrep);
1521                         sx= sima->curtile - sy*sima->image->xrep;
1522         
1523                         sx*= dx;
1524                         sy*= dy;
1525                         
1526                         calc_image_view(sima, 'p');     /* pixel */
1527                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
1528                         
1529                         cpack(0x0);
1530                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx,  sy,  sx+dx-1,  sy+dy-1); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1531                         cpack(0xFFFFFF);
1532                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx+1,  sy+1,  sx+dx,  sy+dy); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1533                 }
1534                 else if(sima->mode==SI_TEXTURE) {
1535                         
1536                         if(sima->image->tpageflag & IMA_TILES) {
1537                                 
1538                                 /* just leave this a while */
1539                                 if(sima->image->xrep<1) return;
1540                                 if(sima->image->yrep<1) return;
1541                                 
1542                                 if(sima->curtile >= sima->image->xrep*sima->image->yrep) 
1543                                         sima->curtile = sima->image->xrep*sima->image->yrep - 1; 
1544                                 
1545                                 dx= ibuf->x/sima->image->xrep;
1546                                 dy= ibuf->y/sima->image->yrep;
1547                                 
1548                                 sy= (sima->curtile / sima->image->xrep);
1549                                 sx= sima->curtile - sy*sima->image->xrep;
1550                 
1551                                 sx*= dx;
1552                                 sy*= dy;
1553                                 
1554                                 rect= get_part_from_ibuf(ibuf, sx, sy, sx+dx, sy+dy);
1555                                 
1556                                 /* rect= ibuf->rect; */
1557                                 for(sy= 0; sy+dy<=ibuf->y; sy+= dy) {
1558                                         for(sx= 0; sx+dx<=ibuf->x; sx+= dx) {
1559                                                 glaDrawPixelsSafe(x1+sx*sima->zoom, y1+sy*sima->zoom, dx, dy, dx, GL_RGBA, GL_UNSIGNED_BYTE, rect);
1560                                         }
1561                                 }
1562                                 
1563                                 MEM_freeN(rect);
1564                         }
1565                         else {
1566                                 /* this part is generic image display */
1567                                 if(sima->flag & SI_SHOW_ALPHA) {
1568                                         if(ibuf->rect)
1569                                                 sima_draw_alpha_pixels(x1, y1, ibuf->x, ibuf->y, ibuf->rect);
1570                                         else if(ibuf->rect_float)
1571                                                 sima_draw_alpha_pixelsf(x1, y1, ibuf->x, ibuf->y, ibuf->rect_float);
1572                                 }
1573                                 else if(sima->flag & SI_SHOW_ZBUF) {
1574                                         if(ibuf->zbuf)
1575                                                 sima_draw_zbuf_pixels(x1, y1, ibuf->x, ibuf->y, ibuf->zbuf);
1576                                         else
1577                                                 sima_draw_zbuffloat_pixels(x1, y1, ibuf->x, ibuf->y, ibuf->zbuf_float);
1578                                 }
1579                                 else {
1580                                         if(sima->flag & SI_USE_ALPHA) {
1581                                                 sima_draw_alpha_backdrop(sima, x1, y1, (float)ibuf->x, (float)ibuf->y);
1582                                                 glEnable(GL_BLEND);
1583                                         }
1584                                         
1585                                         /* detect if we need to redo the curve map. 
1586                                            ibuf->rect is zero for compositor and render results after change 
1587                                            convert to 32 bits always... drawing float rects isnt supported well (atis)
1588                                         */
1589                                         if(ibuf->rect_float) {
1590                                                 if(ibuf->rect==NULL) {
1591                                                         if(image_curves_active(sa))
1592                                                                 curvemapping_do_image(G.sima->cumap, G.sima->image);
1593                                                         else 
1594                                                                 IMB_rect_from_float(ibuf);
1595                                                 }
1596                                         }
1597
1598                                         if(ibuf->rect)
1599                                                 glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1600 //                                      else
1601 //                                              glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_FLOAT, ibuf->rect_float);
1602                                         
1603                                         if(sima->flag & SI_USE_ALPHA)
1604                                                 glDisable(GL_BLEND);
1605                                 }
1606                         }
1607                         
1608                         if(Gip.current == IMAGEPAINT_CLONE) {
1609                                 int w, h;
1610                                 unsigned char *clonerect;
1611
1612                                 /* this is not very efficient, but glDrawPixels doesn't allow
1613                                    drawing with alpha */
1614                                 clonerect= alloc_alpha_clone_image(&w, &h);
1615
1616                                 if(clonerect) {
1617                                         int offx, offy;
1618                                         offx = sima->zoom*ibuf->x * + Gip.clone.offset[0];
1619                                         offy = sima->zoom*ibuf->y * + Gip.clone.offset[1];
1620
1621                                         glEnable(GL_BLEND);
1622                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1623                                         glaDrawPixelsSafe(x1 + offx, y1 + offy, w, h, w, GL_RGBA, GL_UNSIGNED_BYTE, clonerect);
1624                                         glDisable(GL_BLEND);
1625
1626                                         MEM_freeN(clonerect);
1627                                 }
1628                         }
1629                         
1630                         glPixelZoom(1.0, 1.0);
1631                         
1632                         if(show_render==0) 
1633                                 draw_tfaces();
1634                 }
1635
1636                 glPixelZoom(1.0, 1.0);
1637
1638                 calc_image_view(sima, 'f');     /* float */
1639         }
1640
1641         draw_image_transform(ibuf);
1642
1643         mywinset(sa->win);      /* restore scissor after gla call... */
1644         myortho2(-0.375, sa->winx-0.375, -0.375, sa->winy-0.375);
1645
1646         if(G.rendering==0) {
1647                 draw_image_view_tool();
1648                 draw_image_view_icon();
1649         }
1650         draw_area_emboss(sa);
1651
1652         /* it is important to end a view in a transform compatible with buttons */
1653         bwin_scalematrix(sa->win, sima->blockscale, sima->blockscale, sima->blockscale);
1654         if(!(G.rendering && show_render))
1655                 image_blockhandlers(sa);
1656
1657         sa->win_swap= WIN_BACK_OK;
1658 }
1659
1660 static void image_zoom_power_of_two(void)
1661 {
1662         /* Make zoom a power of 2 */
1663
1664         G.sima->zoom = 1 / G.sima->zoom;
1665         G.sima->zoom = log(G.sima->zoom) / log(2);
1666         G.sima->zoom = ceil(G.sima->zoom);
1667         G.sima->zoom = pow(2, G.sima->zoom);
1668         G.sima->zoom = 1 / G.sima->zoom;
1669 }
1670
1671 static void image_zoom_set_factor(float zoomfac)
1672 {
1673         SpaceImage *sima= curarea->spacedata.first;
1674         int width, height;
1675
1676         if (zoomfac <= 0.0f)
1677                 return;
1678
1679         sima->zoom *= zoomfac;
1680
1681         if (sima->zoom > 0.1f && sima->zoom < 4.0f)
1682                 return;
1683
1684         /* check zoom limits */
1685
1686         calc_image_view(G.sima, 'p');
1687         width= 256;
1688         height= 256;
1689         if (sima->image) {
1690                 if (sima->image->ibuf) {
1691                         float xim, yim;
1692                         /* I know a bit weak... but preview uses not actual image size */
1693                         if(image_preview_active(curarea, &xim, &yim)) {
1694                                 width= (int) xim;
1695                                 height= (int) yim;
1696                         }
1697                         else {
1698                                 width= sima->image->ibuf->x;
1699                                 height= sima->image->ibuf->y;
1700                         }
1701                 }
1702         }
1703         width *= sima->zoom;
1704         height *= sima->zoom;
1705
1706         if ((width < 4) && (height < 4))
1707                 sima->zoom /= zoomfac;
1708         else if((curarea->winrct.xmax - curarea->winrct.xmin) <= sima->zoom)
1709                 sima->zoom /= zoomfac;
1710         else if((curarea->winrct.ymax - curarea->winrct.ymin) <= sima->zoom)
1711                 sima->zoom /= zoomfac;
1712 }
1713
1714 void image_viewmove(int mode)
1715 {
1716         short mval[2], mvalo[2], zoom0;
1717         int oldcursor;
1718         Window *win;
1719         
1720         getmouseco_sc(mvalo);
1721         zoom0= G.sima->zoom;
1722         
1723         oldcursor=get_cursor();
1724         win=winlay_get_active_window();
1725         
1726         SetBlenderCursor(BC_NSEW_SCROLLCURSOR);
1727         
1728         while(get_mbut()&(L_MOUSE|M_MOUSE)) {
1729
1730                 getmouseco_sc(mval);
1731
1732                 if(mvalo[0]!=mval[0] || mvalo[1]!=mval[1]) {
1733                 
1734                         if(mode==0) {
1735                                 G.sima->xof += (mvalo[0]-mval[0])/G.sima->zoom;
1736                                 G.sima->yof += (mvalo[1]-mval[1])/G.sima->zoom;
1737                         }
1738                         else if (mode==1) {
1739                                 float factor;
1740
1741                                 factor= 1.0+(float)(mvalo[0]-mval[0]+mvalo[1]-mval[1])/300.0;
1742                                 image_zoom_set_factor(factor);
1743                         }
1744
1745                         mvalo[0]= mval[0];
1746                         mvalo[1]= mval[1];
1747                         
1748                         scrarea_do_windraw(curarea);
1749                         screen_swapbuffers();
1750                 }
1751                 else BIF_wait_for_statechange();
1752         }
1753         window_set_cursor(win, oldcursor);
1754         
1755         if(image_preview_active(curarea, NULL, NULL)) {
1756                 /* recalculates new preview rect */
1757                 scrarea_do_windraw(curarea);
1758                 image_preview_event(2);
1759         }
1760 }
1761
1762 void image_viewzoom(unsigned short event, int invert)
1763 {
1764         SpaceImage *sima= curarea->spacedata.first;
1765
1766         if(event==WHEELDOWNMOUSE || event==PADMINUS)
1767                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 1.25: 0.8);
1768         else if(event==WHEELUPMOUSE || event==PADPLUSKEY)
1769                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 0.8: 1.25);
1770         else if(event==PAD1)
1771                 sima->zoom= 1.0;
1772         else if(event==PAD2)
1773                 sima->zoom= (invert)? 2.0: 0.5;
1774         else if(event==PAD4)
1775                 sima->zoom= (invert)? 4.0: 0.25;
1776         else if(event==PAD8)
1777                 sima->zoom= (invert)? 8.0: 0.125;
1778         
1779         /* ensure pixel exact locations for draw */
1780         sima->xof= (int)sima->xof;
1781         sima->yof= (int)sima->yof;
1782         
1783         if(image_preview_active(curarea, NULL, NULL)) {
1784                 /* recalculates new preview rect */
1785                 scrarea_do_windraw(curarea);
1786                 image_preview_event(2);
1787         }
1788 }
1789
1790 /**
1791  * Updates the fields of the View2D member of the SpaceImage struct.
1792  * Default behavior is to reset the position of the image and set the zoom to 1
1793  * If the image will not fit within the window rectangle, the zoom is adjusted
1794  *
1795  * @return    void
1796  *   
1797  */
1798 void image_home(void)
1799 {
1800         int width, height, imgwidth, imgheight;
1801         float zoomX, zoomY;
1802
1803         if (curarea->spacetype != SPACE_IMAGE) return;
1804
1805         if ((G.sima->image == NULL) || (G.sima->image->ibuf == NULL)) {
1806                 imgwidth = 256;
1807                 imgheight = 256;
1808         }
1809         else {
1810                 imgwidth = G.sima->image->ibuf->x;
1811                 imgheight = G.sima->image->ibuf->y;
1812         }
1813
1814         /* Check if the image will fit in the image with zoom==1 */
1815         width = curarea->winx;
1816         height = curarea->winy;
1817         if (((imgwidth >= width) || (imgheight >= height)) && 
1818                 ((width > 0) && (height > 0))) {
1819                 /* Find the zoom value that will fit the image in the image space */
1820                 zoomX = ((float)width) / ((float)imgwidth);
1821                 zoomY = ((float)height) / ((float)imgheight);
1822                 G.sima->zoom= MIN2(zoomX, zoomY);
1823
1824                 image_zoom_power_of_two();
1825         }
1826         else {
1827                 G.sima->zoom= 1.0f;
1828         }
1829
1830         G.sima->xof= G.sima->yof= 0.0f;
1831         
1832         calc_image_view(G.sima, 'p');
1833         
1834         scrarea_queue_winredraw(curarea);
1835 }
1836
1837 void image_viewcentre(void)
1838 {
1839         float size, min[2], max[2], d[2], xim=256.0f, yim=256.0f;
1840
1841         if( is_uv_tface_editing_allowed()==0 ) return;
1842
1843         if (!minmax_tface_uv(min, max)) return;
1844
1845         if(G.sima->image && G.sima->image->ibuf) {
1846                 xim= G.sima->image->ibuf->x;
1847                 yim= G.sima->image->ibuf->y;
1848         }
1849
1850         G.sima->xof= (int) (((min[0] + max[0])*0.5f - 0.5f)*xim);
1851         G.sima->yof= (int) (((min[1] + max[1])*0.5f - 0.5f)*yim);
1852
1853         d[0] = max[0] - min[0];
1854         d[1] = max[1] - min[1];
1855         size= 0.5*MAX2(d[0], d[1])*MAX2(xim, yim)/256.0f;
1856         
1857         if(size<=0.01) size= 0.01;
1858
1859         G.sima->zoom= 0.7/size;
1860
1861         calc_image_view(G.sima, 'p');
1862
1863         scrarea_queue_winredraw(curarea);
1864 }
1865
1866
1867 /* *********************** render callbacks ***************** */
1868
1869 /* set on initialize render, only one render output to imagewindow can exist, so the global isnt dangerous yet :) */
1870 static ScrArea *image_area= NULL;
1871
1872 /* can get as well the full picture, as the parts while rendering */
1873 static void imagewindow_progress(ScrArea *sa, RenderResult *rr, volatile rcti *renrect)
1874 {
1875         SpaceImage *sima= sa->spacedata.first;
1876         float x1, y1, *rectf= NULL;
1877         unsigned int *rect32= NULL;
1878         int ymin, ymax, xmin, xmax;
1879         
1880         /* if renrect argument, we only display scanlines */
1881         if(renrect) {
1882                 /* if ymax==recty, rendering of layer is ready, we should not draw, other things happen... */
1883                 if(rr->renlay==NULL || renrect->ymax>=rr->recty)
1884                         return;
1885                 
1886                 /* xmin here is first subrect x coord, xmax defines subrect width */
1887                 xmin = renrect->xmin;
1888                 xmax = renrect->xmax - xmin;
1889                 if (xmax<2) return;
1890                 
1891                 ymin= renrect->ymin;
1892                 ymax= renrect->ymax - ymin;
1893                 if(ymax<2)
1894                         return;
1895                 renrect->ymin= renrect->ymax;
1896         }
1897         else {
1898                 xmin = ymin = 0;
1899                 xmax = rr->rectx - 2*rr->crop;
1900                 ymax = rr->recty - 2*rr->crop;
1901         }
1902         
1903         /* image window cruft */
1904         
1905         /* find current float rect for display, first case is after composit... still weak */
1906         if(rr->rectf)
1907                 rectf= rr->rectf;
1908         else {
1909                 if(rr->rect32)
1910                         rect32= rr->rect32;
1911                 else {
1912                         if(rr->renlay==NULL || rr->renlay->rectf==NULL) return;
1913                         rectf= rr->renlay->rectf;
1914                 }
1915         }
1916         if(rectf) {
1917                 /* if scanline updates... */
1918                 rectf+= 4*(rr->rectx*ymin + xmin);
1919                 
1920                 /* when rendering more pixels than needed, we crop away cruft */
1921                 if(rr->crop)
1922                         rectf+= 4*(rr->crop*rr->rectx + rr->crop);
1923         }
1924         
1925         /* tilerect defines drawing offset from (0,0) */
1926         /* however, tilerect (xmin, ymin) is first pixel */
1927         x1 = sima->centx + (rr->tilerect.xmin + rr->crop + xmin)*sima->zoom;
1928         y1 = sima->centy + (rr->tilerect.ymin + rr->crop + ymin)*sima->zoom;
1929         
1930         /* needed for gla draw */
1931         { rcti rct= sa->winrct; rct.ymax-= RW_HEADERY; glaDefine2DArea(&rct);}
1932
1933         glPixelZoom((float)sima->zoom, (float)sima->zoom);
1934         
1935         if(rect32)
1936                 glaDrawPixelsSafe(x1, y1, xmax, ymax, rr->rectx, GL_RGBA, GL_UNSIGNED_BYTE, rect32);
1937         else
1938                 glaDrawPixelsSafe_to32(x1, y1, xmax, ymax, rr->rectx, rectf);
1939         
1940         glPixelZoom(1.0, 1.0);
1941         
1942 }
1943
1944
1945 /* in render window; display a couple of scanlines of rendered image */
1946 static void imagewindow_progress_display_cb(RenderResult *rr, volatile rcti *rect)
1947 {
1948         
1949         if (image_area) {
1950                 imagewindow_progress(image_area, rr, rect);
1951                 image_area->win_swap= WIN_BACK_OK;
1952                 screen_swapbuffers();
1953         }
1954 }
1955
1956 /* unused, init_display_cb is called on each render */
1957 static void imagewindow_clear_display_cb(RenderResult *rr)
1958 {
1959         if (image_area) {
1960         }
1961 }
1962
1963 static ScrArea *biggest_non_image_area(void)
1964 {
1965         ScrArea *sa, *big= NULL;
1966         int size, maxsize= 0;
1967         
1968         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1969                 if(sa->spacetype!=SPACE_IMAGE) {
1970                         size= sa->winx*sa->winy;
1971                         if(sa->winx > 10 && sa->winy > 10 && size > maxsize) {
1972                                 maxsize= size;
1973                                 big= sa;
1974                         }
1975                 }
1976         }
1977         return big;
1978 }
1979
1980 static ScrArea *biggest_area(void)
1981 {
1982         ScrArea *sa, *big= NULL;
1983         int size, maxsize= 0;
1984         
1985         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1986                 size= sa->winx*sa->winy;
1987                 if(size > maxsize) {
1988                         maxsize= size;
1989                         big= sa;
1990                 }
1991         }
1992         return big;
1993 }
1994
1995
1996 /* if R_DISPLAYIMAGE
1997       use Image Window showing Render Result
1998           else: turn largest non-image area into Image Window (not to frustrate texture or composite usage)
1999           else: then we use Image Window anyway...
2000    if R_DISPSCREEN
2001       make a new temp fullscreen area with Image Window
2002 */
2003
2004 static ScrArea *imagewindow_set_render_display(void)
2005 {
2006         ScrArea *sa;
2007         SpaceImage *sima;
2008         
2009         /* find an imagewindow showing render result */
2010         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2011                 if(sa->spacetype==SPACE_IMAGE) {
2012                         sima= sa->spacedata.first;
2013                         
2014                         if(sima->image && BLI_streq(sima->image->id.name+2, "Render Result") )
2015                                 break;
2016                 }
2017         }
2018         if(sa==NULL) {
2019                 /* find largest open non-image area */
2020                 sa= biggest_non_image_area();
2021                 if(sa) {
2022                         newspace(sa, SPACE_IMAGE);
2023                         sima= sa->spacedata.first;
2024                         
2025                         /* makes ESC go back to prev space */
2026                         sima->flag |= SI_PREVSPACE;
2027                 }
2028                 else {
2029                         /* use any area of decent size */
2030                         sa= biggest_area();
2031                         if(sa->spacetype!=SPACE_IMAGE) {
2032                                 newspace(sa, SPACE_IMAGE);
2033                                 sima= sa->spacedata.first;
2034                                 
2035                                 /* makes ESC go back to prev space */
2036                                 sima->flag |= SI_PREVSPACE;
2037                         }
2038                 }
2039         }
2040         
2041         sima= sa->spacedata.first;
2042         
2043         /* get the correct image, and scale it */
2044         sima->image = (Image *)find_id("IM", "Render Result");
2045         
2046         if(sima->image==NULL) {
2047                 Image *ima= alloc_libblock(&G.main->image, ID_IM, "Render Result");
2048                 strcpy(ima->name, "Render Result");
2049                 ima->ok= 1;
2050                 ima->xrep= ima->yrep= 1;
2051                 sima->image= ima;
2052         }
2053         else if(sima->image->id.us==0)  /* well... happens on reload, dunno yet what todo, imagewindow cannot be user when hidden*/
2054                 sima->image->id.us= 1;
2055         
2056         IMB_freeImBuf(sima->image->ibuf);
2057         sima->image->ibuf= NULL;
2058         
2059         if(G.displaymode==R_DISPLAYSCREEN) {
2060                 if(sa->full==0) {
2061                         sima->flag |= SI_FULLWINDOW;
2062                         /* fullscreen works with lousy curarea */
2063                         curarea= sa;
2064                         area_fullscreen();
2065                         sa= curarea;
2066                 }
2067         }
2068         
2069         return sa;
2070 }
2071
2072 static void imagewindow_init_display_cb(RenderResult *rr)
2073 {
2074         
2075         image_area= imagewindow_set_render_display();
2076         
2077         if(image_area) {
2078                 SpaceImage *sima= image_area->spacedata.first;
2079                 
2080                 areawinset(image_area->win);
2081                 
2082                 /* calc location using original size (tiles don't tell) */
2083                 sima->centx= (image_area->winx - sima->zoom*(float)rr->rectx)/2.0f;
2084                 sima->centy= (image_area->winy - sima->zoom*(float)rr->recty)/2.0f;
2085                 
2086                 sima->centx-= sima->zoom*sima->xof;
2087                 sima->centy-= sima->zoom*sima->yof;
2088                 
2089                 drawimagespace(image_area, sima);
2090                 if(image_area->headertype) scrarea_do_headdraw(image_area);
2091                 screen_swapbuffers();
2092                 
2093                 allqueue(REDRAWIMAGE, 0);       /* redraw in end */
2094         }
2095 }
2096
2097 /* coming from BIF_toggle_render_display() */
2098 void imagewindow_toggle_render(void)
2099 {
2100         ScrArea *sa;
2101         
2102         /* check if any imagewindow is showing temporal render output */
2103         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2104                 if(sa->spacetype==SPACE_IMAGE) {
2105                         SpaceImage *sima= sa->spacedata.first;
2106                         
2107                         if(sima->image && BLI_streq(sima->image->id.name+2, "Render Result") )
2108                                 if(sima->flag & (SI_PREVSPACE|SI_FULLWINDOW))
2109                                         break;
2110                 }
2111         }
2112         if(sa) {
2113                 addqueue(sa->win, ESCKEY, 1);   /* also returns from fullscreen */
2114         }
2115         else {
2116                 sa= imagewindow_set_render_display();
2117                 scrarea_queue_headredraw(sa);
2118                 scrarea_queue_winredraw(sa);
2119         }
2120 }
2121
2122 static void imagewindow_renderinfo_cb(RenderStats *rs)
2123 {
2124         
2125         if(image_area) {
2126                 SpaceImage *sima= image_area->spacedata.first;
2127                 
2128                 if(sima->info_str==NULL)
2129                         sima->info_str= MEM_callocN(RW_MAXTEXT, "info str imagewin");
2130                 
2131                 if(rs)
2132                         make_renderinfo_string(rs, sima->info_str);
2133
2134                 imagewindow_draw_renderinfo(image_area);
2135                 
2136                 image_area->win_swap= WIN_BACK_OK;
2137                 screen_swapbuffers();
2138         }
2139 }
2140
2141
2142 void imagewindow_render_callbacks(Render *re)
2143 {
2144         RE_display_init_cb(re, imagewindow_init_display_cb);
2145         RE_display_draw_cb(re, imagewindow_progress_display_cb);
2146         RE_display_clear_cb(re, imagewindow_clear_display_cb);
2147         RE_stats_draw_cb(re, imagewindow_renderinfo_cb);        
2148 }
2149