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