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