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