09ba518565fd10674b8ae22ffeb9cb0a611653e6
[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 #include "BLI_editVert.h"
47
48 #include "IMB_imbuf.h"
49 #include "IMB_imbuf_types.h"
50
51 #include "DNA_brush_types.h"
52 #include "DNA_camera_types.h"
53 #include "DNA_color_types.h"
54 #include "DNA_image_types.h"
55 #include "DNA_mesh_types.h"
56 #include "DNA_meshdata_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_packedFile_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_screen_types.h"
62 #include "DNA_space_types.h"
63 #include "DNA_texture_types.h"
64 #include "DNA_userdef_types.h"
65
66 #include "BKE_brush.h"
67 #include "BKE_colortools.h"
68 #include "BKE_utildefines.h"
69 #include "BKE_global.h"
70 #include "BKE_library.h"
71 #include "BKE_main.h"
72 #include "BKE_mesh.h"
73 #include "BKE_node.h"
74 #include "BKE_image.h"
75 #include "BKE_DerivedMesh.h"
76 #include "BKE_displist.h"
77 #include "BKE_object.h"
78
79 #include "BDR_editface.h"
80 #include "BDR_drawobject.h"
81 #include "BDR_drawmesh.h"
82 #include "BDR_imagepaint.h"
83
84 #include "BIF_cursors.h"
85 #include "BIF_gl.h"
86 #include "BIF_graphics.h"
87 #include "BIF_mywindow.h"
88 #include "BIF_drawimage.h"
89 #include "BIF_resources.h"
90 #include "BIF_interface.h"
91 #include "BIF_interface_icons.h"
92 #include "BIF_editsima.h"
93 #include "BIF_glutil.h"
94 #include "BIF_renderwin.h"
95 #include "BIF_space.h"
96 #include "BIF_screen.h"
97 #include "BIF_toolbox.h"
98 #include "BIF_transform.h"
99 #include "BIF_editmesh.h"
100
101 #include "BSE_drawipo.h"
102 #include "BSE_drawview.h"
103 #include "BSE_filesel.h"
104 #include "BSE_headerbuttons.h"
105 #include "BSE_node.h"
106 #include "BSE_trans_types.h"
107 #include "BSE_view.h"
108
109 #include "RE_pipeline.h"
110 #include "BMF_Api.h"
111
112 #include "PIL_time.h"
113
114 /* Modules used */
115 #include "mydevice.h"
116 #include "blendef.h"
117 #include "butspace.h"  // event codes
118 #include "winlay.h"
119
120 #include "interface.h"  /* bad.... but preview code needs UI info. Will solve... (ton) */
121
122 static unsigned char *alloc_alpha_clone_image(int *width, int *height)
123 {
124         Brush *brush = G.scene->toolsettings->imapaint.brush;
125         ImBuf *ibuf;
126         unsigned int size, alpha;
127         unsigned char *rect, *cp;
128
129         if(!brush || !brush->clone.image)
130                 return NULL;
131         
132         ibuf= BKE_image_get_ibuf(brush->clone.image, NULL);
133
134         if(!ibuf || !ibuf->rect)
135                 return NULL;
136
137         rect= MEM_dupallocN(ibuf->rect);
138         if(!rect)
139                 return NULL;
140
141         *width= ibuf->x;
142         *height= ibuf->y;
143
144         size= (*width)*(*height);
145         alpha= (unsigned char)255*brush->clone.alpha;
146         cp= rect;
147
148         while(size-- > 0) {
149                 cp[3]= alpha;
150                 cp += 4;
151         }
152
153         return rect;
154 }
155
156 static int image_preview_active(ScrArea *sa, float *xim, float *yim)
157 {
158         SpaceImage *sima= sa->spacedata.first;
159         
160         /* only when compositor shows, and image handler set */
161         if(sima->image && sima->image->type==IMA_TYPE_COMPOSITE) {
162                 short a;
163         
164                 for(a=0; a<SPACE_MAXHANDLER; a+=2) {
165                         if(sima->blockhandler[a] == IMAGE_HANDLER_PREVIEW) {
166                                 if(xim) *xim= (G.scene->r.size*G.scene->r.xsch)/100;
167                                 if(yim) *yim= (G.scene->r.size*G.scene->r.ysch)/100;
168                                 return 1;
169                         }
170                 }
171         }
172         return 0;
173 }
174
175
176 /**
177  * Sets up the fields of the View2D member of the SpaceImage struct
178  * This routine can be called in two modes:
179  * mode == 'f': float mode (0.0 - 1.0)
180  * mode == 'p': pixel mode (0 - size)
181  *
182  * @param     sima  the image space to update
183  * @param     mode  the mode to use for the update
184  * @return    void
185  *   
186  */
187 void calc_image_view(SpaceImage *sima, char mode)
188 {
189         float xim=256, yim=256;
190         float x1, y1;
191         
192         if(image_preview_active(curarea, &xim, &yim));
193         else if(sima->image) {
194                 ImBuf *ibuf= imagewindow_get_ibuf(sima);
195                 float xuser_asp, yuser_asp;
196                 
197                 image_pixel_aspect(sima->image, &xuser_asp, &yuser_asp);
198                 if(ibuf) {
199                         xim= ibuf->x * xuser_asp;
200                         yim= ibuf->y * yuser_asp;
201                 }
202                 else if( sima->image->type==IMA_TYPE_R_RESULT ) {
203                         /* not very important, just nice */
204                         xim= (G.scene->r.xsch*G.scene->r.size)/100;
205                         yim= (G.scene->r.ysch*G.scene->r.size)/100;
206                 }
207         }
208                 
209         sima->v2d.tot.xmin= 0;
210         sima->v2d.tot.ymin= 0;
211         sima->v2d.tot.xmax= xim;
212         sima->v2d.tot.ymax= yim;
213         
214         sima->v2d.mask.xmin= sima->v2d.mask.ymin= 0;
215         sima->v2d.mask.xmax= curarea->winx;
216         sima->v2d.mask.ymax= curarea->winy;
217
218
219         /* Which part of the image space do we see? */
220         /* Same calculation as in lrectwrite: area left and down*/
221         x1= curarea->winrct.xmin+(curarea->winx-sima->zoom*xim)/2;
222         y1= curarea->winrct.ymin+(curarea->winy-sima->zoom*yim)/2;
223
224         x1-= sima->zoom*sima->xof;
225         y1-= sima->zoom*sima->yof;
226         
227         /* relative display right */
228         sima->v2d.cur.xmin= ((curarea->winrct.xmin - (float)x1)/sima->zoom);
229         sima->v2d.cur.xmax= sima->v2d.cur.xmin + ((float)curarea->winx/sima->zoom);
230         
231         /* relative display left */
232         sima->v2d.cur.ymin= ((curarea->winrct.ymin-(float)y1)/sima->zoom);
233         sima->v2d.cur.ymax= sima->v2d.cur.ymin + ((float)curarea->winy/sima->zoom);
234         
235         if(mode=='f') {         
236                 sima->v2d.cur.xmin/= xim;
237                 sima->v2d.cur.xmax/= xim;
238                 sima->v2d.cur.ymin/= yim;
239                 sima->v2d.cur.ymax/= yim;
240         }
241 }
242
243 /* check for facelesect, and set active image */
244 void what_image(SpaceImage *sima)
245 {
246         if(             (sima->mode!=SI_TEXTURE) ||
247                         (sima->image && sima->image->source==IMA_SRC_VIEWER) ||
248                         (G.obedit != OBACT) ||
249                         (G.editMesh==NULL) ||
250                         (sima->pin)
251         ) {
252                 return;
253         }
254         
255         /* viewer overrides uv editmode */
256         if (EM_texFaceCheck()) {
257                 MTFace *activetf;
258                 
259                 sima->image= NULL;
260                 
261                 activetf = get_active_mtface(NULL, NULL, 1); /* partially selected face is ok */
262                 
263                 if(activetf && activetf->mode & TF_TEX) {
264                         /* done need to check for pin here, see above */
265                         /*if (!sima->pin)*/
266                         sima->image= activetf->tpage;
267                         
268                         if(sima->flag & SI_EDITTILE);
269                         else sima->curtile= activetf->tile;
270                         
271                         if(sima->image) {
272                                 if(activetf->mode & TF_TILES)
273                                         sima->image->tpageflag |= IMA_TILES;
274                                 else sima->image->tpageflag &= ~IMA_TILES;
275                         }
276                 }
277         }
278 }
279
280 /* after a what_image(), this call will give ibufs, includes the spare image */
281 ImBuf *imagewindow_get_ibuf(SpaceImage *sima)
282 {
283         if(G.sima->image) {
284                 /* check for spare */
285                 if(sima->image->type==IMA_TYPE_R_RESULT && BIF_show_render_spare())
286                         return BIF_render_spare_imbuf();
287                 else
288                         return BKE_image_get_ibuf(sima->image, &sima->iuser);
289         }
290         return NULL;
291 }
292
293 /*
294  * dotile -     1, set the tile flag (from the space image)
295  *                      2, set the tile index for the faces. 
296  * */
297 void image_set_tile(SpaceImage *sima, int dotile)
298 {
299         MTFace *tface;
300         EditMesh *em = G.editMesh;
301         EditFace *efa;
302         
303         if(!sima->image || sima->mode!=SI_TEXTURE || !EM_texFaceCheck())
304                 return;
305         
306         /* skip assigning these procedural images... */
307         if(sima->image && (sima->image->type==IMA_TYPE_R_RESULT || sima->image->type==IMA_TYPE_COMPOSITE))
308                 return;
309         
310         for (efa= em->faces.first; efa; efa= efa->next) {
311                 tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
312                 if (efa->h==0 && efa->f & SELECT) {
313                         if (dotile==1) {
314                                 /* set tile flag */
315                                 if (sima->image->tpageflag & IMA_TILES) {
316                                         tface->mode |= TF_TILES;
317                                 } else {
318                                         tface->mode &= ~TF_TILES;
319                                 }
320                         } else if (dotile==2) {
321                                 /* set tile index */
322                                 tface->tile= sima->curtile;
323                         }
324                 }
325         }
326         object_uvs_changed(OBACT);
327         allqueue(REDRAWBUTSEDIT, 0);
328 }
329
330
331
332 void uvco_to_areaco(float *vec, short *mval)
333 {
334         float x, y;
335
336         mval[0]= IS_CLIPPED;
337         
338         x= (vec[0] - G.v2d->cur.xmin)/(G.v2d->cur.xmax-G.v2d->cur.xmin);
339         y= (vec[1] - G.v2d->cur.ymin)/(G.v2d->cur.ymax-G.v2d->cur.ymin);
340
341         if(x>=0.0 && x<=1.0) {
342                 if(y>=0.0 && y<=1.0) {          
343                         mval[0]= G.v2d->mask.xmin + x*(G.v2d->mask.xmax-G.v2d->mask.xmin);
344                         mval[1]= G.v2d->mask.ymin + y*(G.v2d->mask.ymax-G.v2d->mask.ymin);
345                 }
346         }
347 }
348
349 void uvco_to_areaco_noclip(float *vec, int *mval)
350 {
351         float x, y;
352
353         mval[0]= IS_CLIPPED;
354         
355         x= (vec[0] - G.v2d->cur.xmin)/(G.v2d->cur.xmax-G.v2d->cur.xmin);
356         y= (vec[1] - G.v2d->cur.ymin)/(G.v2d->cur.ymax-G.v2d->cur.ymin);
357
358         x= G.v2d->mask.xmin + x*(G.v2d->mask.xmax-G.v2d->mask.xmin);
359         y= G.v2d->mask.ymin + y*(G.v2d->mask.ymax-G.v2d->mask.ymin);
360         
361         mval[0]= x;
362         mval[1]= y;
363 }
364
365 static void drawcursor_sima(float xuser_asp, float yuser_asp)
366 {
367         int wi, hi;
368         float w, h;
369         
370         if (!G.obedit || !CustomData_has_layer(&G.editMesh->fdata, CD_MTFACE)) return;
371         
372         transform_width_height_tface_uv(&wi, &hi);
373         w = (((float)wi)/256.0f)*G.sima->zoom * xuser_asp;
374         h = (((float)hi)/256.0f)*G.sima->zoom * yuser_asp;
375         
376         cpack(0xFFFFFF);
377         glTranslatef(G.v2d->cursor[0], G.v2d->cursor[1], 0.0f);  
378         fdrawline(-0.05/w, 0, 0, 0.05/h);
379         fdrawline(0, 0.05/h, 0.05/w, 0);
380         fdrawline(0.05/w, 0, 0, -0.05/h);
381         fdrawline(0, -0.05/h, -0.05/w, 0);
382         
383         setlinestyle(4);
384         cpack(0xFF);
385         fdrawline(-0.05/w, 0, 0, 0.05/h);
386         fdrawline(0, 0.05/h, 0.05/w, 0);
387         fdrawline(0.05/w, 0, 0, -0.05/h);
388         fdrawline(0, -0.05/h, -0.05/w, 0);
389         
390         
391         setlinestyle(0);
392         cpack(0x0);
393         fdrawline(-0.020/w, 0, -0.1/w, 0);
394         fdrawline(0.1/w, 0, .020/w, 0);
395         fdrawline(0, -0.020/h, 0, -0.1/h);
396         fdrawline(0, 0.1/h, 0, 0.020/h);
397         
398         setlinestyle(1);
399         cpack(0xFFFFFF);
400         fdrawline(-0.020/w, 0, -0.1/w, 0);
401         fdrawline(0.1/w, 0, .020/w, 0);
402         fdrawline(0, -0.020/h, 0, -0.1/h);
403         fdrawline(0, 0.1/h, 0, 0.020/h);
404         
405         glTranslatef(-G.v2d->cursor[0], -G.v2d->cursor[1], 0.0f);
406         setlinestyle(0);
407 }
408
409 // checks if we are selecting only faces
410 int draw_uvs_face_check(void)
411 {
412         if (G.sima==NULL) {
413                 return 0;
414         }
415         if (G.sima->flag & SI_SYNC_UVSEL) {
416                 if (G.scene->selectmode == SCE_SELECT_FACE) {
417                         return 2;
418                 } else if (G.scene->selectmode & SCE_SELECT_FACE) {
419                         return 1;
420                 } 
421         } else {
422                 if (G.sima->flag & SI_SELACTFACE) {
423                         return 1;
424                 }
425         }
426         return 0;
427 }
428
429 void uv_center(float uv[][2], float cent[2], void * isquad)
430 {
431
432         if (isquad) {
433                 cent[0] = (uv[0][0] + uv[1][0] + uv[2][0] + uv[3][0]) / 4.0;
434                 cent[1] = (uv[0][1] + uv[1][1] + uv[2][1] + uv[3][1]) / 4.0;            
435         } else {
436                 cent[0] = (uv[0][0] + uv[1][0] + uv[2][0]) / 3.0;
437                 cent[1] = (uv[0][1] + uv[1][1] + uv[2][1]) / 3.0;               
438         }
439 }
440
441 static float uv_area(float uv[][2], int quad)
442 {
443         if (quad) {
444                 return AreaF2Dfl(uv[0], uv[1], uv[2]) + AreaF2Dfl(uv[0], uv[2], uv[3]); 
445         } else { 
446                 return AreaF2Dfl(uv[0], uv[1], uv[2]); 
447         }
448 }
449
450 void uv_copy_aspect(float uv_orig[][2], float uv[][2], float aspx, float aspy)
451 {
452         uv[0][0] = uv_orig[0][0]*aspx;
453         uv[0][1] = uv_orig[0][1]*aspy;
454         
455         uv[1][0] = uv_orig[1][0]*aspx;
456         uv[1][1] = uv_orig[1][1]*aspy;
457         
458         uv[2][0] = uv_orig[2][0]*aspx;
459         uv[2][1] = uv_orig[2][1]*aspy;
460         
461         uv[3][0] = uv_orig[3][0]*aspx;
462         uv[3][1] = uv_orig[3][1]*aspy;
463 }
464
465 /* draws uv's in the image space */
466 void draw_uvs_sima(void)
467 {
468         MTFace *tface,*activetface = NULL;
469         EditMesh *em = G.editMesh;
470         EditFace *efa, *efa_act;
471         
472         char col1[4], col2[4];
473         float pointsize;
474         int drawface;
475         int lastsel, sel;
476         
477         if (!G.obedit || !CustomData_has_layer(&em->fdata, CD_MTFACE))
478                 return;
479         
480         drawface = draw_uvs_face_check();
481         
482         calc_image_view(G.sima, 'f');   /* float */
483         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
484         glLoadIdentity();
485         
486         
487         if(G.sima->flag & SI_DRAWTOOL) {
488                 /* draws the grey mesh when painting */
489                 glColor3ub(112, 112, 112);
490                 for (efa= em->faces.first; efa; efa= efa->next) {
491                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
492                         glBegin(GL_LINE_LOOP);
493                         glVertex2fv(tface->uv[0]);
494                         glVertex2fv(tface->uv[1]);
495                         glVertex2fv(tface->uv[2]);
496                         if(efa->v4) glVertex2fv(tface->uv[3]);
497                         glEnd();
498                 }
499                 return; /* only draw shadow mesh */
500         } else if (G.sima->flag & SI_DRAWSHADOW) {
501                 /* draw shadow mesh - this is the mesh with the modifier applied */
502                 glColor3ub(112, 112, 112);
503                 if (    em->derivedFinal &&
504                                 em->derivedFinal->drawUVEdges &&
505                                 CustomData_has_layer(&em->derivedFinal->faceData, CD_MTFACE)
506                 ) {
507                         /* we can use the existing final mesh */
508                         glColor3ub(112, 112, 112);
509                         em->derivedFinal->drawUVEdges(em->derivedFinal);
510                 } else {
511                         DerivedMesh *finalDM, *cageDM;
512                         
513                         /* draw final mesh with modifiers applied */
514                         cageDM = editmesh_get_derived_cage_and_final(&finalDM, CD_MASK_BAREMESH | CD_MASK_MTFACE);
515                         
516                         if              (finalDM->drawUVEdges &&
517                                         DM_get_face_data_layer(finalDM, CD_MTFACE) &&
518                                         /* When sync selection is enabled, all faces are drawn (except for hidden)
519                                          * so if cage is the same as the final, theres no point in drawing the shadowmesh. */
520                                         !((G.sima->flag & SI_SYNC_UVSEL && cageDM==finalDM))
521                         ) {
522                                 glColor3ub(112, 112, 112);
523                                 finalDM->drawUVEdges(finalDM);
524                         }
525                         
526                         if (cageDM != finalDM)
527                                 cageDM->release(cageDM);
528                         finalDM->release(finalDM);
529                 }
530         }
531         
532         activetface = get_active_mtface(&efa_act, NULL, 0); /* will be set to NULL if hidden */
533                 
534         
535         if (G.sima->flag & SI_DRAW_STRETCH) {
536                 float col[4];
537                 float aspx, aspy;
538                 float tface_uv[4][2];
539                 
540                 transform_aspect_ratio_tface_uv(&aspx, &aspy);
541                 
542                 switch (G.sima->dt_uvstretch) {
543                         case SI_UVDT_STRETCH_AREA:
544                         {
545                                 float totarea=0.0f, totuvarea=0.0f, areadiff, uvarea, area;
546                                 
547                                 for (efa= em->faces.first; efa; efa= efa->next) {
548                                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
549                                         uv_copy_aspect(tface->uv, tface_uv, aspx, aspy);
550
551                                         totarea += EM_face_area(efa);
552                                         //totuvarea += tface_area(tface, efa->v4!=0);
553                                         totuvarea += uv_area(tface_uv, efa->v4!=0);
554                                         
555                                         if (simaFaceDraw_Check(efa, tface)) {
556                                                 efa->tmp.p = tface;
557                                         } else {
558                                                 if (tface == activetface)
559                                                         activetface= NULL;
560                                                 efa->tmp.p = NULL;
561                                         }
562                                 }
563                                 
564                                 if (totarea < FLT_EPSILON || totuvarea < FLT_EPSILON) {
565                                         col[0] = 1.0;
566                                         col[1] = col[2] = 0.0;
567                                         glColor3fv(col);
568                                         for (efa= em->faces.first; efa; efa= efa->next) {
569                                                 if ((tface=(MTFace *)efa->tmp.p)) {
570                                                         glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
571                                                                 glVertex2fv(tface->uv[0]);
572                                                                 glVertex2fv(tface->uv[1]);
573                                                                 glVertex2fv(tface->uv[2]);
574                                                                 if(efa->v4) glVertex2fv(tface->uv[3]);
575                                                         glEnd();
576                                                 }
577                                         }
578                                 } else {
579                                         for (efa= em->faces.first; efa; efa= efa->next) {
580                                                 if ((tface=(MTFace *)efa->tmp.p)) {
581                                                         area = EM_face_area(efa) / totarea;
582                                                         uv_copy_aspect(tface->uv, tface_uv, aspx, aspy);
583                                                         //uvarea = tface_area(tface, efa->v4!=0) / totuvarea;
584                                                         uvarea = uv_area(tface_uv, efa->v4!=0) / totuvarea;
585                                                         
586                                                         if (area < FLT_EPSILON || uvarea < FLT_EPSILON) {
587                                                                 areadiff = 1.0;
588                                                         } else if (area>uvarea) {
589                                                                 areadiff = 1.0-(uvarea/area);
590                                                         } else {
591                                                                 areadiff = 1.0-(area/uvarea);
592                                                         }
593                                                         
594                                                         weight_to_rgb(areadiff, col, col+1, col+2);
595                                                         glColor3fv(col);
596                                                         
597                                                         glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
598                                                                 glVertex2fv(tface->uv[0]);
599                                                                 glVertex2fv(tface->uv[1]);
600                                                                 glVertex2fv(tface->uv[2]);
601                                                                 if(efa->v4) glVertex2fv(tface->uv[3]);
602                                                         glEnd();
603                                                 }
604                                         }
605                                 }
606                                 break;
607                         }
608                         case SI_UVDT_STRETCH_ANGLE:
609                         {
610                                 float uvang1,uvang2,uvang3,uvang4;
611                                 float ang1,ang2,ang3,ang4;
612                                 float av1[3], av2[3], av3[3], av4[3]; /* use for 2d and 3d  angle vectors */
613                                 float a;
614                                 
615                                 col[3] = 0.5; /* hard coded alpha, not that nice */
616                                 
617                                 glShadeModel(GL_SMOOTH);
618                                 
619                                 for (efa= em->faces.first; efa; efa= efa->next) {
620                                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
621                                         
622                                         if (simaFaceDraw_Check(efa, tface)) {
623                                                 efa->tmp.p = tface;
624                                                 uv_copy_aspect(tface->uv, tface_uv, aspx, aspy);
625                                                 if (efa->v4) {
626                                                         
627 #if 0                                           /* Simple but slow, better reuse normalized vectors */
628                                                         uvang1 = VecAngle3_2D(tface_uv[3], tface_uv[0], tface_uv[1]);
629                                                         ang1 = VecAngle3(efa->v4->co, efa->v1->co, efa->v2->co);
630                                                         
631                                                         uvang2 = VecAngle3_2D(tface_uv[0], tface_uv[1], tface_uv[2]);
632                                                         ang2 = VecAngle3(efa->v1->co, efa->v2->co, efa->v3->co);
633                                                         
634                                                         uvang3 = VecAngle3_2D(tface_uv[1], tface_uv[2], tface_uv[3]);
635                                                         ang3 = VecAngle3(efa->v2->co, efa->v3->co, efa->v4->co);
636                                                         
637                                                         uvang4 = VecAngle3_2D(tface_uv[2], tface_uv[3], tface_uv[0]);
638                                                         ang4 = VecAngle3(efa->v3->co, efa->v4->co, efa->v1->co);
639 #endif
640                                                         
641                                                         /* uv angles */
642                                                         VECSUB2D(av1, tface_uv[3], tface_uv[0]); Normalize2(av1);
643                                                         VECSUB2D(av2, tface_uv[0], tface_uv[1]); Normalize2(av2);
644                                                         VECSUB2D(av3, tface_uv[1], tface_uv[2]); Normalize2(av3);
645                                                         VECSUB2D(av4, tface_uv[2], tface_uv[3]); Normalize2(av4);
646                                                         
647                                                         /* This is the correct angle however we are only comparing angles
648                                                          * uvang1 = 90-((NormalizedVecAngle2_2D(av1, av2) * 180.0/M_PI)-90);*/
649                                                         uvang1 = NormalizedVecAngle2_2D(av1, av2)*180.0/M_PI;
650                                                         uvang2 = NormalizedVecAngle2_2D(av2, av3)*180.0/M_PI;
651                                                         uvang3 = NormalizedVecAngle2_2D(av3, av4)*180.0/M_PI;
652                                                         uvang4 = NormalizedVecAngle2_2D(av4, av1)*180.0/M_PI;
653                                                         
654                                                         /* 3d angles */
655                                                         VECSUB(av1, efa->v4->co, efa->v1->co); Normalize(av1);
656                                                         VECSUB(av2, efa->v1->co, efa->v2->co); Normalize(av2);
657                                                         VECSUB(av3, efa->v2->co, efa->v3->co); Normalize(av3);
658                                                         VECSUB(av4, efa->v3->co, efa->v4->co); Normalize(av4);
659                                                         
660                                                         /* This is the correct angle however we are only comparing angles
661                                                          * ang1 = 90-((NormalizedVecAngle2(av1, av2) * 180.0/M_PI)-90);*/
662                                                         ang1 = NormalizedVecAngle2(av1, av2)*180.0/M_PI;
663                                                         ang2 = NormalizedVecAngle2(av2, av3)*180.0/M_PI;
664                                                         ang3 = NormalizedVecAngle2(av3, av4)*180.0/M_PI;
665                                                         ang4 = NormalizedVecAngle2(av4, av1)*180.0/M_PI;
666                                                         
667                                                         glBegin(GL_QUADS);
668                                                         
669                                                         /* This simple makes the angles display worse then they really are ;)
670                                                          * 1.0-pow((1.0-a), 2) */
671                                                         
672                                                         a = fabs(uvang1-ang1)/180.0;
673                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
674                                                         glColor3fv(col);
675                                                         glVertex2fv(tface->uv[0]);
676                                                         a = fabs(uvang2-ang2)/180.0;
677                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
678                                                         glColor3fv(col);
679                                                         glVertex2fv(tface->uv[1]);
680                                                         a = fabs(uvang3-ang3)/180.0;
681                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
682                                                         glColor3fv(col);
683                                                         glVertex2fv(tface->uv[2]);
684                                                         a = fabs(uvang4-ang4)/180.0;
685                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
686                                                         glColor3fv(col);
687                                                         glVertex2fv(tface->uv[3]);
688                                                         
689                                                 } else {
690 #if 0                                           /* Simple but slow, better reuse normalized vectors */
691                                                         uvang1 = VecAngle3_2D(tface_uv[2], tface_uv[0], tface_uv[1]);
692                                                         ang1 = VecAngle3(efa->v3->co, efa->v1->co, efa->v2->co);
693                                                         
694                                                         uvang2 = VecAngle3_2D(tface_uv[0], tface_uv[1], tface_uv[2]);
695                                                         ang2 = VecAngle3(efa->v1->co, efa->v2->co, efa->v3->co);
696                                                         
697                                                         uvang3 = 180-(uvang1+uvang2);
698                                                         ang3 = 180-(ang1+ang2);
699 #endif                                          
700                                                         
701                                                         /* uv angles */
702                                                         VECSUB2D(av1, tface_uv[2], tface_uv[0]); Normalize2(av1);
703                                                         VECSUB2D(av2, tface_uv[0], tface_uv[1]); Normalize2(av2);
704                                                         VECSUB2D(av3, tface_uv[1], tface_uv[2]); Normalize2(av3);
705                                                         
706                                                         /* This is the correct angle however we are only comparing angles
707                                                          * uvang1 = 90-((NormalizedVecAngle2_2D(av1, av2) * 180.0/M_PI)-90); */
708                                                         uvang1 = NormalizedVecAngle2_2D(av1, av2)*180.0/M_PI;
709                                                         uvang2 = NormalizedVecAngle2_2D(av2, av3)*180.0/M_PI;
710                                                         uvang3 = NormalizedVecAngle2_2D(av3, av1)*180.0/M_PI;
711                                                         
712                                                         /* 3d angles */
713                                                         VECSUB(av1, efa->v3->co, efa->v1->co); Normalize(av1);
714                                                         VECSUB(av2, efa->v1->co, efa->v2->co); Normalize(av2);
715                                                         VECSUB(av3, efa->v2->co, efa->v3->co); Normalize(av3);
716                                                         /* This is the correct angle however we are only comparing angles
717                                                          * ang1 = 90-((NormalizedVecAngle2(av1, av2) * 180.0/M_PI)-90); */
718                                                         ang1 = NormalizedVecAngle2(av1, av2)*180.0/M_PI;
719                                                         ang2 = NormalizedVecAngle2(av2, av3)*180.0/M_PI;
720                                                         ang3 = NormalizedVecAngle2(av3, av1)*180.0/M_PI;
721                                                         
722                                                         /* This simple makes the angles display worse then they really are ;)
723                                                          * 1.0-pow((1.0-a), 2) */
724                                                         
725                                                         glBegin(GL_TRIANGLES);
726                                                         a = fabs(uvang1-ang1)/180.0;
727                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
728                                                         glColor3fv(col);
729                                                         glVertex2fv(tface->uv[0]);
730                                                         a = fabs(uvang2-ang2)/180.0;
731                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
732                                                         glColor3fv(col);
733                                                         glVertex2fv(tface->uv[1]);
734                                                         a = fabs(uvang3-ang3)/180.0;
735                                                         weight_to_rgb(1.0-pow((1.0-a), 2), col, col+1, col+2);
736                                                         glColor3fv(col);
737                                                         glVertex2fv(tface->uv[2]);
738                                                 }
739                                                 glEnd();
740                                         } else {
741                                                 if (tface == activetface)
742                                                         activetface= NULL;
743                                                 efa->tmp.p = NULL;
744                                         }
745                                 }
746                                 glShadeModel(GL_FLAT);
747                                 break;
748                         }
749                 }
750         } else if(G.f & G_DRAWFACES) {
751                 /* draw transparent faces */
752                 BIF_GetThemeColor4ubv(TH_FACE, col1);
753                 BIF_GetThemeColor4ubv(TH_FACE_SELECT, col2);
754                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
755                 glEnable(GL_BLEND);
756                 
757                 for (efa= em->faces.first; efa; efa= efa->next) {
758                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
759                         
760                         if (simaFaceDraw_Check(efa, tface)) {
761                                 efa->tmp.p = tface;
762                                 if (tface==activetface) continue; /* important the temp pointer is set above */
763                                 if( simaFaceSel_Check(efa, tface)) {
764                                         glColor4ubv((GLubyte *)col2);
765                                 } else {
766                                         glColor4ubv((GLubyte *)col1);
767                                 }
768                                         
769                                 glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
770                                         glVertex2fv(tface->uv[0]);
771                                         glVertex2fv(tface->uv[1]);
772                                         glVertex2fv(tface->uv[2]);
773                                         if(efa->v4) glVertex2fv(tface->uv[3]);
774                                 glEnd();
775                                 
776                         } else {
777                                 if (tface == activetface)
778                                         activetface= NULL;
779                                 efa->tmp.p = NULL;
780                         }
781                 }
782                 glDisable(GL_BLEND);
783         } else {
784                 /* would be nice to do this within a draw loop but most below are optional, so it would involve too many checks */
785                 for (efa= em->faces.first; efa; efa= efa->next) {
786                         tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
787                         if (simaFaceDraw_Check(efa, tface)) {           
788                                 efa->tmp.p = tface;
789                         } else {
790                                 if (tface == activetface)
791                                         activetface= NULL;
792                                 efa->tmp.p = NULL;
793                         }
794                 }
795                 
796         }
797         
798         if (activetface) {
799                 glEnable(GL_BLEND);
800                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
801                 BIF_ThemeColor4(TH_EDITMESH_ACTIVE);
802                 glEnable(GL_POLYGON_STIPPLE);
803                 glPolygonStipple(stipple_quarttone);
804                 glBegin(efa_act->v4?GL_QUADS:GL_TRIANGLES);
805                         glVertex2fv(activetface->uv[0]);
806                         glVertex2fv(activetface->uv[1]);
807                         glVertex2fv(activetface->uv[2]);
808                         if(efa_act->v4) glVertex2fv(activetface->uv[3]);
809                 glEnd();
810                 glDisable(GL_POLYGON_STIPPLE);
811                 glDisable(GL_BLEND);
812         }
813         
814         if (G.sima->flag & SI_SMOOTH_UV) {
815                 glEnable( GL_LINE_SMOOTH );
816                 glEnable(GL_BLEND);
817                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
818         }
819         
820         switch (G.sima->dt_uv) {
821         case SI_UVDT_DASH:
822                 for (efa= em->faces.first; efa; efa= efa->next) {
823 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
824 //                      if (simaFaceDraw_Check(efa, tface)) {
825                         
826                         /*this is a shortcut to do the same as above but a faster for drawing */
827                         if ((tface=(MTFace *)efa->tmp.p)) {
828                         
829                                 cpack(0x111111);
830                                 glBegin(GL_LINE_LOOP);
831                                         glVertex2fv(tface->uv[0]);
832                                         glVertex2fv(tface->uv[1]);
833                                         glVertex2fv(tface->uv[2]);
834                                         if(efa->v4) glVertex2fv(tface->uv[3]);
835                                 glEnd();
836                         
837                                 setlinestyle(2);
838                                 cpack(0x909090);
839                                 glBegin(GL_LINE_STRIP);
840                                         glVertex2fv(tface->uv[0]);
841                                         glVertex2fv(tface->uv[1]);
842                                 glEnd();
843         
844                                 glBegin(GL_LINE_STRIP);
845                                         glVertex2fv(tface->uv[0]);
846                                         if(efa->v4) glVertex2fv(tface->uv[3]);
847                                         else glVertex2fv(tface->uv[2]);
848                                 glEnd();
849         
850                                 glBegin(GL_LINE_STRIP);
851                                         glVertex2fv(tface->uv[1]);
852                                         glVertex2fv(tface->uv[2]);
853                                         if(efa->v4) glVertex2fv(tface->uv[3]);
854                                 glEnd();
855                                 setlinestyle(0);
856                         }
857                 }
858                 break;
859         case SI_UVDT_BLACK: /* black/white */
860         case SI_UVDT_WHITE: 
861                 cpack((G.sima->dt_uv==SI_UVDT_WHITE) ? 0xFFFFFF : 0x0);
862                 for (efa= em->faces.first; efa; efa= efa->next) {
863 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
864 //                      if (simaFaceDraw_Check(efa, tface)) {
865                         
866                         /*this is a shortcut to do the same as above but a faster for drawing */
867                         if ((tface=(MTFace *)efa->tmp.p)) {
868                         
869                                 glBegin(GL_LINE_LOOP);
870                                         glVertex2fv(tface->uv[0]);
871                                         glVertex2fv(tface->uv[1]);
872                                         glVertex2fv(tface->uv[2]);
873                                         if(efa->v4) glVertex2fv(tface->uv[3]);
874                                 glEnd();
875                         }
876                 }
877                 break;
878         case SI_UVDT_OUTLINE:
879                 glLineWidth(3);
880                 cpack(0x0);
881                 
882                 for (efa= em->faces.first; efa; efa= efa->next) {
883 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
884 //                      if (simaFaceDraw_Check(efa, tface)) {
885                         
886                         /*this is a shortcut to do the same as above but a faster for drawing */
887                         if ((tface=(MTFace *)efa->tmp.p)) {
888                                 
889                                 glBegin(GL_LINE_LOOP);
890                                         glVertex2fv(tface->uv[0]);
891                                         glVertex2fv(tface->uv[1]);
892                                         glVertex2fv(tface->uv[2]);
893                                         if(efa->v4) glVertex2fv(tface->uv[3]);
894                                 glEnd();
895                         }
896                 }
897                 
898                 glLineWidth(1);
899                 col2[0] = col2[1] = col2[2] = 128; col2[3] = 255;
900                 glColor4ubv((unsigned char *)col2); 
901                 
902                 if (G.f & G_DRAWEDGES) {
903                         glShadeModel(GL_SMOOTH);
904                         BIF_GetThemeColor4ubv(TH_VERTEX_SELECT, col1);
905                         lastsel = sel = 0;
906
907                         for (efa= em->faces.first; efa; efa= efa->next) {
908         //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
909         //                      if (simaFaceDraw_Check(efa, tface)) {
910                                 
911                                 /*this is a shortcut to do the same as above but a faster for drawing */
912                                 if ((tface=(MTFace *)efa->tmp.p)) {
913                                         
914                                         glBegin(GL_LINE_LOOP);
915                                         sel = (simaUVSel_Check(efa, tface, 0) ? 1 : 0);
916                                         if (sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
917                                         glVertex2fv(tface->uv[0]);
918                                         
919                                         sel = simaUVSel_Check(efa, tface, 1) ? 1 : 0;
920                                         if (sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
921                                         glVertex2fv(tface->uv[1]);
922                                         
923                                         sel = simaUVSel_Check(efa, tface, 2) ? 1 : 0;
924                                         if (sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
925                                         glVertex2fv(tface->uv[2]);
926                                         
927                                         if(efa->v4) {
928                                                 sel = simaUVSel_Check(efa, tface, 3) ? 1 : 0;
929                                                 if (sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
930                                                 glVertex2fv(tface->uv[3]);
931                                         }
932                                         
933                                         glEnd();
934                                 }
935                         }
936                         glShadeModel(GL_FLAT);
937                 } else { /* No nice edges */
938                         
939                         for (efa= em->faces.first; efa; efa= efa->next) {
940         //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
941         //                      if (simaFaceDraw_Check(efa, tface)) {
942                                 
943                                 /*this is a shortcut to do the same as above but a faster for drawing */
944                                 if ((tface=(MTFace *)efa->tmp.p)) {
945                                         
946                                         glBegin(GL_LINE_LOOP);
947                                         glVertex2fv(tface->uv[0]);
948                                         glVertex2fv(tface->uv[1]);
949                                         glVertex2fv(tface->uv[2]);
950                                         if(efa->v4)
951                                                 glVertex2fv(tface->uv[3]);
952                                         glEnd();
953                                 }
954                         }
955                 }
956                 
957                 break;
958         }
959
960         if (G.sima->flag & SI_SMOOTH_UV) {
961                 glDisable( GL_LINE_SMOOTH);
962                 glDisable(GL_BLEND);
963         }
964
965         if (drawface) {
966                 // draw UV face points
967                 float cent[2];
968                 
969                 
970             /* unselected faces's */
971                 pointsize = BIF_GetThemeValuef(TH_FACEDOT_SIZE);
972                 // TODO - drawobject.c changes this value after - Investiagate!
973                 glPointSize(pointsize);
974                 
975                 BIF_ThemeColor(TH_WIRE);
976                 bglBegin(GL_POINTS);
977                 for (efa= em->faces.first; efa; efa= efa->next) {
978                         
979 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
980 //                      if (simaFaceDraw_Check(efa, tface)) {
981                         
982                         /*this is a shortcut to do the same as above but a faster for drawing */
983                         if ((tface=(MTFace *)efa->tmp.p)) {
984                                 if( ! simaFaceSel_Check(efa, tface) ) {
985                                         uv_center(tface->uv, cent, (void *)efa->v4);
986                                         bglVertex2fv(cent);
987                                 }
988                         }
989                 }
990                 bglEnd();
991                 /* selected faces's */
992                 BIF_ThemeColor(TH_FACE_DOT);
993                 bglBegin(GL_POINTS);
994                 for (efa= em->faces.first; efa; efa= efa->next) {
995                         
996 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
997 //                      if (simaFaceDraw_Check(efa, tface)) {
998                         
999                         /*this is a shortcut to do the same as above but a faster for drawing */
1000                         if ((tface=(MTFace *)efa->tmp.p)) {
1001                                 if( simaFaceSel_Check(efa, tface) ) {
1002                                         uv_center(tface->uv, cent, (void *)efa->v4);
1003                                         bglVertex2fv(cent);
1004                                 }
1005                         }
1006                 }
1007                 bglEnd();
1008         }
1009         
1010         if (drawface != 2) { /* 2 means Mesh Face Mode */
1011             /* unselected uv's */
1012                 BIF_ThemeColor(TH_VERTEX);
1013                 pointsize = BIF_GetThemeValuef(TH_VERTEX_SIZE);
1014                 glPointSize(pointsize);
1015         
1016                 bglBegin(GL_POINTS);
1017                 for (efa= em->faces.first; efa; efa= efa->next) {
1018                         
1019 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1020 //                      if (simaFaceDraw_Check(efa, tface)) {
1021                         
1022                         /*this is a shortcut to do the same as above but a faster for drawing */
1023                         if ((tface=(MTFace *)efa->tmp.p)) {
1024                         
1025                                 if(simaUVSel_Check(efa, tface, 0)); else bglVertex2fv(tface->uv[0]);
1026                                 if(simaUVSel_Check(efa, tface, 1)); else bglVertex2fv(tface->uv[1]);
1027                                 if(simaUVSel_Check(efa, tface, 2)); else bglVertex2fv(tface->uv[2]);
1028                                 if(efa->v4) {
1029                                         if(simaUVSel_Check(efa, tface, 3)); else bglVertex2fv(tface->uv[3]);
1030                                 }
1031                         }
1032                 }
1033                 bglEnd();
1034         
1035                 /* pinned uv's */
1036                 /* give odd pointsizes odd pin pointsizes */
1037             glPointSize(pointsize*2 + (((int)pointsize % 2)? (-1): 0));
1038                 cpack(0xFF);
1039         
1040                 bglBegin(GL_POINTS);
1041                 for (efa= em->faces.first; efa; efa= efa->next) {
1042 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1043 //                      if (simaFaceDraw_Check(efa, tface)) {
1044                         
1045                         /*this is a shortcut to do the same as above but a faster for drawing */
1046                         if ((tface=(MTFace *)efa->tmp.p)) {
1047                                 
1048                                 if(tface->unwrap & TF_PIN1) bglVertex2fv(tface->uv[0]);
1049                                 if(tface->unwrap & TF_PIN2) bglVertex2fv(tface->uv[1]);
1050                                 if(tface->unwrap & TF_PIN3) bglVertex2fv(tface->uv[2]);
1051                                 if(efa->v4) {
1052                                         if(tface->unwrap & TF_PIN4) bglVertex2fv(tface->uv[3]);
1053                                 }
1054                         }
1055                 }
1056                 bglEnd();
1057         
1058                 /* selected uv's */
1059                 BIF_ThemeColor(TH_VERTEX_SELECT);
1060             glPointSize(pointsize);
1061         
1062                 bglBegin(GL_POINTS);
1063                 for (efa= em->faces.first; efa; efa= efa->next) {
1064 //                      tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1065 //                      if (simaFaceDraw_Check(efa, tface)) {
1066                         
1067                         /*this is a shortcut to do the same as above but a faster for drawing */
1068                         if ((tface=(MTFace *)efa->tmp.p)) {
1069                         
1070                                 if(!simaUVSel_Check(efa, tface, 0)); else bglVertex2fv(tface->uv[0]);
1071                                 if(!simaUVSel_Check(efa, tface, 1)); else bglVertex2fv(tface->uv[1]);
1072                                 if(!simaUVSel_Check(efa, tface, 2)); else bglVertex2fv(tface->uv[2]);
1073                                 if(efa->v4) {
1074                                         if(!simaUVSel_Check(efa, tface, 3)); else bglVertex2fv(tface->uv[3]);
1075                                 }
1076                         }
1077                 }
1078                 bglEnd();       
1079         }
1080         glPointSize(1.0);
1081 }
1082
1083 static unsigned int *get_part_from_ibuf(ImBuf *ibuf, short startx, short starty, short endx, short endy)
1084 {
1085         unsigned int *rt, *rp, *rectmain;
1086         short y, heigth, len;
1087
1088         /* the right offset in rectot */
1089
1090         rt= ibuf->rect+ (starty*ibuf->x+ startx);
1091
1092         len= (endx-startx);
1093         heigth= (endy-starty);
1094
1095         rp=rectmain= MEM_mallocN(heigth*len*sizeof(int), "rect");
1096         
1097         for(y=0; y<heigth; y++) {
1098                 memcpy(rp, rt, len*4);
1099                 rt+= ibuf->x;
1100                 rp+= len;
1101         }
1102         return rectmain;
1103 }
1104
1105 static void draw_image_transform(ImBuf *ibuf, float xuser_asp, float yuser_asp)
1106 {
1107         if(G.moving) {
1108                 float aspx, aspy, center[3];
1109
1110         BIF_drawConstraint();
1111
1112                 if(ibuf==0 || ibuf->rect==0 || ibuf->x==0 || ibuf->y==0) {
1113                         aspx= aspy= 1.0;
1114                 }
1115                 else {
1116                         aspx= (256.0/ibuf->x) * xuser_asp;
1117                         aspy= (256.0/ibuf->y) * yuser_asp;
1118                 }
1119                 BIF_getPropCenter(center);
1120
1121                 /* scale and translate the circle into place and draw it */
1122                 glPushMatrix();
1123                 glScalef(aspx, aspy, 1.0);
1124                 glTranslatef((1/aspx)*center[0] - center[0],
1125                              (1/aspy)*center[1] - center[1], 0.0);
1126
1127                 BIF_drawPropCircle();
1128
1129                 glPopMatrix();
1130         }
1131 }
1132
1133 static void draw_image_view_tool(void)
1134 {
1135         ToolSettings *settings= G.scene->toolsettings;
1136         Brush *brush= settings->imapaint.brush;
1137         short mval[2];
1138         float radius;
1139         int draw= 0;
1140
1141         if(brush) {
1142                 if(settings->imapaint.flag & IMAGEPAINT_DRAWING) {
1143                         if(settings->imapaint.flag & IMAGEPAINT_DRAW_TOOL_DRAWING)
1144                                 draw= 1;
1145                 }
1146                 else if(settings->imapaint.flag & IMAGEPAINT_DRAW_TOOL)
1147                         draw= 1;
1148                 
1149                 if(draw) {
1150                         getmouseco_areawin(mval);
1151
1152                         radius= brush->size*G.sima->zoom/2;
1153                         fdrawXORcirc(mval[0], mval[1], radius);
1154
1155                         if (brush->innerradius != 1.0) {
1156                                 radius *= brush->innerradius;
1157                                 fdrawXORcirc(mval[0], mval[1], radius);
1158                         }
1159                 }
1160         }
1161 }
1162
1163 /* ************ panel stuff ************* */
1164
1165 /* this function gets the values for cursor and vertex number buttons */
1166 static void image_transform_but_attr(int *imx, int *imy, int *step, int *digits) /*, float *xcoord, float *ycoord)*/
1167 {
1168         ImBuf *ibuf= imagewindow_get_ibuf(G.sima);
1169         if(ibuf) {
1170                 *imx= ibuf->x;
1171                 *imy= ibuf->y;
1172         }
1173         
1174         if (G.sima->flag & SI_COORDFLOATS) {
1175                 *step= 1;
1176                 *digits= 3;
1177         }
1178         else {
1179                 *step= 100;
1180                 *digits= 2;
1181         }
1182 }
1183
1184
1185 /* is used for both read and write... */
1186 void image_editvertex_buts(uiBlock *block)
1187 {
1188         static float ocent[2];
1189         float cent[2]= {0.0, 0.0};
1190         int imx= 256, imy= 256;
1191         int nactive= 0, step, digits;
1192         EditMesh *em = G.editMesh;
1193         EditFace *efa;
1194         MTFace *tf;
1195         
1196         if( is_uv_tface_editing_allowed_silent()==0 ) return;
1197         
1198         image_transform_but_attr(&imx, &imy, &step, &digits);
1199         
1200         for (efa= em->faces.first; efa; efa= efa->next) {
1201                 tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1202                 if (simaFaceDraw_Check(efa, tf)) {
1203                         
1204                         if (simaUVSel_Check(efa, tf, 0)) {
1205                                 cent[0]+= tf->uv[0][0];
1206                                 cent[1]+= tf->uv[0][1];
1207                                 nactive++;
1208                         }
1209                         if (simaUVSel_Check(efa, tf, 1)) {
1210                                 cent[0]+= tf->uv[1][0];
1211                                 cent[1]+= tf->uv[1][1];
1212                                 nactive++;
1213                         }
1214                         if (simaUVSel_Check(efa, tf, 2)) {
1215                                 cent[0]+= tf->uv[2][0];
1216                                 cent[1]+= tf->uv[2][1];
1217                                 nactive++;
1218                         }
1219                         if (efa->v4 && simaUVSel_Check(efa, tf, 3)) {
1220                                 cent[0]+= tf->uv[3][0];
1221                                 cent[1]+= tf->uv[3][1];
1222                                 nactive++;
1223                         }
1224                 }
1225         }
1226                 
1227         if(block) {     // do the buttons
1228                 if (nactive) {
1229                         ocent[0]= cent[0]/nactive;
1230                         ocent[1]= cent[1]/nactive;
1231                         if (G.sima->flag & SI_COORDFLOATS) {
1232                         } else {
1233                                 ocent[0] *= imx;
1234                                 ocent[1] *= imy;
1235                         }
1236                         
1237                         //uiBlockBeginAlign(block);
1238                         if(nactive==1) {
1239                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex X:",       10, 10, 145, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
1240                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Vertex Y:",       165, 10, 145, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
1241                         }
1242                         else {
1243                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median X:",       10, 10, 145, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
1244                                 uiDefButF(block, NUM, B_TRANS_IMAGE, "Median Y:",       165, 10, 145, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
1245                         }
1246                         //uiBlockEndAlign(block);
1247                 }
1248         }
1249         else {  // apply event
1250                 float delta[2];
1251                 
1252                 cent[0]= cent[0]/nactive;
1253                 cent[1]= cent[1]/nactive;
1254                         
1255                 if (G.sima->flag & SI_COORDFLOATS) {
1256                         delta[0]= ocent[0]-cent[0];
1257                         delta[1]= ocent[1]-cent[1];
1258                 }
1259                 else {
1260                         delta[0]= ocent[0]/imx - cent[0];
1261                         delta[1]= ocent[1]/imy - cent[1];
1262                 }
1263
1264                 for (efa= em->faces.first; efa; efa= efa->next) {
1265                         tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1266                         if (simaFaceDraw_Check(efa, tf)) {
1267                                 if (simaUVSel_Check(efa, tf, 0)) {
1268                                         tf->uv[0][0]+= delta[0];
1269                                         tf->uv[0][1]+= delta[1];
1270                                 }
1271                                 if (simaUVSel_Check(efa, tf, 1)) {
1272                                         tf->uv[1][0]+= delta[0];
1273                                         tf->uv[1][1]+= delta[1];
1274                                 }
1275                                 if (simaUVSel_Check(efa, tf, 2)) {
1276                                         tf->uv[2][0]+= delta[0];
1277                                         tf->uv[2][1]+= delta[1];
1278                                 }
1279                                 if (efa->v4 && simaUVSel_Check(efa, tf, 3)) {
1280                                         tf->uv[3][0]+= delta[0];
1281                                         tf->uv[3][1]+= delta[1];
1282                                 }
1283                         }
1284                 }
1285                         
1286                 allqueue(REDRAWVIEW3D, 0);
1287                 allqueue(REDRAWIMAGE, 0);
1288         }
1289 }
1290
1291
1292 /* is used for both read and write... */
1293 void image_editcursor_buts(uiBlock *block)
1294 {
1295         static float ocent[2];
1296         int imx= 256, imy= 256;
1297         int step, digits;
1298         
1299         if( is_uv_tface_editing_allowed_silent()==0 ) return;
1300         
1301         image_transform_but_attr(&imx, &imy, &step, &digits);
1302                 
1303         if(block) {     // do the buttons
1304                 ocent[0]= G.v2d->cursor[0];
1305                 ocent[1]= G.v2d->cursor[1];
1306                 if (G.sima->flag & SI_COORDFLOATS) {
1307                 } else {
1308                         ocent[0] *= imx;
1309                         ocent[1] *= imy;
1310                 }
1311                 
1312                 uiBlockBeginAlign(block);
1313                 uiDefButF(block, NUM, B_CURSOR_IMAGE, "Cursor X:",      165, 120, 145, 19, &ocent[0], -10*imx, 10.0*imx, step, digits, "");
1314                 uiDefButF(block, NUM, B_CURSOR_IMAGE, "Cursor Y:",      165, 100, 145, 19, &ocent[1], -10*imy, 10.0*imy, step, digits, "");
1315                 uiBlockEndAlign(block);
1316         }
1317         else {  // apply event
1318                 if (G.sima->flag & SI_COORDFLOATS) {
1319                         G.v2d->cursor[0]= ocent[0];
1320                         G.v2d->cursor[1]= ocent[1];
1321                 }
1322                 else {
1323                         G.v2d->cursor[0]= ocent[0]/imx;
1324                         G.v2d->cursor[1]= ocent[1]/imy;
1325                 }
1326                 allqueue(REDRAWIMAGE, 0);
1327         }
1328 }
1329
1330
1331 void image_info(Image *ima, ImBuf *ibuf, char *str)
1332 {
1333         int ofs= 0;
1334         
1335         str[0]= 0;
1336         
1337         if(ima==NULL) return;
1338         if(ibuf==NULL) {
1339                 sprintf(str, "Can not get an image");
1340                 return;
1341         }
1342         
1343         if(ima->source==IMA_SRC_MOVIE) {
1344                 ofs= sprintf(str, "Movie ");
1345                 if(ima->anim) 
1346                         ofs+= sprintf(str+ofs, "%d frs", IMB_anim_get_duration(ima->anim));
1347         }
1348         else
1349                 ofs= sprintf(str, "Image ");
1350
1351         ofs+= sprintf(str+ofs, ": size %d x %d,", ibuf->x, ibuf->y);
1352         
1353         if(ibuf->rect_float) {
1354                 if(ibuf->channels!=4) {
1355                         sprintf(str+ofs, "%d float channel(s)", ibuf->channels);
1356                 }
1357                 else if(ibuf->depth==32)
1358                         strcat(str, " RGBA float");
1359                 else
1360                         strcat(str, " RGB float");
1361         }
1362         else {
1363                 if(ibuf->depth==32)
1364                         strcat(str, " RGBA byte");
1365                 else
1366                         strcat(str, " RGB byte");
1367         }
1368         if(ibuf->zbuf || ibuf->zbuf_float)
1369                 strcat(str, " + Z");
1370         
1371 }
1372
1373 static void image_panel_properties(short cntrl) // IMAGE_HANDLER_PROPERTIES
1374 {
1375         uiBlock *block;
1376         
1377         block= uiNewBlock(&curarea->uiblocks, "image_panel_properties", UI_EMBOSS, UI_HELV, curarea->win);
1378         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1379         uiSetPanelHandler(IMAGE_HANDLER_PROPERTIES);  // for close and esc
1380         if(uiNewPanel(curarea, block, "Image Properties", "Image", 10, 10, 318, 204)==0)
1381                 return;
1382         
1383         /* note, it draws no bottom half in facemode, for vertex buttons */
1384         uiblock_image_panel(block, &G.sima->image, &G.sima->iuser, B_REDR, B_REDR);
1385         image_editvertex_buts(block);
1386 }       
1387
1388 static void image_panel_game_properties(short cntrl)    // IMAGE_HANDLER_GAME_PROPERTIES
1389 {
1390         ImBuf *ibuf= BKE_image_get_ibuf(G.sima->image, &G.sima->iuser);
1391         uiBlock *block;
1392
1393         block= uiNewBlock(&curarea->uiblocks, "image_panel_game_properties", UI_EMBOSS, UI_HELV, curarea->win);
1394         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1395         uiSetPanelHandler(IMAGE_HANDLER_GAME_PROPERTIES);  // for close and esc
1396         if(uiNewPanel(curarea, block, "Real-time Properties", "Image", 10, 10, 318, 204)==0)
1397                 return;
1398
1399         if (ibuf) {
1400                 char str[128];
1401                 
1402                 image_info(G.sima->image, ibuf, str);
1403                 uiDefBut(block, LABEL, B_NOP, str,              10,180,300,19, 0, 0, 0, 0, 0, "");
1404
1405                 uiBlockBeginAlign(block);
1406                 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");
1407                 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");
1408                 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");
1409                 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");
1410                 uiBlockEndAlign(block);
1411
1412                 uiBlockBeginAlign(block);
1413                 uiDefButBitS(block, TOG, IMA_TILES, B_SIMAGETILE, "Tiles",      160,150,140,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Toggles use of tilemode for faces (Shift LMB to pick the tile for selected faces)");
1414                 uiDefButS(block, NUM, B_SIMA_REDR_IMA_3D, "X:",         160,130,70,19, &G.sima->image->xrep, 1.0, 16.0, 0, 0, "Sets the degree of repetition in the X direction");
1415                 uiDefButS(block, NUM, B_SIMA_REDR_IMA_3D, "Y:",         230,130,70,19, &G.sima->image->yrep, 1.0, 16.0, 0, 0, "Sets the degree of repetition in the Y direction");
1416                 uiBlockBeginAlign(block);
1417
1418                 uiBlockBeginAlign(block);
1419                 uiDefButBitS(block, TOG, IMA_CLAMP_U, B_SIMA3DVIEWDRAW, "ClampX",       160,100,70,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Disable texture repeating horizontaly");
1420                 uiDefButBitS(block, TOG, IMA_CLAMP_V, B_SIMA3DVIEWDRAW, "ClampY",       230,100,70,19, &G.sima->image->tpageflag, 0, 0, 0, 0, "Disable texture repeating vertically");
1421                 uiBlockEndAlign(block);
1422         }
1423 }
1424
1425 static void image_panel_view_properties(short cntrl)    // IMAGE_HANDLER_VIEW_PROPERTIES
1426 {
1427         uiBlock *block;
1428
1429         block= uiNewBlock(&curarea->uiblocks, "image_view_properties", UI_EMBOSS, UI_HELV, curarea->win);
1430         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1431         uiSetPanelHandler(IMAGE_HANDLER_VIEW_PROPERTIES);  // for close and esc
1432         if(uiNewPanel(curarea, block, "View Properties", "Image", 10, 10, 318, 204)==0)
1433                 return;
1434         
1435         
1436         uiDefButBitI(block, TOG, SI_DRAW_TILE, B_REDR, "Repeat Image",  10,160,140,19, &G.sima->flag, 0, 0, 0, 0, "Repeat/Tile the image display");
1437         uiDefButBitI(block, TOG, SI_COORDFLOATS, B_REDR, "Normalized Coords",   165,160,145,19, &G.sima->flag, 0, 0, 0, 0, "Display coords from 0.0 to 1.0 rather then in pixels");
1438         
1439         
1440         if (G.sima->image) {
1441                 uiDefBut(block, LABEL, B_NOP, "Image Display:",         10,140,140,19, 0, 0, 0, 0, 0, "");
1442                 uiBlockBeginAlign(block);
1443                 uiDefButF(block, NUM, B_REDR, "AspX:", 10,120,140,19, &G.sima->image->aspx, 0.1, 5000.0, 100, 0, "X Display Aspect for this image, does not affect renderingm 0 disables.");
1444                 uiDefButF(block, NUM, B_REDR, "AspY:", 10,100,140,19, &G.sima->image->aspy, 0.1, 5000.0, 100, 0, "X Display Aspect for this image, does not affect rendering 0 disables.");
1445                 uiBlockEndAlign(block);
1446         }
1447         
1448         
1449         if (EM_texFaceCheck()) {
1450                 uiDefBut(block, LABEL, B_NOP, "Draw Type:",             10, 80,120,19, 0, 0, 0, 0, 0, "");
1451                 uiBlockBeginAlign(block);
1452                 uiDefButC(block,  ROW, B_REDR, "Outline",               10,60,58,19, &G.sima->dt_uv, 0.0, SI_UVDT_OUTLINE, 0, 0, "Outline Wire UV drawtype");
1453                 uiDefButC(block,  ROW, B_REDR, "Dash",                  68, 60,58,19, &G.sima->dt_uv, 0.0, SI_UVDT_DASH, 0, 0, "Dashed Wire UV drawtype");
1454                 uiDefButC(block,  ROW, B_REDR, "Black",                 126, 60,58,19, &G.sima->dt_uv, 0.0, SI_UVDT_BLACK, 0, 0, "Black Wire UV drawtype");
1455                 uiDefButC(block,  ROW, B_REDR, "White",                 184,60,58,19, &G.sima->dt_uv, 0.0, SI_UVDT_WHITE, 0, 0, "White Wire UV drawtype");
1456                 
1457                 uiBlockEndAlign(block);
1458                 uiDefButBitI(block, TOG, SI_SMOOTH_UV, B_REDR, "Smooth",        250,60,60,19,  &G.sima->flag, 0, 0, 0, 0, "Display smooth lines in the UV view");
1459                 
1460                 
1461                 uiDefButBitI(block, TOG, G_DRAWFACES, B_REDR, "Faces",          10,30,60,19,  &G.f, 0, 0, 0, 0, "Displays all faces as shades in the 3d view and UV editor");
1462                 uiDefButBitI(block, TOG, G_DRAWEDGES, B_REDR, "Edges", 70, 30,60,19, &G.f, 0, 0, 0, 0, "Displays selected edges using hilights and UV editor");
1463                 
1464                 uiDefButBitI(block, TOG, SI_DRAWSHADOW, B_REDR, "Final Shadow", 130, 30,110,19, &G.sima->flag, 0, 0, 0, 0, "Draw the final result from the objects modifiers");
1465                 
1466                 uiDefButBitI(block, TOG, SI_DRAW_STRETCH, B_REDR, "UV Stretch", 10,0,100,19,  &G.sima->flag, 0, 0, 0, 0, "Difference between UV's and the 3D coords (blue for low distortion, red is high)");
1467                 if (G.sima->flag & SI_DRAW_STRETCH) {
1468                         uiBlockBeginAlign(block);
1469                         uiDefButC(block,  ROW, B_REDR, "Area",                  120,0,60,19, &G.sima->dt_uvstretch, 0.0, SI_UVDT_STRETCH_AREA, 0, 0, "Area distortion between UV's and 3D coords");
1470                         uiDefButC(block,  ROW, B_REDR, "Angle",         180,0,60,19, &G.sima->dt_uvstretch, 0.0, SI_UVDT_STRETCH_ANGLE, 0, 0, "Angle distortion between UV's and 3D coords");
1471                         uiBlockEndAlign(block);
1472                 }
1473                 
1474         }
1475         image_editcursor_buts(block);
1476 }
1477
1478 static void image_panel_paint(short cntrl)      // IMAGE_HANDLER_PAINT
1479 {
1480         /* B_SIMABRUSHCHANGE only redraws and eats the mouse messages  */
1481         /* so that LEFTMOUSE does not 'punch' through the floating panel */
1482         /* B_SIMANOTHING */
1483         ToolSettings *settings= G.scene->toolsettings;
1484         Brush *brush= settings->imapaint.brush;
1485         uiBlock *block;
1486         ID *id;
1487         int yco, xco, butw;
1488
1489         block= uiNewBlock(&curarea->uiblocks, "image_panel_paint", UI_EMBOSS, UI_HELV, curarea->win);
1490         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1491         uiSetPanelHandler(IMAGE_HANDLER_PAINT);  // for close and esc
1492         if(uiNewPanel(curarea, block, "Image Paint", "Image", 10, 230, 318, 204)==0)
1493                 return;
1494
1495         yco= 160;
1496
1497         uiBlockBeginAlign(block);
1498         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Draw",                0  ,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_DRAW, 0, 0, "Draw brush");
1499         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Soften",              80 ,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_SOFTEN, 0, 0, "Soften brush");
1500         uiDefButS(block, ROW, B_SIMABRUSHCHANGE, "Smear",               160,yco,80,19, &settings->imapaint.tool, 7.0, PAINT_TOOL_SMEAR, 0, 0, "Smear brush");   
1501         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");     
1502         uiBlockEndAlign(block);
1503         yco -= 30;
1504
1505         uiBlockSetCol(block, TH_BUT_SETTING2);
1506         id= (ID*)settings->imapaint.brush;
1507         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);
1508         uiBlockSetCol(block, TH_AUTO);
1509
1510         if(brush && !brush->id.lib) {
1511                 butw= 320-(xco+10);
1512
1513                 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");
1514
1515                 uiDefButBitS(block, TOG|BIT, BRUSH_TORUS, B_SIMABRUSHCHANGE, "Wrap",    xco+10,yco-25,butw,19, &brush->flag, 0, 0, 0, 0, "Enables torus wrapping");
1516
1517                 uiBlockBeginAlign(block);
1518                 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)");
1519                 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");
1520                 uiBlockEndAlign(block);
1521
1522                 yco -= 25;
1523
1524                 uiBlockBeginAlign(block);
1525                 uiDefButF(block, COL, B_VPCOLSLI, "",                                   0,yco,200,19, brush->rgb, 0, 0, 0, 0, "");
1526                 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");
1527                 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");
1528                 uiDefButI(block, NUMSLI, B_SIMANOTHING, "Size ",                0,yco-40,180,19, &brush->size, 1, 200, 0, 0, "The size of the brush");
1529                 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");
1530                 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");
1531                 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");
1532                 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");
1533                 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");
1534                 uiBlockEndAlign(block);
1535
1536                 yco -= 110;
1537
1538                 if(settings->imapaint.tool == PAINT_TOOL_CLONE) {
1539                         id= (ID*)brush->clone.image;
1540                         uiBlockSetCol(block, TH_BUT_SETTING2);
1541                         xco= std_libbuttons(block, 0, yco, 0, NULL, B_SIMACLONEBROWSE, ID_IM, 0, id, 0, &G.sima->menunr, 0, 0, B_SIMACLONEDELETE, 0, 0);
1542                         uiBlockSetCol(block, TH_AUTO);
1543                         if(id) {
1544                                 butw= 320-(xco+5);
1545                                 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");
1546                         }
1547                 }
1548                 else {
1549                         MTex *mtex= brush->mtex[brush->texact];
1550
1551                         uiBlockSetCol(block, TH_BUT_SETTING2);
1552                         id= (mtex)? (ID*)mtex->tex: NULL;
1553                         xco= std_libbuttons(block, 0, yco, 0, NULL, B_SIMABTEXBROWSE, ID_TE, 0, id, NULL, &(G.sima->menunr), 0, 0, B_SIMABTEXDELETE, 0, 0);
1554                         /*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");*/
1555                         uiBlockSetCol(block, TH_AUTO);
1556                 }
1557         }
1558
1559 #if 0
1560                 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");
1561                 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");
1562 #endif
1563 }
1564
1565 static void image_panel_curves_reset(void *cumap_v, void *ibuf_v)
1566 {
1567         CurveMapping *cumap = cumap_v;
1568         int a;
1569         
1570         for(a=0; a<CM_TOT; a++)
1571                 curvemap_reset(cumap->cm+a, &cumap->clipr);
1572         
1573         cumap->black[0]=cumap->black[1]=cumap->black[2]= 0.0f;
1574         cumap->white[0]=cumap->white[1]=cumap->white[2]= 1.0f;
1575         curvemapping_set_black_white(cumap, NULL, NULL);
1576         
1577         curvemapping_changed(cumap, 0);
1578         curvemapping_do_ibuf(cumap, ibuf_v);
1579         
1580         allqueue(REDRAWIMAGE, 0);
1581 }
1582
1583
1584 static void image_panel_curves(short cntrl)     // IMAGE_HANDLER_CURVES
1585 {
1586         ImBuf *ibuf;
1587         uiBlock *block;
1588         uiBut *bt;
1589         
1590         /* and we check for spare */
1591         ibuf= imagewindow_get_ibuf(G.sima);
1592         
1593         block= uiNewBlock(&curarea->uiblocks, "image_panel_curves", UI_EMBOSS, UI_HELV, curarea->win);
1594         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
1595         uiSetPanelHandler(IMAGE_HANDLER_CURVES);  // for close and esc
1596         if(uiNewPanel(curarea, block, "Curves", "Image", 10, 450, 318, 204)==0)
1597                 return;
1598         
1599         if (ibuf) {
1600                 rctf rect;
1601                 
1602                 if(G.sima->cumap==NULL)
1603                         G.sima->cumap= curvemapping_add(4, 0.0f, 0.0f, 1.0f, 1.0f);
1604                 
1605                 rect.xmin= 110; rect.xmax= 310;
1606                 rect.ymin= 10; rect.ymax= 200;
1607                 curvemap_buttons(block, G.sima->cumap, 'c', B_SIMACURVES, B_REDR, &rect);
1608                 
1609                 bt=uiDefBut(block, BUT, B_SIMARANGE, "Reset",   10, 160, 90, 19, NULL, 0.0f, 0.0f, 0, 0, "Reset Black/White point and curves");
1610                 uiButSetFunc(bt, image_panel_curves_reset, G.sima->cumap, ibuf);
1611                 
1612                 uiBlockBeginAlign(block);
1613                 uiDefButF(block, NUM, B_SIMARANGE, "Min R:",    10, 120, 90, 19, G.sima->cumap->black, -1000.0f, 1000.0f, 10, 2, "Black level");
1614                 uiDefButF(block, NUM, B_SIMARANGE, "Min G:",    10, 100, 90, 19, G.sima->cumap->black+1, -1000.0f, 1000.0f, 10, 2, "Black level");
1615                 uiDefButF(block, NUM, B_SIMARANGE, "Min B:",    10, 80, 90, 19, G.sima->cumap->black+2, -1000.0f, 1000.0f, 10, 2, "Black level");
1616                 
1617                 uiBlockBeginAlign(block);
1618                 uiDefButF(block, NUM, B_SIMARANGE, "Max R:",    10, 50, 90, 19, G.sima->cumap->white, -1000.0f, 1000.0f, 10, 2, "White level");
1619                 uiDefButF(block, NUM, B_SIMARANGE, "Max G:",    10, 30, 90, 19, G.sima->cumap->white+1, -1000.0f, 1000.0f, 10, 2, "White level");
1620                 uiDefButF(block, NUM, B_SIMARANGE, "Max B:",    10, 10, 90, 19, G.sima->cumap->white+2, -1000.0f, 1000.0f, 10, 2, "White level");
1621                 
1622         }
1623 }
1624
1625 /* are there curves? curves visible? and curves do something? */
1626 static int image_curves_active(ScrArea *sa)
1627 {
1628         SpaceImage *sima= sa->spacedata.first;
1629
1630         if(sima->cumap) {
1631                 if(curvemapping_RGBA_does_something(sima->cumap)) {
1632                         short a;
1633                         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1634                                 if(sima->blockhandler[a] == IMAGE_HANDLER_CURVES)
1635                                         return 1;
1636                         }
1637                 }
1638         }
1639         return 0;
1640 }
1641
1642 /* 0: disable preview 
1643    otherwise refresh preview
1644 */
1645 void image_preview_event(int event)
1646 {
1647         int exec= 0;
1648         
1649
1650         if(event==0) {
1651                 G.scene->r.scemode &= ~R_COMP_CROP;
1652                 exec= 1;
1653         }
1654         else {
1655                 if(image_preview_active(curarea, NULL, NULL)) {
1656                         G.scene->r.scemode |= R_COMP_CROP;
1657                         exec= 1;
1658                 }
1659                 else
1660                         G.scene->r.scemode &= ~R_COMP_CROP;
1661         }
1662         
1663         if(exec && G.scene->nodetree) {
1664                 /* should work when no node editor in screen..., so we execute right away */
1665                 
1666                 ntreeCompositTagGenerators(G.scene->nodetree);
1667
1668                 G.afbreek= 0;
1669                 G.scene->nodetree->timecursor= set_timecursor;
1670                 G.scene->nodetree->test_break= blender_test_break;
1671                 
1672                 BIF_store_spare();
1673                 
1674                 ntreeCompositExecTree(G.scene->nodetree, &G.scene->r, 1);       /* 1 is do_previews */
1675                 
1676                 G.scene->nodetree->timecursor= NULL;
1677                 G.scene->nodetree->test_break= NULL;
1678                 
1679                 scrarea_do_windraw(curarea);
1680                 waitcursor(0);
1681                 
1682                 allqueue(REDRAWNODE, 1);
1683         }       
1684 }
1685
1686
1687 /* nothing drawn here, we use it to store values */
1688 static void preview_cb(struct ScrArea *sa, struct uiBlock *block)
1689 {
1690         rctf dispf;
1691         rcti *disprect= &G.scene->r.disprect;
1692         int winx= (G.scene->r.size*G.scene->r.xsch)/100;
1693         int winy= (G.scene->r.size*G.scene->r.ysch)/100;
1694         short mval[2];
1695         
1696         if(G.scene->r.mode & R_BORDER) {
1697                 winx*= (G.scene->r.border.xmax - G.scene->r.border.xmin);
1698                 winy*= (G.scene->r.border.ymax - G.scene->r.border.ymin);
1699         }
1700         
1701         /* while dragging we need to update the rects, otherwise it doesn't end with correct one */
1702
1703         BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
1704         ui_graphics_to_window_rct(sa->win, &dispf, disprect);
1705         
1706         /* correction for gla draw */
1707         BLI_translate_rcti(disprect, -curarea->winrct.xmin, -curarea->winrct.ymin);
1708         
1709         calc_image_view(G.sima, 'p');
1710 //      printf("winrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1711         /* map to image space coordinates */
1712         mval[0]= disprect->xmin; mval[1]= disprect->ymin;
1713         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmin, &dispf.ymin);
1714         mval[0]= disprect->xmax; mval[1]= disprect->ymax;
1715         areamouseco_to_ipoco(G.v2d, mval, &dispf.xmax, &dispf.ymax);
1716         
1717         /* map to render coordinates */
1718         disprect->xmin= dispf.xmin;
1719         disprect->xmax= dispf.xmax;
1720         disprect->ymin= dispf.ymin;
1721         disprect->ymax= dispf.ymax;
1722         
1723         CLAMP(disprect->xmin, 0, winx);
1724         CLAMP(disprect->xmax, 0, winx);
1725         CLAMP(disprect->ymin, 0, winy);
1726         CLAMP(disprect->ymax, 0, winy);
1727 //      printf("drawrct %d %d %d %d\n", disprect->xmin, disprect->ymin,disprect->xmax, disprect->ymax);
1728
1729 }
1730
1731 static int is_preview_allowed(ScrArea *cur)
1732 {
1733         SpaceImage *sima= cur->spacedata.first;
1734         ScrArea *sa;
1735
1736         /* check if another areawindow has preview set */
1737         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
1738                 if(sa!=cur && sa->spacetype==SPACE_IMAGE) {
1739                         if(image_preview_active(sa, NULL, NULL))
1740                            return 0;
1741                 }
1742         }
1743         /* check image type */
1744         if(sima->image==NULL || sima->image->type!=IMA_TYPE_COMPOSITE)
1745                 return 0;
1746         
1747         return 1;
1748 }
1749
1750 static void image_panel_preview(ScrArea *sa, short cntrl)       // IMAGE_HANDLER_PREVIEW
1751 {
1752         uiBlock *block;
1753         SpaceImage *sima= sa->spacedata.first;
1754         int ofsx, ofsy;
1755         
1756         if(is_preview_allowed(sa)==0) {
1757                 rem_blockhandler(sa, IMAGE_HANDLER_PREVIEW);
1758                 G.scene->r.scemode &= ~R_COMP_CROP;     /* quite weak */
1759                 return;
1760         }
1761         
1762         block= uiNewBlock(&sa->uiblocks, "image_panel_preview", UI_EMBOSS, UI_HELV, sa->win);
1763         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | UI_PNL_SCALE | cntrl);
1764         uiSetPanelHandler(IMAGE_HANDLER_PREVIEW);  // for close and esc
1765         
1766         ofsx= -150+(sa->winx/2)/sima->blockscale;
1767         ofsy= -100+(sa->winy/2)/sima->blockscale;
1768         if(uiNewPanel(sa, block, "Preview", "Image", ofsx, ofsy, 300, 200)==0) return;
1769         
1770         uiBlockSetDrawExtraFunc(block, preview_cb);
1771         
1772 }
1773
1774 static void image_blockhandlers(ScrArea *sa)
1775 {
1776         SpaceImage *sima= sa->spacedata.first;
1777         short a;
1778
1779         /* warning; blocks need to be freed each time, handlers dont remove  */
1780         uiFreeBlocksWin(&sa->uiblocks, sa->win);
1781         
1782         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
1783                 switch(sima->blockhandler[a]) {
1784
1785                 case IMAGE_HANDLER_PROPERTIES:
1786                         image_panel_properties(sima->blockhandler[a+1]);
1787                         break;
1788                 case IMAGE_HANDLER_GAME_PROPERTIES:
1789                         image_panel_game_properties(sima->blockhandler[a+1]);
1790                         break;
1791                 case IMAGE_HANDLER_VIEW_PROPERTIES:
1792                         image_panel_view_properties(sima->blockhandler[a+1]);
1793                         break;
1794                 case IMAGE_HANDLER_PAINT:
1795                         image_panel_paint(sima->blockhandler[a+1]);
1796                         break;          
1797                 case IMAGE_HANDLER_CURVES:
1798                         image_panel_curves(sima->blockhandler[a+1]);
1799                         break;          
1800                 case IMAGE_HANDLER_PREVIEW:
1801                         image_panel_preview(sa, sima->blockhandler[a+1]);
1802                         break;          
1803                 }
1804                 /* clear action value for event */
1805                 sima->blockhandler[a+1]= 0;
1806         }
1807         uiDrawBlocksPanels(sa, 0);
1808 }
1809
1810 void imagespace_composite_flipbook(ScrArea *sa)
1811 {
1812         SpaceImage *sima= sa->spacedata.first;
1813         ImBuf *ibuf;
1814         int cfrao= G.scene->r.cfra;
1815         int sfra, efra;
1816         
1817         if(sa->spacetype!=SPACE_IMAGE)
1818                 return;
1819         if(sima->iuser.frames<2)
1820                 return;
1821         if(G.scene->nodetree==NULL)
1822                 return;
1823         
1824         sfra= sima->iuser.sfra;
1825         efra= sima->iuser.sfra + sima->iuser.frames-1;
1826         G.scene->nodetree->test_break= blender_test_break;
1827         
1828         for(G.scene->r.cfra=sfra; G.scene->r.cfra<=efra; G.scene->r.cfra++) {
1829                 
1830                 set_timecursor(CFRA);
1831                 
1832                 BKE_image_all_free_anim_ibufs(CFRA);
1833                 ntreeCompositTagAnimated(G.scene->nodetree);
1834                 ntreeCompositExecTree(G.scene->nodetree, &G.scene->r, G.scene->r.cfra!=cfrao);  /* 1 is no previews */
1835                 
1836                 force_draw(0);
1837                 
1838                 ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
1839                 /* save memory in flipbooks */
1840                 if(ibuf)
1841                         imb_freerectfloatImBuf(ibuf);
1842                 
1843                 if(blender_test_break())
1844                         break;
1845         }
1846         G.scene->nodetree->test_break= NULL;
1847         waitcursor(0);
1848         
1849         play_anim(0);
1850         
1851         allqueue(REDRAWNODE, 1);
1852         allqueue(REDRAWIMAGE, 1);
1853         
1854         G.scene->r.cfra= cfrao;
1855 }
1856
1857 static void imagespace_grid(SpaceImage *sima)
1858 {
1859         float gridsize, gridstep= 1.0f/32.0f;
1860         float fac, blendfac;
1861         
1862         gridsize= sima->zoom;
1863         
1864         calc_image_view(sima, 'f');
1865         myortho2(sima->v2d.cur.xmin, sima->v2d.cur.xmax, sima->v2d.cur.ymin, sima->v2d.cur.ymax);
1866         
1867         BIF_ThemeColorShade(TH_BACK, 20);
1868         glRectf(0.0, 0.0, 1.0, 1.0);
1869         
1870         if(gridsize<=0.0f) return;
1871         
1872         if(gridsize<1.0f) {
1873                 while(gridsize<1.0f) {
1874                         gridsize*= 4.0;
1875                         gridstep*= 4.0;
1876                 }
1877         }
1878         else {
1879                 while(gridsize>=4.0f) {
1880                         gridsize/= 4.0;
1881                         gridstep/= 4.0;
1882                 }
1883         }
1884         
1885         /* the fine resolution level */
1886         blendfac= 0.25*gridsize - floor(0.25*gridsize);
1887         CLAMP(blendfac, 0.0, 1.0);
1888         BIF_ThemeColorShade(TH_BACK, (int)(20.0*(1.0-blendfac)));
1889         
1890         fac= 0.0f;
1891         glBegin(GL_LINES);
1892         while(fac<1.0) {
1893                 glVertex2f(0.0f, fac);
1894                 glVertex2f(1.0f, fac);
1895                 glVertex2f(fac, 0.0f);
1896                 glVertex2f(fac, 1.0f);
1897                 fac+= gridstep;
1898         }
1899         
1900         /* the large resolution level */
1901         BIF_ThemeColor(TH_BACK);
1902         
1903         fac= 0.0f;
1904         while(fac<1.0) {
1905                 glVertex2f(0.0f, fac);
1906                 glVertex2f(1.0f, fac);
1907                 glVertex2f(fac, 0.0f);
1908                 glVertex2f(fac, 1.0f);
1909                 fac+= 4.0*gridstep;
1910         }
1911         glEnd();
1912         
1913 }
1914
1915 static void sima_draw_alpha_backdrop(SpaceImage *sima, float x1, float y1, float xsize, float ysize)
1916 {
1917         GLubyte checker_stipple[32*32/8] =
1918         {
1919                 255,255,0,0,255,255,0,0,255,255,0,0,255,255,0,0, \
1920                 255,255,0,0,255,255,0,0,255,255,0,0,255,255,0,0, \
1921                 255,255,0,0,255,255,0,0,255,255,0,0,255,255,0,0, \
1922                 255,255,0,0,255,255,0,0,255,255,0,0,255,255,0,0, \
1923                 0,0,255,255,0,0,255,255,0,0,255,255,0,0,255,255, \
1924                 0,0,255,255,0,0,255,255,0,0,255,255,0,0,255,255, \
1925                 0,0,255,255,0,0,255,255,0,0,255,255,0,0,255,255, \
1926                 0,0,255,255,0,0,255,255,0,0,255,255,0,0,255,255, \
1927         };
1928         
1929         glColor3ub(100, 100, 100);
1930         glRectf(x1, y1, x1 + sima->zoom*xsize, y1 + sima->zoom*ysize);
1931         glColor3ub(160, 160, 160);
1932
1933         glEnable(GL_POLYGON_STIPPLE);
1934         glPolygonStipple(checker_stipple);
1935         glRectf(x1, y1, x1 + sima->zoom*xsize, y1 + sima->zoom*ysize);
1936         glDisable(GL_POLYGON_STIPPLE);
1937 }
1938
1939 static void sima_draw_alpha_pixels(float x1, float y1, int rectx, int recty, unsigned int *recti)
1940 {
1941         
1942         /* swap bytes, so alpha is most significant one, then just draw it as luminance int */
1943         if(G.order==B_ENDIAN)
1944                 glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
1945         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_UNSIGNED_INT, recti);
1946         glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
1947 }
1948
1949 static void sima_draw_alpha_pixelsf(float x1, float y1, int rectx, int recty, float *rectf)
1950 {
1951         float *trectf= MEM_mallocN(rectx*recty*4, "temp");
1952         int a, b;
1953         
1954         for(a= rectx*recty -1, b= 4*a+3; a>=0; a--, b-=4)
1955                 trectf[a]= rectf[b];
1956         
1957         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, trectf);
1958         MEM_freeN(trectf);
1959         /* ogl trick below is slower... (on ATI 9600) */
1960 //      glColorMask(1, 0, 0, 0);
1961 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+3);
1962 //      glColorMask(0, 1, 0, 0);
1963 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+2);
1964 //      glColorMask(0, 0, 1, 0);
1965 //      glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_RGBA, GL_FLOAT, rectf+1);
1966 //      glColorMask(1, 1, 1, 1);
1967 }
1968
1969 static void sima_draw_zbuf_pixels(float x1, float y1, int rectx, int recty, int *recti)
1970 {
1971         if(recti==NULL)
1972                 return;
1973         
1974         /* zbuffer values are signed, so we need to shift color range */
1975         glPixelTransferf(GL_RED_SCALE, 0.5f);
1976         glPixelTransferf(GL_GREEN_SCALE, 0.5f);
1977         glPixelTransferf(GL_BLUE_SCALE, 0.5f);
1978         glPixelTransferf(GL_RED_BIAS, 0.5f);
1979         glPixelTransferf(GL_GREEN_BIAS, 0.5f);
1980         glPixelTransferf(GL_BLUE_BIAS, 0.5f);
1981         
1982         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_INT, recti);
1983         
1984         glPixelTransferf(GL_RED_SCALE, 1.0f);
1985         glPixelTransferf(GL_GREEN_SCALE, 1.0f);
1986         glPixelTransferf(GL_BLUE_SCALE, 1.0f);
1987         glPixelTransferf(GL_RED_BIAS, 0.0f);
1988         glPixelTransferf(GL_GREEN_BIAS, 0.0f);
1989         glPixelTransferf(GL_BLUE_BIAS, 0.0f);
1990 }
1991
1992 static void sima_draw_zbuffloat_pixels(float x1, float y1, int rectx, int recty, float *rect_float)
1993 {
1994         float bias, scale, *rectf, clipend;
1995         int a;
1996         
1997         if(rect_float==NULL)
1998                 return;
1999         
2000         if(G.scene->camera && G.scene->camera->type==OB_CAMERA) {
2001                 bias= ((Camera *)G.scene->camera->data)->clipsta;
2002                 clipend= ((Camera *)G.scene->camera->data)->clipend;
2003                 scale= 1.0f/(clipend-bias);
2004         }
2005         else {
2006                 bias= 0.1f;
2007                 scale= 0.01f;
2008                 clipend= 100.0f;
2009         }
2010         
2011         rectf= MEM_mallocN(rectx*recty*4, "temp");
2012         for(a= rectx*recty -1; a>=0; a--) {
2013                 if(rect_float[a]>clipend)
2014                         rectf[a]= 0.0f;
2015                 else if(rect_float[a]<bias)
2016                         rectf[a]= 1.0f;
2017                 else {
2018                         rectf[a]= 1.0f - (rect_float[a]-bias)*scale;
2019                         rectf[a]*= rectf[a];
2020                 }
2021         }
2022         glaDrawPixelsSafe(x1, y1, rectx, recty, rectx, GL_LUMINANCE, GL_FLOAT, rectf);
2023         
2024         MEM_freeN(rectf);
2025 }
2026
2027 static void imagewindow_draw_renderinfo(ScrArea *sa)
2028 {
2029         rcti rect;
2030         float colf[3];
2031         int showspare= BIF_show_render_spare();
2032         char *str= BIF_render_text();
2033         
2034         if(str==NULL)
2035                 return;
2036         
2037         rect= sa->winrct;
2038         rect.ymin= rect.ymax-RW_HEADERY;
2039         
2040         glaDefine2DArea(&rect);
2041         
2042         /* clear header rect */
2043         BIF_GetThemeColor3fv(TH_BACK, colf);
2044         glClearColor(colf[0]+0.1f, colf[1]+0.1f, colf[2]+0.1f, 1.0); 
2045         glClear(GL_COLOR_BUFFER_BIT);
2046         
2047         BIF_ThemeColor(TH_TEXT_HI);
2048         glRasterPos2i(12, 5);
2049         if(showspare) {
2050                 BMF_DrawString(G.fonts, "(Previous)");
2051                 glRasterPos2i(72, 5);
2052         }               
2053         BMF_DrawString(G.fonts, str);
2054 }
2055
2056 void drawimagespace(ScrArea *sa, void *spacedata)
2057 {
2058         SpaceImage *sima= spacedata;
2059         ImBuf *ibuf= NULL;
2060         Brush *brush;
2061         float col[3];
2062         unsigned int *rect;
2063         float x1, y1;
2064         short sx, sy, dx, dy, show_render= 0, show_viewer= 0;
2065         float xuser_asp=1, yuser_asp=1;
2066                 /* If derived data is used then make sure that object
2067                  * is up-to-date... might not be the case because updates
2068                  * are normally done in drawview and could get here before
2069                  * drawing a View3D.
2070                  */
2071         if (G.obedit && OBACT && (sima->flag & SI_DRAWSHADOW)) {
2072                 object_handle_update(OBACT);
2073         }
2074         
2075         BIF_GetThemeColor3fv(TH_BACK, col);
2076         glClearColor(col[0], col[1], col[2], 0.0);
2077         glClear(GL_COLOR_BUFFER_BIT);
2078
2079         bwin_clear_viewmat(sa->win);    /* clear buttons view */
2080         glLoadIdentity();
2081         
2082         if(sima->image && sima->image->source==IMA_SRC_VIEWER) {
2083                 show_viewer= 1;
2084                 if(sima->image->type==IMA_TYPE_R_RESULT)
2085                         show_render= 1;
2086         }
2087         
2088         what_image(sima);
2089         
2090         if(sima->image) {
2091                 image_pixel_aspect(sima->image, &xuser_asp, &yuser_asp);
2092                 
2093                 /* UGLY hack? until now iusers worked fine... but for flipbook viewer we need this */
2094                 if(sima->image->type==IMA_TYPE_COMPOSITE) {
2095                         ImageUser *iuser= ntree_get_active_iuser(G.scene->nodetree);
2096                         if(iuser) {
2097                                 BKE_image_user_calc_imanr(iuser, G.scene->r.cfra, 0);
2098                                 G.sima->iuser= *iuser;
2099                         }
2100                 }
2101                 /* and we check for spare */
2102                 ibuf= imagewindow_get_ibuf(sima);
2103         }
2104         
2105         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL)) {
2106                 imagespace_grid(sima);
2107                 if(show_viewer==0) {
2108                         draw_uvs_sima();
2109                         drawcursor_sima(xuser_asp, yuser_asp);
2110                 }
2111         }
2112         else {
2113                 float xim, yim, xoffs=0.0f, yoffs= 0.0f;
2114                 
2115                 if(image_preview_active(sa, &xim, &yim)) {
2116                         xoffs= G.scene->r.disprect.xmin;
2117                         yoffs= G.scene->r.disprect.ymin;
2118                         glColor3ub(0,0,0);
2119                         calc_image_view(sima, 'f');     
2120                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
2121                         glRectf(0.0f, 0.0f, 1.0f, 1.0f);
2122                         glLoadIdentity();
2123                 }
2124                 else {
2125                         xim= ibuf->x * xuser_asp; yim= ibuf->y * yuser_asp;
2126                 }
2127                 
2128                 /* calc location */
2129                 x1= sima->zoom*xoffs + ((float)sa->winx - sima->zoom*(float)xim)/2.0f;
2130                 y1= sima->zoom*yoffs + ((float)sa->winy - sima->zoom*(float)yim)/2.0f;
2131         
2132                 x1-= sima->zoom*sima->xof;
2133                 y1-= sima->zoom*sima->yof;
2134                 
2135                 /* needed for gla draw */
2136                 if(show_render) { 
2137                         rcti rct= sa->winrct; 
2138                         
2139                         imagewindow_draw_renderinfo(sa);        /* calls glaDefine2DArea too */
2140                         
2141                         rct.ymax-=RW_HEADERY; 
2142                         glaDefine2DArea(&rct);
2143                 }
2144                 else glaDefine2DArea(&sa->winrct);
2145                 
2146                 glPixelZoom(sima->zoom * xuser_asp, sima->zoom * yuser_asp);
2147                                 
2148                 if(sima->flag & SI_EDITTILE) {
2149                         /* create char buffer from float if needed */
2150                         if(ibuf->rect_float && ibuf->rect==NULL)
2151                                 IMB_rect_from_float(ibuf);
2152
2153                         glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
2154                         
2155                         glPixelZoom(1.0, 1.0);
2156                         
2157                         dx= ibuf->x/sima->image->xrep;
2158                         dy= ibuf->y/sima->image->yrep;
2159                         sy= (sima->curtile / sima->image->xrep);
2160                         sx= sima->curtile - sy*sima->image->xrep;
2161         
2162                         sx*= dx;
2163                         sy*= dy;
2164                         
2165                         calc_image_view(sima, 'p');     /* pixel */
2166                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
2167                         
2168                         cpack(0x0);
2169                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx,  sy,  sx+dx-1,  sy+dy-1); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
2170                         cpack(0xFFFFFF);
2171                         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRects(sx+1,  sy+1,  sx+dx,  sy+dy); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
2172                 }
2173                 else if(sima->mode==SI_TEXTURE) {
2174                         
2175                         if(sima->image->tpageflag & IMA_TILES) {
2176                                 
2177                                 /* just leave this a while */
2178                                 if(sima->image->xrep<1) return;
2179                                 if(sima->image->yrep<1) return;
2180                                 
2181                                 if(sima->curtile >= sima->image->xrep*sima->image->yrep) 
2182                                         sima->curtile = sima->image->xrep*sima->image->yrep - 1; 
2183                                 
2184                                 dx= ibuf->x/sima->image->xrep;
2185                                 dy= ibuf->y/sima->image->yrep;
2186                                 
2187                                 sy= (sima->curtile / sima->image->xrep);
2188                                 sx= sima->curtile - sy*sima->image->xrep;
2189                 
2190                                 sx*= dx;
2191                                 sy*= dy;
2192                                 
2193                                 /* create char buffer from float if needed */
2194                                 if(ibuf->rect_float && ibuf->rect==NULL)
2195                                         IMB_rect_from_float(ibuf);
2196
2197                                 rect= get_part_from_ibuf(ibuf, sx, sy, sx+dx, sy+dy);
2198                                 
2199                                 /* rect= ibuf->rect; */
2200                                 for(sy= 0; sy+dy<=ibuf->y; sy+= dy) {
2201                                         for(sx= 0; sx+dx<=ibuf->x; sx+= dx) {
2202                                                 glaDrawPixelsSafe(x1+sx*sima->zoom, y1+sy*sima->zoom, dx, dy, dx, GL_RGBA, GL_UNSIGNED_BYTE, rect);
2203                                         }
2204                                 }
2205                                 
2206                                 MEM_freeN(rect);
2207                         }
2208                         else {
2209                                 float x1_rep, y1_rep;
2210                                 int x_rep, y_rep;
2211                                 double time_current;
2212                                 short loop_draw_ok = 0;
2213                                 
2214                                 if (sima->flag & SI_DRAW_TILE) {
2215                                         loop_draw_ok= 1;
2216                                 }
2217                                 
2218                                 time_current = PIL_check_seconds_timer();
2219                                 
2220                                 for (x_rep= ((int)G.v2d->cur.xmin)-1; x_rep < G.v2d->cur.xmax; x_rep++) {
2221                                         x1_rep=x1+  ((x_rep* ibuf->x * sima->zoom)  *xuser_asp);
2222                                         for (y_rep= ((int)G.v2d->cur.ymin)-1; y_rep < G.v2d->cur.ymax; y_rep++) {
2223                                                 y1_rep=y1+  ((y_rep * ibuf->y *sima->zoom)  *yuser_asp);
2224                                 
2225                                 /* end repeating image loop */
2226                                                 
2227                                                 if(!loop_draw_ok) {
2228                                                         y1_rep = y1;
2229                                                         x1_rep = x1;
2230                                                 }
2231                                                 
2232                                                 /*printf("Drawing %d %d zoom:%.6f (%.6f %.6f), (%.6f %.6f)\n", x_rep, y_rep, sima->zoom, G.v2d->cur.xmin, G.v2d->cur.ymin, G.v2d->cur.xmax, G.v2d->cur.ymax);*/
2233                                                 
2234                                                 /* this part is generic image display */
2235                                                 if(sima->flag & SI_SHOW_ALPHA) {
2236                                                         if(ibuf->rect)
2237                                                                 sima_draw_alpha_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->rect);
2238                                                         else if(ibuf->rect_float && ibuf->channels==4)
2239                                                                 sima_draw_alpha_pixelsf(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->rect_float);
2240                                                 }
2241                                                 else if(sima->flag & SI_SHOW_ZBUF && (ibuf->zbuf || ibuf->zbuf_float || (ibuf->channels==1))) {
2242                                                         if(ibuf->zbuf)
2243                                                                 sima_draw_zbuf_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->zbuf);
2244                                                         else if(ibuf->zbuf_float)
2245                                                                 sima_draw_zbuffloat_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->zbuf_float);
2246                                                         else if(ibuf->channels==1)
2247                                                                 sima_draw_zbuffloat_pixels(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->rect_float);
2248                                                 }
2249                                                 else {
2250                                                         if(sima->flag & SI_USE_ALPHA) {
2251                                                                 sima_draw_alpha_backdrop(sima, x1_rep, y1_rep, ibuf->x*xuser_asp, ibuf->y*yuser_asp);
2252                                                                 glEnable(GL_BLEND);
2253                                                                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
2254                                                         }
2255                                                         
2256                                                         /* detect if we need to redo the curve map. 
2257                                                            ibuf->rect is zero for compositor and render results after change 
2258                                                            convert to 32 bits always... drawing float rects isnt supported well (atis)
2259                                                         
2260                                                            NOTE: if float buffer changes, we have to manually remove the rect
2261                                                         */
2262                                                         
2263                                                         if(ibuf->rect_float) {
2264                                                                 if(ibuf->rect==NULL) {
2265                                                                         if(image_curves_active(sa))
2266                                                                                 curvemapping_do_ibuf(G.sima->cumap, ibuf);
2267                                                                         else 
2268                                                                                 IMB_rect_from_float(ibuf);
2269                                                                 }
2270                                                         }
2271                 
2272                                                         if(ibuf->rect)
2273                                                                 glaDrawPixelsSafe(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
2274                 //                                      else
2275                 //                                              glaDrawPixelsSafe(x1_rep, y1_rep, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_FLOAT, ibuf->rect_float);
2276                                                         
2277                                                         if(sima->flag & SI_USE_ALPHA)
2278                                                                 glDisable(GL_BLEND);
2279                                                 }
2280                                                 
2281                                                 /* only draw once */
2282                                                 if(!loop_draw_ok) {
2283                                                         break; /* only draw once */
2284                                                 } else if ((PIL_check_seconds_timer() - time_current) > 0.25) {
2285                                                         loop_draw_ok = 0;
2286                                                         break;
2287                                                 }
2288                                 
2289                                 /* tile draw loop */
2290                                         }
2291                                         /* only draw once */
2292                                         if(!loop_draw_ok) break;
2293                                 }
2294                                 /* tile draw loop */
2295                                 
2296                         }
2297                         
2298                         brush= G.scene->toolsettings->imapaint.brush;
2299                         if(brush && (G.scene->toolsettings->imapaint.tool == PAINT_TOOL_CLONE)) {
2300                                 int w, h;
2301                                 unsigned char *clonerect;
2302
2303                                 /* this is not very efficient, but glDrawPixels doesn't allow
2304                                    drawing with alpha */
2305                                 clonerect= alloc_alpha_clone_image(&w, &h);
2306
2307                                 if(clonerect) {
2308                                         int offx, offy;
2309                                         offx = sima->zoom*ibuf->x * + brush->clone.offset[0];
2310                                         offy = sima->zoom*ibuf->y * + brush->clone.offset[1];
2311
2312                                         glEnable(GL_BLEND);
2313                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2314                                         glaDrawPixelsSafe(x1 + offx, y1 + offy, w, h, w, GL_RGBA, GL_UNSIGNED_BYTE, clonerect);
2315                                         glDisable(GL_BLEND);
2316
2317                                         MEM_freeN(clonerect);
2318                                 }
2319                         }
2320                         
2321                         glPixelZoom(1.0, 1.0);
2322                         
2323                         if(show_viewer==0) { 
2324                                 draw_uvs_sima();
2325                                 drawcursor_sima(xuser_asp, yuser_asp);
2326                         }
2327                 }
2328
2329                 glPixelZoom(1.0, 1.0);
2330
2331                 calc_image_view(sima, 'f');     /* float */
2332         }
2333
2334         draw_image_transform(ibuf, xuser_asp, yuser_asp);
2335
2336         mywinset(sa->win);      /* restore scissor after gla call... */
2337         myortho2(-0.375, sa->winx-0.375, -0.375, sa->winy-0.375);
2338
2339         if(G.rendering==0) {
2340                 draw_image_view_tool();
2341         }
2342         draw_area_emboss(sa);
2343
2344         /* it is important to end a view in a transform compatible with buttons */
2345         bwin_scalematrix(sa->win, sima->blockscale, sima->blockscale, sima->blockscale);
2346         if(!(G.rendering && show_render))
2347                 image_blockhandlers(sa);
2348
2349         sa->win_swap= WIN_BACK_OK;
2350 }
2351
2352 static void image_zoom_set_factor(float zoomfac)
2353 {
2354         SpaceImage *sima= curarea->spacedata.first;
2355         int width, height;
2356
2357         if (zoomfac <= 0.0f)
2358                 return;
2359
2360         sima->zoom *= zoomfac;
2361
2362         if (sima->zoom > 0.1f && sima->zoom < 4.0f)
2363                 return;
2364
2365         /* check zoom limits */
2366
2367         calc_image_view(G.sima, 'f'); /* was 'p' are there any cases where this should be 'p'?*/
2368         width= 256;
2369         height= 256;
2370         if (sima->image) {
2371                 ImBuf *ibuf= imagewindow_get_ibuf(sima);
2372
2373                 if (ibuf) {
2374                         float xim, yim;
2375                         /* I know a bit weak... but preview uses not actual image size */
2376                         if(image_preview_active(curarea, &xim, &yim)) {
2377                                 width= (int) xim;
2378                                 height= (int) yim;
2379                         }
2380                         else {
2381                                 width= ibuf->x;
2382                                 height= ibuf->y;
2383                         }
2384                 }
2385         }
2386         width *= sima->zoom;
2387         height *= sima->zoom;
2388
2389         if ((width < 4) && (height < 4))
2390                 sima->zoom /= zoomfac;
2391         else if((curarea->winrct.xmax - curarea->winrct.xmin) <= sima->zoom)
2392                 sima->zoom /= zoomfac;
2393         else if((curarea->winrct.ymax - curarea->winrct.ymin) <= sima->zoom)
2394                 sima->zoom /= zoomfac;
2395 }
2396
2397 void image_viewmove(int mode)
2398 {
2399         short mval[2], mvalo[2], zoom0;
2400         int oldcursor;
2401         Window *win;
2402         
2403         getmouseco_sc(mvalo);
2404         zoom0= G.sima->zoom;
2405         
2406         oldcursor=get_cursor();
2407         win=winlay_get_active_window();
2408         
2409         SetBlenderCursor(BC_NSEW_SCROLLCURSOR);
2410         
2411         while(get_mbut()&(L_MOUSE|M_MOUSE)) {
2412
2413                 getmouseco_sc(mval);
2414
2415                 if(mvalo[0]!=mval[0] || mvalo[1]!=mval[1]) {
2416                 
2417                         if(mode==0) {
2418                                 G.sima->xof += (mvalo[0]-mval[0])/G.sima->zoom;
2419                                 G.sima->yof += (mvalo[1]-mval[1])/G.sima->zoom;
2420                         }
2421                         else if (mode==1) {
2422                                 float factor;
2423
2424                                 factor= 1.0+(float)(mvalo[0]-mval[0]+mvalo[1]-mval[1])/300.0;
2425                                 image_zoom_set_factor(factor);
2426                         }
2427
2428                         mvalo[0]= mval[0];
2429                         mvalo[1]= mval[1];
2430                         
2431                         scrarea_do_windraw(curarea);
2432                         screen_swapbuffers();
2433                 }
2434                 else BIF_wait_for_statechange();
2435         }
2436         window_set_cursor(win, oldcursor);
2437         
2438         if(image_preview_active(curarea, NULL, NULL)) {
2439                 /* recalculates new preview rect */
2440                 scrarea_do_windraw(curarea);
2441                 image_preview_event(2);
2442         }
2443 }
2444
2445 void image_viewzoom(unsigned short event, int invert)
2446 {
2447         SpaceImage *sima= curarea->spacedata.first;
2448
2449         if(event==WHEELDOWNMOUSE || event==PADMINUS)
2450                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 1.25: 0.8);
2451         else if(event==WHEELUPMOUSE || event==PADPLUSKEY)
2452                 image_zoom_set_factor((U.uiflag & USER_WHEELZOOMDIR)? 0.8: 1.25);
2453         else if(event==PAD1)
2454                 sima->zoom= 1.0;
2455         else if(event==PAD2)
2456                 sima->zoom= (invert)? 2.0: 0.5;
2457         else if(event==PAD4)
2458                 sima->zoom= (invert)? 4.0: 0.25;
2459         else if(event==PAD8)
2460                 sima->zoom= (invert)? 8.0: 0.125;
2461         
2462         /* ensure pixel exact locations for draw */
2463         sima->xof= (int)sima->xof;
2464         sima->yof= (int)sima->yof;
2465         
2466         if(image_preview_active(curarea, NULL, NULL)) {
2467                 /* recalculates new preview rect */
2468                 scrarea_do_windraw(curarea);
2469                 image_preview_event(2);
2470         }
2471 }
2472
2473 /**
2474  * Updates the fields of the View2D member of the SpaceImage struct.
2475  * Default behavior is to reset the position of the image and set the zoom to 1
2476  * If the image will not fit within the window rectangle, the zoom is adjusted
2477  *
2478  * @return    void
2479  *   
2480  */
2481 void image_home(void)
2482 {
2483         ImBuf *ibuf;
2484         int width, height, imgwidth, imgheight;
2485         float zoomX, zoomY;
2486
2487         if (curarea->spacetype != SPACE_IMAGE) return;
2488         ibuf= imagewindow_get_ibuf(G.sima);
2489         
2490         if (ibuf == NULL) {
2491                 imgwidth = 256;
2492                 imgheight = 256;
2493         }
2494         else {
2495                 float xuser_asp, yuser_asp;
2496                 image_pixel_aspect(G.sima->image, &xuser_asp, &yuser_asp);
2497                 imgwidth = ibuf->x * xuser_asp;
2498                 imgheight = ibuf->y * yuser_asp;
2499         }
2500
2501         /* Check if the image will fit in the image with zoom==1 */
2502         width = curarea->winx;
2503         height = curarea->winy;
2504         if (((imgwidth >= width) || (imgheight >= height)) && 
2505                 ((width > 0) && (height > 0))) {
2506                 /* Find the zoom value that will fit the image in the image space */
2507                 zoomX = ((float)width) / ((float)imgwidth);
2508                 zoomY = ((float)height) / ((float)imgheight);
2509                 G.sima->zoom = 1.0f / power_of_2(1/ MIN2(zoomX, zoomY) );
2510         }
2511         else {
2512                 G.sima->zoom= 1.0f;
2513         }
2514
2515         G.sima->xof= G.sima->yof= 0.0f;
2516         
2517         calc_image_view(G.sima, 'f'); /* was 'p' are there any cases where this should be 'p'?*/
2518         /*calc_arearcts(curarea);*/
2519         scrarea_queue_winredraw(curarea);
2520         scrarea_queue_winredraw(curarea);
2521 }
2522
2523 void image_viewcenter(void)
2524 {
2525         ImBuf *ibuf= imagewindow_get_ibuf(G.sima);
2526         float size, min[2], max[2], d[2], xim=256.0f, yim=256.0f;
2527
2528         if( is_uv_tface_editing_allowed()==0 ) return;
2529
2530         if (!minmax_tface_uv(min, max)) return;
2531
2532         if(ibuf) {
2533                 xim= ibuf->x;
2534                 yim= ibuf->y;
2535         }
2536
2537         G.sima->xof= (int) (((min[0] + max[0])*0.5f - 0.5f)*xim);
2538         G.sima->yof= (int) (((min[1] + max[1])*0.5f - 0.5f)*yim);
2539
2540         d[0] = max[0] - min[0];
2541         d[1] = max[1] - min[1];
2542         size= 0.5*MAX2(d[0], d[1])*MAX2(xim, yim)/256.0f;
2543         
2544         if(size<=0.01) size= 0.01;
2545
2546         G.sima->zoom= 0.7/size;
2547
2548         calc_image_view(G.sima, 'f'); /* was 'p' are there any cases where 'p' is still needed? */
2549
2550         scrarea_queue_winredraw(curarea);
2551 }
2552
2553
2554 /* *********************** render callbacks ***************** */
2555
2556 /* set on initialize render, only one render output to imagewindow can exist, so the global isnt dangerous yet :) */
2557 static ScrArea *image_area= NULL;
2558
2559 /* can get as well the full picture, as the parts while rendering */
2560 static void imagewindow_progress(ScrArea *sa, RenderResult *rr, volatile rcti *renrect)
2561 {
2562         SpaceImage *sima= sa->spacedata.first;
2563         float x1, y1, *rectf= NULL;
2564         unsigned int *rect32= NULL;
2565         int ymin, ymax, xmin, xmax;
2566         
2567         /* if renrect argument, we only display scanlines */
2568         if(renrect) {
2569                 /* if ymax==recty, rendering of layer is ready, we should not draw, other things happen... */
2570                 if(rr->renlay==NULL || renrect->ymax>=rr->recty)
2571                         return;
2572                 
2573                 /* xmin here is first subrect x coord, xmax defines subrect width */
2574                 xmin = renrect->xmin;
2575                 xmax = renrect->xmax - xmin;
2576                 if (xmax<2) return;
2577                 
2578                 ymin= renrect->ymin;
2579                 ymax= renrect->ymax - ymin;
2580                 if(ymax<2)
2581                         return;
2582                 renrect->ymin= renrect->ymax;
2583         }
2584         else {
2585                 xmin = ymin = 0;
2586                 xmax = rr->rectx - 2*rr->crop;
2587                 ymax = rr->recty - 2*rr->crop;
2588         }
2589         
2590         /* image window cruft */
2591         
2592         /* find current float rect for display, first case is after composit... still weak */
2593         if(rr->rectf)
2594                 rectf= rr->rectf;
2595         else {
2596                 if(rr->rect32)
2597                         rect32= (unsigned int *)rr->rect32;
2598                 else {
2599                         if(rr->renlay==NULL || rr->renlay->rectf==NULL) return;
2600                         rectf= rr->renlay->rectf;
2601                 }
2602         }
2603         if(rectf) {
2604                 /* if scanline updates... */
2605                 rectf+= 4*(rr->rectx*ymin + xmin);
2606                 
2607                 /* when rendering more pixels than needed, we crop away cruft */
2608                 if(rr->crop)
2609                         rectf+= 4*(rr->crop*rr->rectx + rr->crop);
2610         }
2611         
2612         /* tilerect defines drawing offset from (0,0) */
2613         /* however, tilerect (xmin, ymin) is first pixel */
2614         x1 = sima->centx + (rr->tilerect.xmin + rr->crop + xmin)*sima->zoom;
2615         y1 = sima->centy + (rr->tilerect.ymin + rr->crop + ymin)*sima->zoom;
2616         
2617         /* needed for gla draw */
2618         { rcti rct= sa->winrct; rct.ymax-= RW_HEADERY; glaDefine2DArea(&rct);}
2619
2620         glPixelZoom(sima->zoom, sima->zoom);
2621         
2622         if(rect32)
2623                 glaDrawPixelsSafe(x1, y1, xmax, ymax, rr->rectx, GL_RGBA, GL_UNSIGNED_BYTE, rect32);
2624         else
2625                 glaDrawPixelsSafe_to32(x1, y1, xmax, ymax, rr->rectx, rectf);
2626         
2627         glPixelZoom(1.0, 1.0);
2628         
2629 }
2630
2631
2632 /* in render window; display a couple of scanlines of rendered image */
2633 /* NOTE: called while render, so no malloc allowed! */
2634 static void imagewindow_progress_display_cb(RenderResult *rr, volatile rcti *rect)
2635 {
2636         
2637         if (image_area) {
2638                 
2639                 imagewindow_progress(image_area, rr, rect);
2640
2641                 /* no screen_swapbuffers, prevent any other window to draw */
2642                 myswapbuffers();
2643         }
2644 }
2645
2646 /* unused, init_display_cb is called on each render */
2647 static void imagewindow_clear_display_cb(RenderResult *rr)
2648 {
2649         if (image_area) {
2650         }
2651 }
2652
2653 /* returns biggest area that is not uv/image editor. Note that it uses buttons */
2654 /* window as the last possible alternative.                                                                        */
2655 static ScrArea *biggest_non_image_area(void)
2656 {
2657         ScrArea *sa, *big= NULL;
2658         int size, maxsize= 0, bwmaxsize= 0;
2659         short foundwin= 0;
2660         
2661         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2662                 if(sa->winx > 10 && sa->winy > 10) {
2663                         size= sa->winx*sa->winy;
2664                         if(sa->spacetype == SPACE_BUTS) {
2665                                 if(foundwin == 0 && size > bwmaxsize) {
2666                                         bwmaxsize= size;
2667                                         big= sa;        
2668                                 }
2669                         }
2670                         else if(sa->spacetype != SPACE_IMAGE && size > maxsize) {
2671                                 maxsize= size;
2672                                 big= sa;
2673                                 foundwin= 1;
2674                         }
2675                 }
2676         }
2677                 
2678         return big;
2679 }
2680
2681 static ScrArea *biggest_area(void)
2682 {
2683         ScrArea *sa, *big= NULL;
2684         int size, maxsize= 0;
2685         
2686         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2687                 size= sa->winx*sa->winy;
2688                 if(size > maxsize) {
2689                         maxsize= size;
2690                         big= sa;
2691                 }
2692         }
2693         return big;
2694 }
2695
2696
2697 /* if R_DISPLAYIMAGE
2698       use Image Window showing Render Result
2699           else: turn largest non-image area into Image Window (not to frustrate texture or composite usage)
2700           else: then we use Image Window anyway...
2701    if R_DISPSCREEN
2702       make a new temp fullscreen area with Image Window
2703 */
2704
2705 static ScrArea *find_area_showing_r_result(void)
2706 {
2707         ScrArea *sa;
2708         SpaceImage *sima;
2709         
2710         /* find an imagewindow showing render result */
2711         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2712                 if(sa->spacetype==SPACE_IMAGE) {
2713                         sima= sa->spacedata.first;
2714                         if(sima->image && sima->image->type==IMA_TYPE_R_RESULT)
2715                                 break;
2716                 }
2717         }
2718         return sa;
2719 }
2720
2721 static ScrArea *imagewindow_set_render_display(void)
2722 {
2723         ScrArea *sa;
2724         SpaceImage *sima;
2725         
2726         sa= find_area_showing_r_result();
2727         
2728         if(sa==NULL) {
2729                 /* find largest open non-image area */
2730                 sa= biggest_non_image_area();
2731                 if(sa) {
2732                         newspace(sa, SPACE_IMAGE);
2733                         sima= sa->spacedata.first;
2734                         
2735                         /* makes ESC go back to prev space */
2736                         sima->flag |= SI_PREVSPACE;
2737                 }
2738                 else {
2739                         /* use any area of decent size */
2740                         sa= biggest_area();
2741                         if(sa->spacetype!=SPACE_IMAGE) {
2742                                 newspace(sa, SPACE_IMAGE);
2743                                 sima= sa->spacedata.first;
2744                                 
2745                                 /* makes ESC go back to prev space */
2746                                 sima->flag |= SI_PREVSPACE;
2747                         }
2748                 }
2749         }
2750         
2751         sima= sa->spacedata.first;
2752         
2753         /* get the correct image, and scale it */
2754         sima->image= BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
2755         
2756         if(G.displaymode==R_DISPLAYSCREEN) {
2757                 if(sa->full==0) {
2758                         sima->flag |= SI_FULLWINDOW;
2759                         /* fullscreen works with lousy curarea */
2760                         curarea= sa;
2761                         area_fullscreen();
2762                         sa= curarea;
2763                 }
2764         }
2765         
2766         return sa;
2767 }
2768
2769 static void imagewindow_init_display_cb(RenderResult *rr)
2770 {
2771         
2772         image_area= imagewindow_set_render_display();
2773         
2774         if(image_area) {
2775                 SpaceImage *sima= image_area->spacedata.first;
2776                 
2777                 areawinset(image_area->win);
2778                 
2779                 /* calc location using original size (tiles don't tell) */
2780                 sima->centx= (image_area->winx - sima->zoom*(float)rr->rectx)/2.0f;
2781                 sima->centy= (image_area->winy - sima->zoom*(float)rr->recty)/2.0f;
2782                 
2783                 sima->centx-= sima->zoom*sima->xof;
2784                 sima->centy-= sima->zoom*sima->yof;
2785                 
2786                 drawimagespace(image_area, sima);
2787                 if(image_area->headertype) scrarea_do_headdraw(image_area);
2788
2789                 /* no screen_swapbuffers, prevent any other window to draw */
2790                 myswapbuffers();
2791                 
2792                 allqueue(REDRAWIMAGE, 0);       /* redraw in end */
2793         }
2794 }
2795
2796 /* coming from BIF_toggle_render_display() */
2797 void imagewindow_toggle_render(void)
2798 {
2799         ScrArea *sa;
2800         
2801         /* check if any imagewindow is showing temporal render output */
2802         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
2803                 if(sa->spacetype==SPACE_IMAGE) {
2804                         SpaceImage *sima= sa->spacedata.first;
2805                         
2806                         if(sima->image && sima->image->type==IMA_TYPE_R_RESULT)
2807                                 if(sima->flag & (SI_PREVSPACE|SI_FULLWINDOW))
2808                                         break;
2809                 }
2810         }
2811         if(sa) {
2812                 addqueue(sa->win, ESCKEY, 1);   /* also returns from fullscreen */
2813         }
2814         else {
2815                 sa= imagewindow_set_render_display();
2816                 scrarea_queue_headredraw(sa);
2817                 scrarea_queue_winredraw(sa);
2818         }
2819 }
2820
2821 /* NOTE: called while render, so no malloc allowed! */
2822 static void imagewindow_renderinfo_cb(RenderStats *rs)
2823 {
2824         
2825         if(image_area) {
2826                 BIF_make_render_text(rs);
2827
2828                 imagewindow_draw_renderinfo(image_area);
2829                 
2830                 /* no screen_swapbuffers, prevent any other window to draw */
2831                 myswapbuffers();
2832         }
2833 }
2834
2835 void imagewindow_render_callbacks(Render *re)
2836 {
2837         RE_display_init_cb(re, imagewindow_init_display_cb);
2838         RE_display_draw_cb(re, imagewindow_progress_display_cb);
2839         RE_display_clear_cb(re, imagewindow_clear_display_cb);
2840         RE_stats_draw_cb(re, imagewindow_renderinfo_cb);        
2841 }
2842