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