image format arg parsing for creator.c
[blender.git] / source / blender / blenkernel / intern / image.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2006, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/image.c
27  *  \ingroup bke
28  */
29
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #ifndef WIN32 
36 #include <unistd.h>
37 #else
38 #include <io.h>
39 #endif
40
41 #include <time.h>
42
43 #ifdef _WIN32
44 #define open _open
45 #define close _close
46 #endif
47
48 #include "MEM_guardedalloc.h"
49
50 #include "IMB_imbuf_types.h"
51 #include "IMB_imbuf.h"
52
53 #ifdef WITH_OPENEXR
54 #include "intern/openexr/openexr_multi.h"
55 #endif
56
57 #include "DNA_packedFile_types.h"
58 #include "DNA_scene_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_camera_types.h"
61 #include "DNA_sequence_types.h"
62 #include "DNA_userdef_types.h"
63 #include "DNA_brush_types.h"
64 #include "DNA_mesh_types.h"
65 #include "DNA_meshdata_types.h"
66
67 #include "BLI_blenlib.h"
68 #include "BLI_threads.h"
69 #include "BLI_utildefines.h"
70 #include "BLI_bpath.h"
71
72 #include "BKE_bmfont.h"
73 #include "BKE_global.h"
74 #include "BKE_icons.h"
75 #include "BKE_image.h"
76 #include "BKE_library.h"
77 #include "BKE_main.h"
78 #include "BKE_packedFile.h"
79 #include "BKE_scene.h"
80 #include "BKE_node.h"
81 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
82 #include "BKE_utildefines.h"
83
84 #include "BLF_api.h"
85
86 #include "PIL_time.h"
87
88 #include "RE_pipeline.h"
89
90 #include "GPU_draw.h"
91
92 #include "BLO_sys_types.h" // for intptr_t support
93
94 /* max int, to indicate we don't store sequences in ibuf */
95 #define IMA_NO_INDEX    0x7FEFEFEF
96
97 /* quick lookup: supports 1 million frames, thousand passes */
98 #define IMA_MAKE_INDEX(frame, index)    ((frame)<<10)+index
99 #define IMA_INDEX_FRAME(index)                  (index>>10)
100 #define IMA_INDEX_PASS(index)                   (index & ~1023)
101
102 /* ******** IMAGE PROCESSING ************* */
103
104 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
105 {
106         struct ImBuf * tbuf1, * tbuf2;
107         
108         if (ibuf == NULL) return;
109         if (ibuf->flags & IB_fields) return;
110         ibuf->flags |= IB_fields;
111         
112         if (ibuf->rect) {
113                 /* make copies */
114                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
115                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
116                 
117                 ibuf->x *= 2;
118                 
119                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
120                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
121                 
122                 ibuf->x /= 2;
123                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
124                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
125                 
126                 IMB_freeImBuf(tbuf1);
127                 IMB_freeImBuf(tbuf2);
128         }
129         ibuf->y /= 2;
130 }
131
132 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
133 {
134         struct ImBuf * tbuf1, * tbuf2;
135         
136         if (ibuf == NULL) return;
137         if (ibuf->flags & IB_fields) return;
138         ibuf->flags |= IB_fields;
139         
140         if (ibuf->rect) {
141                 /* make copies */
142                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
143                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
144                 
145                 ibuf->x *= 2;
146                 
147                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
148                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
149                 
150                 ibuf->x /= 2;
151                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
152                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
153                 
154                 IMB_freeImBuf(tbuf1);
155                 IMB_freeImBuf(tbuf2);
156         }
157         ibuf->y /= 2;
158 }
159
160 void image_de_interlace(Image *ima, int odd)
161 {
162         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
163         if(ibuf) {
164                 if(odd)
165                         de_interlace_st(ibuf);
166                 else
167                         de_interlace_ng(ibuf);
168         }
169 }
170
171 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
172
173 static void image_free_buffers(Image *ima)
174 {
175         ImBuf *ibuf;
176         
177         while((ibuf = ima->ibufs.first)) {
178                 BLI_remlink(&ima->ibufs, ibuf);
179                 
180                 if (ibuf->userdata) {
181                         MEM_freeN(ibuf->userdata);
182                         ibuf->userdata = NULL;
183                 }
184                 IMB_freeImBuf(ibuf);
185         }
186         
187         if(ima->anim) IMB_free_anim(ima->anim);
188         ima->anim= NULL;
189
190         if(ima->rr) {
191                 RE_FreeRenderResult(ima->rr);
192                 ima->rr= NULL;
193         }       
194         
195         GPU_free_image(ima);
196         
197         ima->ok= IMA_OK;
198 }
199
200 /* called by library too, do not free ima itself */
201 void free_image(Image *ima)
202 {
203         int a;
204
205         image_free_buffers(ima);
206         if (ima->packedfile) {
207                 freePackedFile(ima->packedfile);
208                 ima->packedfile = NULL;
209         }
210         BKE_icon_delete(&ima->id);
211         ima->id.icon_id = 0;
212
213         BKE_previewimg_free(&ima->preview);
214
215         for(a=0; a<IMA_MAX_RENDER_SLOT; a++) {
216                 if(ima->renders[a]) {
217                         RE_FreeRenderResult(ima->renders[a]);
218                         ima->renders[a]= NULL;
219                 }
220         }
221 }
222
223 /* only image block itself */
224 static Image *image_alloc(const char *name, short source, short type)
225 {
226         Image *ima;
227         
228         ima= alloc_libblock(&G.main->image, ID_IM, name);
229         if(ima) {
230                 ima->ok= IMA_OK;
231                 
232                 ima->xrep= ima->yrep= 1;
233                 ima->aspx= ima->aspy= 1.0;
234                 ima->gen_x= 1024; ima->gen_y= 1024;
235                 ima->gen_type= 1;       /* no defines yet? */
236                 
237                 ima->source= source;
238                 ima->type= type;
239         }
240         return ima;
241 }
242
243 /* get the ibuf from an image cache, local use here only */
244 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
245 {
246         /* this function is intended to be thread safe. with IMA_NO_INDEX this
247          * should be OK, but when iterating over the list this is more tricky
248          * */
249         if(index==IMA_NO_INDEX)
250                 return ima->ibufs.first;
251         else {
252                 ImBuf *ibuf;
253
254                 index= IMA_MAKE_INDEX(frame, index);
255                 for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
256                         if(ibuf->index==index)
257                                 return ibuf;
258
259                 return NULL;
260         }
261 }
262
263 /* no ima->ibuf anymore, but listbase */
264 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
265 {
266         if(ibuf) {
267                 BLI_remlink(&ima->ibufs, ibuf);
268                 IMB_freeImBuf(ibuf);
269         }
270 }
271
272
273 /* no ima->ibuf anymore, but listbase */
274 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
275 {
276         if(ibuf) {
277                 ImBuf *link;
278                 
279                 if(index!=IMA_NO_INDEX)
280                         index= IMA_MAKE_INDEX(frame, index);
281                 
282                 /* insert based on index */
283                 for(link= ima->ibufs.first; link; link= link->next)
284                         if(link->index>=index)
285                                 break;
286
287                 ibuf->index= index;
288
289                 /* this function accepts link==NULL */
290                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
291
292                 /* now we don't want copies? */
293                 if(link && ibuf->index==link->index)
294                         image_remove_ibuf(ima, link);
295         }
296 }
297
298 /* empty image block, of similar type and filename */
299 Image *copy_image(Image *ima)
300 {
301         Image *nima= image_alloc(ima->id.name+2, ima->source, ima->type);
302
303         BLI_strncpy(nima->name, ima->name, sizeof(ima->name));
304
305         nima->flag= ima->flag;
306         nima->tpageflag= ima->tpageflag;
307         
308         nima->gen_x= ima->gen_x;
309         nima->gen_y= ima->gen_y;
310         nima->gen_type= ima->gen_type;
311
312         nima->animspeed= ima->animspeed;
313
314         nima->aspx= ima->aspx;
315         nima->aspy= ima->aspy;
316
317         return nima;
318 }
319
320 static void extern_local_image(Image *UNUSED(ima))
321 {
322         /* Nothing to do: images don't link to other IDs. This function exists to
323            match id_make_local pattern. */
324 }
325
326 void make_local_image(struct Image *ima)
327 {
328         Main *bmain= G.main;
329         Tex *tex;
330         Brush *brush;
331         Mesh *me;
332         int is_local= FALSE, is_lib= FALSE;
333
334         /* - only lib users: do nothing
335          * - only local users: set flag
336          * - mixed: make copy
337          */
338
339         if(ima->id.lib==NULL) return;
340
341         /* Can't take short cut here: must check meshes at least because of bogus
342            texface ID refs. - z0r */
343 #if 0
344         if(ima->id.us==1) {
345                 id_clear_lib_data(bmain, &ima->id);
346                 extern_local_image(ima);
347                 return;
348         }
349 #endif
350
351         for(tex= bmain->tex.first; tex; tex= tex->id.next) {
352                 if(tex->ima == ima) {
353                         if(tex->id.lib) is_lib= TRUE;
354                         else is_local= TRUE;
355                 }
356         }
357         for(brush= bmain->brush.first; brush; brush= brush->id.next) {
358                 if(brush->clone.image == ima) {
359                         if(brush->id.lib) is_lib= TRUE;
360                         else is_local= TRUE;
361                 }
362         }
363         for(me= bmain->mesh.first; me; me= me->id.next) {
364                 if(me->mtface) {
365                         MTFace *tface;
366                         int a, i;
367
368                         for(i=0; i<me->fdata.totlayer; i++) {
369                                 if(me->fdata.layers[i].type == CD_MTFACE) {
370                                         tface= (MTFace*)me->fdata.layers[i].data;
371
372                                         for(a=0; a<me->totface; a++, tface++) {
373                                                 if(tface->tpage == ima) {
374                                                         if(me->id.lib) is_lib= TRUE;
375                                                         else is_local= TRUE;
376                                                 }
377                                         }
378                                 }
379                         }
380                 }
381         }
382
383         if(is_local && is_lib == FALSE) {
384                 id_clear_lib_data(bmain, &ima->id);
385                 extern_local_image(ima);
386         }
387         else if(is_local && is_lib) {
388                 Image *iman= copy_image(ima);
389
390                 iman->id.us= 0;
391
392                 /* Remap paths of new ID using old library as base. */
393                 BKE_id_lib_local_paths(bmain, &iman->id);
394
395                 tex= bmain->tex.first;
396                 while(tex) {
397                         if(tex->id.lib==NULL) {
398                                 if(tex->ima==ima) {
399                                         tex->ima = iman;
400                                         iman->id.us++;
401                                         ima->id.us--;
402                                 }
403                         }
404                         tex= tex->id.next;
405                 }
406                 brush= bmain->brush.first;
407                 while(brush) {
408                         if(brush->id.lib==NULL) {
409                                 if(brush->clone.image==ima) {
410                                         brush->clone.image = iman;
411                                         iman->id.us++;
412                                         ima->id.us--;
413                                 }
414                         }
415                         brush= brush->id.next;
416                 }
417                 /* Transfer references in texfaces. Texfaces don't add to image ID
418                    user count *unless* there are no other users. See
419                    readfile.c:lib_link_mtface. */
420                 me= bmain->mesh.first;
421                 while(me) {
422                         if(me->mtface) {
423                                 MTFace *tface;
424                                 int a, i;
425
426                                 for(i=0; i<me->fdata.totlayer; i++) {
427                                         if(me->fdata.layers[i].type == CD_MTFACE) {
428                                                 tface= (MTFace*)me->fdata.layers[i].data;
429
430                                                 for(a=0; a<me->totface; a++, tface++) { 
431                                                         if(tface->tpage == ima) {
432                                                                 tface->tpage = iman;
433                                                                 if(iman->id.us == 0) {
434                                                                         tface->tpage->id.us= 1;
435                                                                 }
436                                                                 id_lib_extern((ID*)iman);
437                                                         }
438                                                 }
439                                         }
440                                 }
441                         }
442                         me= me->id.next;
443                 }
444         }
445 }
446
447 void BKE_image_merge(Image *dest, Image *source)
448 {
449         ImBuf *ibuf;
450         
451         /* sanity check */
452         if(dest && source && dest!=source) {
453         
454                 while((ibuf= source->ibufs.first)) {
455                         BLI_remlink(&source->ibufs, ibuf);
456                         image_assign_ibuf(dest, ibuf, IMA_INDEX_PASS(ibuf->index), IMA_INDEX_FRAME(ibuf->index));
457                 }
458                 
459                 free_libblock(&G.main->image, source);
460         }
461 }
462
463
464 /* checks if image was already loaded, then returns same image */
465 /* otherwise creates new. */
466 /* does not load ibuf itself */
467 /* pass on optional frame for #name images */
468 Image *BKE_add_image_file(const char *name)
469 {
470         Image *ima;
471         int file, len;
472         const char *libname;
473         char str[FILE_MAX], strtest[FILE_MAX];
474         
475         BLI_strncpy(str, name, sizeof(str));
476         BLI_path_abs(str, G.main->name);
477         
478         /* exists? */
479         file= open(str, O_BINARY|O_RDONLY);
480         if(file== -1) return NULL;
481         close(file);
482         
483         /* first search an identical image */
484         for(ima= G.main->image.first; ima; ima= ima->id.next) {
485                 if(ima->source!=IMA_SRC_VIEWER && ima->source!=IMA_SRC_GENERATED) {
486                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
487                         BLI_path_abs(strtest, G.main->name);
488                         
489                         if( strcmp(strtest, str)==0 ) {
490                                 if(ima->anim==NULL || ima->id.us==0) {
491                                         BLI_strncpy(ima->name, name, sizeof(ima->name));        /* for stringcode */
492                                         ima->id.us++;                                                                           /* officially should not, it doesn't link here! */
493                                         if(ima->ok==0)
494                                                 ima->ok= IMA_OK;
495                         /* RETURN! */
496                                         return ima;
497                                 }
498                         }
499                 }
500         }
501         /* add new image */
502         
503         /* create a short library name */
504         len= strlen(name);
505         
506         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
507         libname= name+len;
508         
509         ima= image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
510         BLI_strncpy(ima->name, name, sizeof(ima->name));
511         
512         if(BLI_testextensie_array(name, imb_ext_movie))
513                 ima->source= IMA_SRC_MOVIE;
514         
515         return ima;
516 }
517
518 static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
519 {
520         ImBuf *ibuf;
521         unsigned char *rect= NULL;
522         float *rect_float= NULL;
523         
524         if (floatbuf) {
525                 ibuf= IMB_allocImBuf(width, height, depth, IB_rectfloat);
526                 rect_float= (float*)ibuf->rect_float;
527         }
528         else {
529                 ibuf= IMB_allocImBuf(width, height, depth, IB_rect);
530                 rect= (unsigned char*)ibuf->rect;
531         }
532         
533         BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
534         ibuf->userflags |= IB_BITMAPDIRTY;
535         
536         switch(uvtestgrid) {
537         case 1:
538                 BKE_image_buf_fill_checker(rect, rect_float, width, height);
539                 break;
540         case 2:
541                 BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
542                 break;
543         default:
544                 BKE_image_buf_fill_color(rect, rect_float, width, height, color);
545         }
546
547         return ibuf;
548 }
549
550 /* adds new image block, creates ImBuf and initializes color */
551 Image *BKE_add_image_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
552 {
553         /* on save, type is changed to FILE in editsima.c */
554         Image *ima= image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
555         
556         if (ima) {
557                 ImBuf *ibuf;
558                 
559                 /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* dont do this, this writes in ain invalid filepath! */
560                 ima->gen_x= width;
561                 ima->gen_y= height;
562                 ima->gen_type= uvtestgrid;
563                 ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
564                 
565                 ibuf= add_ibuf_size(width, height, ima->name, depth, floatbuf, uvtestgrid, color);
566                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
567                 
568                 ima->ok= IMA_OK_LOADED;
569         }
570
571         return ima;
572 }
573
574 /* creates an image image owns the imbuf passed */
575 Image *BKE_add_image_imbuf(ImBuf *ibuf)
576 {
577         /* on save, type is changed to FILE in editsima.c */
578         Image *ima;
579
580         ima= image_alloc(BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
581
582         if (ima) {
583                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
584                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
585                 ima->ok= IMA_OK_LOADED;
586         }
587
588         return ima;
589 }
590
591 /* packs rect from memory as PNG */
592 void BKE_image_memorypack(Image *ima)
593 {
594         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
595         
596         if(ibuf==NULL)
597                 return;
598         if (ima->packedfile) {
599                 freePackedFile(ima->packedfile);
600                 ima->packedfile = NULL;
601         }
602         
603         ibuf->ftype= PNG;
604         ibuf->planes= R_IMF_PLANES_RGBA;
605         
606         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
607         if(ibuf->encodedbuffer==NULL) {
608                 printf("memory save for pack error\n");
609         }
610         else {
611                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
612                 
613                 pf->data = ibuf->encodedbuffer;
614                 pf->size = ibuf->encodedsize;
615                 ima->packedfile= pf;
616                 ibuf->encodedbuffer= NULL;
617                 ibuf->encodedsize= 0;
618                 ibuf->userflags &= ~IB_BITMAPDIRTY;
619                 
620                 if(ima->source==IMA_SRC_GENERATED) {
621                         ima->source= IMA_SRC_FILE;
622                         ima->type= IMA_TYPE_IMAGE;
623                 }
624         }
625 }
626
627 void tag_image_time(Image *ima)
628 {
629         if (ima)
630                 ima->lastused = (int)PIL_check_seconds_timer();
631 }
632
633 #if 0
634 static void tag_all_images_time() 
635 {
636         Image *ima;
637         int ctime = (int)PIL_check_seconds_timer();
638
639         ima= G.main->image.first;
640         while(ima) {
641                 if(ima->bindcode || ima->repbind || ima->ibufs.first) {
642                         ima->lastused = ctime;
643                 }
644         }
645 }
646 #endif
647
648 void free_old_images(void)
649 {
650         Image *ima;
651         static int lasttime = 0;
652         int ctime = (int)PIL_check_seconds_timer();
653         
654         /* 
655            Run garbage collector once for every collecting period of time 
656            if textimeout is 0, that's the option to NOT run the collector
657         */
658         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
659                 return;
660
661         /* of course not! */
662         if (G.rendering)
663                 return;
664         
665         lasttime = ctime;
666
667         ima= G.main->image.first;
668         while(ima) {
669                 if((ima->flag & IMA_NOCOLLECT)==0 && ctime - ima->lastused > U.textimeout) {
670                         /*
671                            If it's in GL memory, deallocate and set time tag to current time
672                            This gives textures a "second chance" to be used before dying.
673                         */
674                         if(ima->bindcode || ima->repbind) {
675                                 GPU_free_image(ima);
676                                 ima->lastused = ctime;
677                         }
678                         /* Otherwise, just kill the buffers */
679                         else if (ima->ibufs.first) {
680                                 image_free_buffers(ima);
681                         }
682                 }
683                 ima = ima->id.next;
684         }
685 }
686
687 static uintptr_t image_mem_size(Image *ima)
688 {
689         ImBuf *ibuf, *ibufm;
690         int level;
691         uintptr_t size = 0;
692
693         size= 0;
694         
695         /* viewers have memory depending on other rules, has no valid rect pointer */
696         if(ima->source==IMA_SRC_VIEWER)
697                 return 0;
698         
699         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
700                 if(ibuf->rect) size += MEM_allocN_len(ibuf->rect);
701                 else if(ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
702
703                 for(level=0; level<IB_MIPMAP_LEVELS; level++) {
704                         ibufm= ibuf->mipmap[level];
705                         if(ibufm) {
706                                 if(ibufm->rect) size += MEM_allocN_len(ibufm->rect);
707                                 else if(ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
708                         }
709                 }
710         }
711
712         return size;
713 }
714
715 void BKE_image_print_memlist(void)
716 {
717         Image *ima;
718         uintptr_t size, totsize= 0;
719
720         for(ima= G.main->image.first; ima; ima= ima->id.next)
721                 totsize += image_mem_size(ima);
722
723         printf("\ntotal image memory len: %.3f MB\n", (double)totsize/(double)(1024*1024));
724
725         for(ima= G.main->image.first; ima; ima= ima->id.next) {
726                 size= image_mem_size(ima);
727
728                 if(size)
729                         printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
730         }
731 }
732
733 void BKE_image_free_all_textures(void)
734 {
735         Tex *tex;
736         Image *ima;
737         /* unsigned int totsize= 0; */
738         
739         for(ima= G.main->image.first; ima; ima= ima->id.next)
740                 ima->id.flag &= ~LIB_DOIT;
741         
742         for(tex= G.main->tex.first; tex; tex= tex->id.next)
743                 if(tex->ima)
744                         tex->ima->id.flag |= LIB_DOIT;
745         
746         for(ima= G.main->image.first; ima; ima= ima->id.next) {
747                 if(ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
748                         ImBuf *ibuf;
749                         
750                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
751                                 /* escape when image is painted on */
752                                 if(ibuf->userflags & IB_BITMAPDIRTY)
753                                         break;
754                                 
755                                 /* if(ibuf->mipmap[0]) 
756                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
757                                 else
758                                         totsize+= ibuf->x*ibuf->y*4;*/
759                                 
760                         }
761                         if(ibuf==NULL)
762                                 image_free_buffers(ima);
763                 }
764         }
765         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
766 }
767
768 /* except_frame is weak, only works for seqs without offset... */
769 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
770 {
771         ImBuf *ibuf, *nbuf;
772
773         for(ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
774                 nbuf= ibuf->next;
775                 if(ibuf->userflags & IB_BITMAPDIRTY)
776                         continue;
777                 if(ibuf->index==IMA_NO_INDEX)
778                         continue;
779                 if(except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
780                         BLI_remlink(&ima->ibufs, ibuf);
781                         
782                         if (ibuf->userdata) {
783                                 MEM_freeN(ibuf->userdata);
784                                 ibuf->userdata = NULL;
785                         }
786                         IMB_freeImBuf(ibuf);
787                 }                                       
788         }
789 }
790
791 void BKE_image_all_free_anim_ibufs(int cfra)
792 {
793         Image *ima;
794         
795         for(ima= G.main->image.first; ima; ima= ima->id.next)
796                 if(ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
797                         BKE_image_free_anim_ibufs(ima, cfra);
798 }
799
800
801 /* *********** READ AND WRITE ************** */
802
803 int BKE_imtype_to_ftype(const char imtype)
804 {
805         if(imtype==R_IMF_IMTYPE_TARGA)
806                 return TGA;
807         else if(imtype==R_IMF_IMTYPE_RAWTGA)
808                 return RAWTGA;
809         else if(imtype== R_IMF_IMTYPE_IRIS) 
810                 return IMAGIC;
811 #ifdef WITH_HDR
812         else if (imtype==R_IMF_IMTYPE_RADHDR)
813                 return RADHDR;
814 #endif
815         else if (imtype==R_IMF_IMTYPE_PNG)
816                 return PNG;
817 #ifdef WITH_DDS
818         else if (imtype==R_IMF_IMTYPE_DDS)
819                 return DDS;
820 #endif
821         else if (imtype==R_IMF_IMTYPE_BMP)
822                 return BMP;
823 #ifdef WITH_TIFF
824         else if (imtype==R_IMF_IMTYPE_TIFF)
825                 return TIF;
826 #endif
827         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER)
828                 return OPENEXR;
829 #ifdef WITH_CINEON
830         else if (imtype==R_IMF_IMTYPE_CINEON)
831                 return CINEON;
832         else if (imtype==R_IMF_IMTYPE_DPX)
833                 return DPX;
834 #endif
835 #ifdef WITH_OPENJPEG
836         else if(imtype==R_IMF_IMTYPE_JP2)
837                 return JP2;
838 #endif
839         else
840                 return JPG|90;
841 }
842
843 char BKE_ftype_to_imtype(const int ftype)
844 {
845         if(ftype==0)
846                 return R_IMF_IMTYPE_TARGA;
847         else if(ftype == IMAGIC) 
848                 return R_IMF_IMTYPE_IRIS;
849 #ifdef WITH_HDR
850         else if (ftype & RADHDR)
851                 return R_IMF_IMTYPE_RADHDR;
852 #endif
853         else if (ftype & PNG)
854                 return R_IMF_IMTYPE_PNG;
855 #ifdef WITH_DDS
856         else if (ftype & DDS)
857                 return R_IMF_IMTYPE_DDS;
858 #endif
859         else if (ftype & BMP)
860                 return R_IMF_IMTYPE_BMP;
861 #ifdef WITH_TIFF
862         else if (ftype & TIF)
863                 return R_IMF_IMTYPE_TIFF;
864 #endif
865         else if (ftype & OPENEXR)
866                 return R_IMF_IMTYPE_OPENEXR;
867 #ifdef WITH_CINEON
868         else if (ftype & CINEON)
869                 return R_IMF_IMTYPE_CINEON;
870         else if (ftype & DPX)
871                 return R_IMF_IMTYPE_DPX;
872 #endif
873         else if (ftype & TGA)
874                 return R_IMF_IMTYPE_TARGA;
875         else if(ftype & RAWTGA)
876                 return R_IMF_IMTYPE_RAWTGA;
877 #ifdef WITH_OPENJPEG
878         else if(ftype & JP2)
879                 return R_IMF_IMTYPE_JP2;
880 #endif
881         else
882                 return R_IMF_IMTYPE_JPEG90;
883 }
884
885
886 int BKE_imtype_is_movie(const char imtype)
887 {
888         switch(imtype) {
889         case R_IMF_IMTYPE_AVIRAW:
890         case R_IMF_IMTYPE_AVIJPEG:
891         case R_IMF_IMTYPE_AVICODEC:
892         case R_IMF_IMTYPE_QUICKTIME:
893         case R_IMF_IMTYPE_FFMPEG:
894         case R_IMF_IMTYPE_H264:
895         case R_IMF_IMTYPE_THEORA:
896         case R_IMF_IMTYPE_XVID:
897         case R_IMF_IMTYPE_FRAMESERVER:
898                         return 1;
899         }
900         return 0;
901 }
902
903 int BKE_imtype_supports_alpha(const char imtype)
904 {
905         switch(imtype) {
906         case R_IMF_IMTYPE_TARGA:
907         case R_IMF_IMTYPE_IRIS:
908         case R_IMF_IMTYPE_PNG:
909         /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
910         case R_IMF_IMTYPE_RADHDR:
911         case R_IMF_IMTYPE_TIFF:
912         case R_IMF_IMTYPE_OPENEXR:
913         case R_IMF_IMTYPE_MULTILAYER:
914         case R_IMF_IMTYPE_DDS:
915         case R_IMF_IMTYPE_JP2:
916                         return 1;
917         }
918         return 0;
919 }
920
921 int BKE_imtype_supports_zbuf(const char imtype)
922 {
923         switch(imtype) {
924         case R_IMF_IMTYPE_IRIZ:
925         case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
926                         return 1;
927         }
928         return 0;
929 }
930
931 int BKE_imtype_supports_compress(const char imtype)
932 {
933         switch(imtype) {
934         case R_IMF_IMTYPE_PNG:
935                         return 1;
936         }
937         return 0;
938 }
939
940 int BKE_imtype_supports_quality(const char imtype)
941 {
942         switch(imtype) {
943         case R_IMF_IMTYPE_JPEG90:
944         case R_IMF_IMTYPE_JP2:
945         case R_IMF_IMTYPE_AVIJPEG:
946                         return 1;
947         }
948         return 0;
949 }
950
951 char BKE_imtype_valid_depths(const char imtype)
952 {
953         switch (imtype) {
954         case R_IMF_IMTYPE_RADHDR:
955                 return R_IMF_CHAN_DEPTH_32;
956         case R_IMF_IMTYPE_TIFF:
957                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
958         case R_IMF_IMTYPE_OPENEXR:
959                 return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
960         case R_IMF_IMTYPE_MULTILAYER:
961                 return R_IMF_CHAN_DEPTH_32;
962         /* eeh, cineone does some strange 10bits per channel */
963         case R_IMF_IMTYPE_DPX:
964         case R_IMF_IMTYPE_CINEON:
965                 return R_IMF_CHAN_DEPTH_12;
966         case R_IMF_IMTYPE_JP2:
967                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
968         /* most formats are 8bit only */
969         default:
970                 return R_IMF_CHAN_DEPTH_8;
971         }
972 }
973
974
975 /* string is from command line --render-format arg, keep in sync with
976  * creator.c help info */
977 char BKE_imtype_from_arg(const char *imtype_arg)
978 {
979         if      (!strcmp(imtype_arg,"TGA")) return R_IMF_IMTYPE_TARGA;
980         else if (!strcmp(imtype_arg,"IRIS")) return R_IMF_IMTYPE_IRIS;
981 #ifdef WITH_DDS
982         else if (!strcmp(imtype_arg,"DDS")) return R_IMF_IMTYPE_DDS;
983 #endif
984         else if (!strcmp(imtype_arg,"JPEG")) return R_IMF_IMTYPE_JPEG90;
985         else if (!strcmp(imtype_arg,"IRIZ")) return R_IMF_IMTYPE_IRIZ;
986         else if (!strcmp(imtype_arg,"RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
987         else if (!strcmp(imtype_arg,"AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
988         else if (!strcmp(imtype_arg,"AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
989         else if (!strcmp(imtype_arg,"PNG")) return R_IMF_IMTYPE_PNG;
990         else if (!strcmp(imtype_arg,"AVICODEC")) return R_IMF_IMTYPE_AVICODEC;
991         else if (!strcmp(imtype_arg,"QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
992         else if (!strcmp(imtype_arg,"BMP")) return R_IMF_IMTYPE_BMP;
993 #ifdef WITH_HDR
994         else if (!strcmp(imtype_arg,"HDR")) return R_IMF_IMTYPE_RADHDR;
995 #endif
996 #ifdef WITH_TIFF
997         else if (!strcmp(imtype_arg,"TIFF")) return R_IMF_IMTYPE_TIFF;
998 #endif
999 #ifdef WITH_OPENEXR
1000         else if (!strcmp(imtype_arg,"EXR")) return R_IMF_IMTYPE_OPENEXR;
1001         else if (!strcmp(imtype_arg,"MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1002 #endif
1003         else if (!strcmp(imtype_arg,"MPEG")) return R_IMF_IMTYPE_FFMPEG;
1004         else if (!strcmp(imtype_arg,"FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
1005 #ifdef WITH_CINEON
1006         else if (!strcmp(imtype_arg,"CINEON")) return R_IMF_IMTYPE_CINEON;
1007         else if (!strcmp(imtype_arg,"DPX")) return R_IMF_IMTYPE_DPX;
1008 #endif
1009 #ifdef WITH_OPENJPEG
1010         else if (!strcmp(imtype_arg,"JP2")) return R_IMF_IMTYPE_JP2;
1011 #endif
1012         else return R_IMF_IMTYPE_INVALID;
1013 }
1014
1015 int BKE_add_image_extension(char *string, const char imtype)
1016 {
1017         const char *extension= NULL;
1018         
1019         if(imtype== R_IMF_IMTYPE_IRIS) {
1020                 if(!BLI_testextensie(string, ".rgb"))
1021                         extension= ".rgb";
1022         }
1023         else if(imtype==R_IMF_IMTYPE_IRIZ) {
1024                 if(!BLI_testextensie(string, ".rgb"))
1025                         extension= ".rgb";
1026         }
1027 #ifdef WITH_HDR
1028         else if(imtype==R_IMF_IMTYPE_RADHDR) {
1029                 if(!BLI_testextensie(string, ".hdr"))
1030                         extension= ".hdr";
1031         }
1032 #endif
1033         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1034                 if(!BLI_testextensie(string, ".png"))
1035                         extension= ".png";
1036         }
1037 #ifdef WITH_DDS
1038         else if(imtype==R_IMF_IMTYPE_DDS) {
1039                 if(!BLI_testextensie(string, ".dds"))
1040                         extension= ".dds";
1041         }
1042 #endif
1043         else if(imtype==R_IMF_IMTYPE_RAWTGA) {
1044                 if(!BLI_testextensie(string, ".tga"))
1045                         extension= ".tga";
1046         }
1047         else if(imtype==R_IMF_IMTYPE_BMP) {
1048                 if(!BLI_testextensie(string, ".bmp"))
1049                         extension= ".bmp";
1050         }
1051 #ifdef WITH_TIFF
1052         else if(imtype==R_IMF_IMTYPE_TIFF) {
1053                 if(!BLI_testextensie(string, ".tif") && 
1054                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
1055         }
1056 #endif
1057 #ifdef WITH_OPENEXR
1058         else if( ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1059                 if(!BLI_testextensie(string, ".exr"))
1060                         extension= ".exr";
1061         }
1062 #endif
1063 #ifdef WITH_CINEON
1064         else if(imtype==R_IMF_IMTYPE_CINEON){
1065                 if (!BLI_testextensie(string, ".cin"))
1066                         extension= ".cin";
1067         }
1068         else if(imtype==R_IMF_IMTYPE_DPX){
1069                 if (!BLI_testextensie(string, ".dpx"))
1070                         extension= ".dpx";
1071         }
1072 #endif
1073         else if(imtype==R_IMF_IMTYPE_TARGA) {
1074                 if(!BLI_testextensie(string, ".tga"))
1075                         extension= ".tga";
1076         }
1077 #ifdef WITH_OPENJPEG
1078         else if(imtype==R_IMF_IMTYPE_JP2) {
1079                 if(!BLI_testextensie(string, ".jp2"))
1080                         extension= ".jp2";
1081         }
1082 #endif
1083         else { //   R_IMF_IMTYPE_AVICODEC, R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1084                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1085                         extension= ".jpg";
1086         }
1087
1088         if(extension) {
1089                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1090                 /* remove any other known image extension */
1091                 if(BLI_testextensie_array(string, imb_ext_image)
1092                                   || (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt))) {
1093                         return BLI_replace_extension(string, FILE_MAX, extension);
1094                 } else {
1095                         return BLI_ensure_extension(string, FILE_MAX, extension);
1096                         return TRUE;
1097                 }
1098                 
1099         }
1100         else {
1101                 return FALSE;
1102         }
1103 }
1104
1105 /* could allow access externally - 512 is for long names, 64 is for id names */
1106 typedef struct StampData {
1107         char    file[512];
1108         char    note[512];
1109         char    date[512];
1110         char    marker[512];
1111         char    time[512];
1112         char    frame[512];
1113         char    camera[64];
1114         char    cameralens[64];
1115         char    scene[64];
1116         char    strip[64];
1117         char    rendertime[64];
1118 } StampData;
1119
1120 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1121 {
1122         char text[256];
1123         struct tm *tl;
1124         time_t t;
1125
1126         if (scene->r.stamp & R_STAMP_FILENAME) {
1127                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s":"%s", G.relbase_valid ? G.main->name:"<untitled>");
1128         } else {
1129                 stamp_data->file[0] = '\0';
1130         }
1131         
1132         if (scene->r.stamp & R_STAMP_NOTE) {
1133                 /* Never do prefix for Note */
1134                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1135         } else {
1136                 stamp_data->note[0] = '\0';
1137         }
1138         
1139         if (scene->r.stamp & R_STAMP_DATE) {
1140                 t = time(NULL);
1141                 tl = localtime(&t);
1142                 BLI_snprintf(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d", tl->tm_year+1900, tl->tm_mon+1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
1143                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s":"%s", text);
1144         } else {
1145                 stamp_data->date[0] = '\0';
1146         }
1147         
1148         if (scene->r.stamp & R_STAMP_MARKER) {
1149                 char *name = scene_find_last_marker_name(scene, CFRA);
1150
1151                 if (name)       BLI_strncpy(text, name, sizeof(text));
1152                 else            strcpy(text, "<none>");
1153
1154                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s":"%s", text);
1155         } else {
1156                 stamp_data->marker[0] = '\0';
1157         }
1158         
1159         if (scene->r.stamp & R_STAMP_TIME) {
1160                 int f = (int)(scene->r.cfra % scene->r.frs_sec);
1161                 int s = (int)(scene->r.cfra / scene->r.frs_sec);
1162                 int h= 0;
1163                 int m= 0;
1164
1165                 if (s) {
1166                         m = (int)(s / 60);
1167                         s %= 60;
1168
1169                         if (m) {
1170                                 h = (int)(m / 60);
1171                                 m %= 60;
1172                         }
1173                 }
1174
1175                 if (scene->r.frs_sec < 100)
1176                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%02d", h, m, s, f);
1177                 else
1178                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%03d", h, m, s, f);
1179
1180                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s":"%s", text);
1181         } else {
1182                 stamp_data->time[0] = '\0';
1183         }
1184         
1185         if (scene->r.stamp & R_STAMP_FRAME) {
1186                 char format[32];
1187                 int digits= 1;
1188                 
1189                 if(scene->r.efra>9)
1190                         digits= 1 + (int) log10(scene->r.efra);
1191
1192                 BLI_snprintf(format, sizeof(format), do_prefix ? "Frame %%0%di":"%%0%di", digits);
1193                 BLI_snprintf (stamp_data->frame, sizeof(stamp_data->frame), format, scene->r.cfra);
1194         } else {
1195                 stamp_data->frame[0] = '\0';
1196         }
1197
1198         if (scene->r.stamp & R_STAMP_CAMERA) {
1199                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s":"%s", camera ? camera->id.name+2 : "<none>");
1200         } else {
1201                 stamp_data->camera[0] = '\0';
1202         }
1203
1204         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1205                 if (camera && camera->type == OB_CAMERA) {
1206                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1207                 }
1208                 else            strcpy(text, "<none>");
1209
1210                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s":"%s", text);
1211         } else {
1212                 stamp_data->cameralens[0] = '\0';
1213         }
1214
1215         if (scene->r.stamp & R_STAMP_SCENE) {
1216                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s":"%s", scene->id.name+2);
1217         } else {
1218                 stamp_data->scene[0] = '\0';
1219         }
1220         
1221         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1222                 Sequence *seq= seq_foreground_frame_get(scene, scene->r.cfra);
1223         
1224                 if (seq)        BLI_strncpy(text, seq->name+2, sizeof(text));
1225                 else            strcpy(text, "<none>");
1226
1227                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s":"%s", text);
1228         } else {
1229                 stamp_data->strip[0] = '\0';
1230         }
1231
1232         {
1233                 Render *re= RE_GetRender(scene->id.name);
1234                 RenderStats *stats= re ? RE_GetStats(re):NULL;
1235
1236                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1237                         BLI_timestr(stats->lastframetime, text);
1238
1239                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s":"%s", text);
1240                 } else {
1241                         stamp_data->rendertime[0] = '\0';
1242                 }
1243         }
1244 }
1245
1246 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1247 {
1248         struct StampData stamp_data;
1249         float w, h, pad;
1250         int x, y, y_ofs;
1251         float h_fixed;
1252         const int mono= blf_mono_font_render; // XXX
1253
1254 #define BUFF_MARGIN_X 2
1255 #define BUFF_MARGIN_Y 1
1256
1257         if (!rect && !rectf)
1258                 return;
1259         
1260         stampdata(scene, camera, &stamp_data, 1);
1261
1262         /* TODO, do_versions */
1263         if(scene->r.stamp_font_id < 8)
1264                 scene->r.stamp_font_id= 12;
1265
1266         /* set before return */
1267         BLF_size(mono, scene->r.stamp_font_id, 72);
1268         
1269         BLF_buffer(mono, rectf, rect, width, height, channels);
1270         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1271         pad= BLF_width_max(mono);
1272
1273         /* use 'h_fixed' rather than 'h', aligns better */
1274         h_fixed= BLF_height_max(mono);
1275         y_ofs = -BLF_descender(mono);
1276
1277         x= 0;
1278         y= height;
1279
1280         if (stamp_data.file[0]) {
1281                 /* Top left corner */
1282                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1283                 y -= h;
1284
1285                 /* also a little of space to the background. */
1286                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1287
1288                 /* and draw the text. */
1289                 BLF_position(mono, x, y + y_ofs, 0.0);
1290                 BLF_draw_buffer(mono, stamp_data.file);
1291
1292                 /* the extra pixel for background. */
1293                 y -= BUFF_MARGIN_Y * 2;
1294         }
1295
1296         /* Top left corner, below File */
1297         if (stamp_data.note[0]) {
1298                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1299                 y -= h;
1300
1301                 /* and space for background. */
1302                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1303
1304                 BLF_position(mono, x, y + y_ofs, 0.0);
1305                 BLF_draw_buffer(mono, stamp_data.note);
1306
1307                 /* the extra pixel for background. */
1308                 y -= BUFF_MARGIN_Y * 2;
1309         }
1310         
1311         /* Top left corner, below File (or Note) */
1312         if (stamp_data.date[0]) {
1313                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1314                 y -= h;
1315
1316                 /* and space for background. */
1317                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1318
1319                 BLF_position(mono, x, y + y_ofs, 0.0);
1320                 BLF_draw_buffer(mono, stamp_data.date);
1321
1322                 /* the extra pixel for background. */
1323                 y -= BUFF_MARGIN_Y * 2;
1324         }
1325
1326         /* Top left corner, below File, Date or Note */
1327         if (stamp_data.rendertime[0]) {
1328                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1329                 y -= h;
1330
1331                 /* and space for background. */
1332                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1333
1334                 BLF_position(mono, x, y + y_ofs, 0.0);
1335                 BLF_draw_buffer(mono, stamp_data.rendertime);
1336         }
1337
1338         x= 0;
1339         y= 0;
1340
1341         /* Bottom left corner, leaving space for timing */
1342         if (stamp_data.marker[0]) {
1343                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1344
1345                 /* extra space for background. */
1346                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1347
1348                 /* and pad the text. */
1349                 BLF_position(mono, x, y + y_ofs, 0.0);
1350                 BLF_draw_buffer(mono, stamp_data.marker);
1351
1352                 /* space width. */
1353                 x += w + pad;
1354         }
1355         
1356         /* Left bottom corner */
1357         if (stamp_data.time[0]) {
1358                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h= h_fixed;
1359
1360                 /* extra space for background */
1361                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1362
1363                 /* and pad the text. */
1364                 BLF_position(mono, x, y + y_ofs, 0.0);
1365                 BLF_draw_buffer(mono, stamp_data.time);
1366
1367                 /* space width. */
1368                 x += w + pad;
1369         }
1370         
1371         if (stamp_data.frame[0]) {
1372                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h= h_fixed;
1373
1374                 /* extra space for background. */
1375                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1376
1377                 /* and pad the text. */
1378                 BLF_position(mono, x, y + y_ofs, 0.0);
1379                 BLF_draw_buffer(mono, stamp_data.frame);
1380
1381                 /* space width. */
1382                 x += w + pad;
1383         }
1384
1385         if (stamp_data.camera[0]) {
1386                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1387
1388                 /* extra space for background. */
1389                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1390                 BLF_position(mono, x, y + y_ofs, 0.0);
1391                 BLF_draw_buffer(mono, stamp_data.camera);
1392
1393                 /* space width. */
1394                 x += w + pad;
1395         }
1396
1397         if (stamp_data.cameralens[0]) {
1398                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h= h_fixed;
1399
1400                 /* extra space for background. */
1401                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1402                 BLF_position(mono, x, y + y_ofs, 0.0);
1403                 BLF_draw_buffer(mono, stamp_data.cameralens);
1404         }
1405         
1406         if (stamp_data.scene[0]) {
1407                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1408
1409                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1410                 x= width - w - 2;
1411
1412                 /* extra space for background. */
1413                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1414
1415                 /* and pad the text. */
1416                 BLF_position(mono, x, y+y_ofs, 0.0);
1417                 BLF_draw_buffer(mono, stamp_data.scene);
1418         }
1419         
1420         if (stamp_data.strip[0]) {
1421                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h= h_fixed;
1422
1423                 /* Top right corner, with an extra space because blenfont is too strict! */
1424                 x= width - w - pad;
1425                 y= height - h;
1426
1427                 /* extra space for background. */
1428                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1429
1430                 BLF_position(mono, x, y + y_ofs, 0.0);
1431                 BLF_draw_buffer(mono, stamp_data.strip);
1432         }
1433
1434         /* cleanup the buffer. */
1435         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1436
1437 #undef BUFF_MARGIN_X
1438 #undef BUFF_MARGIN_Y
1439 }
1440
1441 void BKE_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1442 {
1443         struct StampData stamp_data;
1444
1445         if (!ibuf)      return;
1446         
1447         /* fill all the data values, no prefix */
1448         stampdata(scene, camera, &stamp_data, 0);
1449         
1450         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1451         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1452         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1453         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1454         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1455         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1456         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1457         if (stamp_data.cameralens[0]) IMB_metadata_change_field (ibuf, "Lens",  stamp_data.cameralens);
1458         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1459         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1460         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1461 }
1462
1463 int BKE_alphatest_ibuf(ImBuf *ibuf)
1464 {
1465         int tot;
1466         if(ibuf->rect_float) {
1467                 float *buf= ibuf->rect_float;
1468                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1469                         if(buf[3] < 1.0f) {
1470                                 return TRUE;
1471                         }
1472                 }
1473         }
1474         else if (ibuf->rect) {
1475                 unsigned char *buf= (unsigned char *)ibuf->rect;
1476                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1477                         if(buf[3] != 255) {
1478                                 return TRUE;
1479                         }
1480                 }
1481         }
1482
1483         return FALSE;
1484 }
1485
1486 int BKE_write_ibuf(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1487 {
1488         char imtype= imf->imtype;
1489         char compress= imf->compress;
1490         char quality= imf->quality;
1491
1492         int ok;
1493
1494         if(imtype == -1) {
1495                 /* use whatever existing image type is set by 'ibuf' */
1496         }
1497         else if(imtype== R_IMF_IMTYPE_IRIS) {
1498                 ibuf->ftype= IMAGIC;
1499         }
1500 #ifdef WITH_HDR
1501         else if (imtype==R_IMF_IMTYPE_RADHDR) {
1502                 ibuf->ftype= RADHDR;
1503         }
1504 #endif
1505         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1506                 ibuf->ftype= PNG;
1507
1508                 if(imtype==R_IMF_IMTYPE_PNG)
1509                         ibuf->ftype |= compress;
1510
1511         }
1512 #ifdef WITH_DDS
1513         else if (imtype==R_IMF_IMTYPE_DDS) {
1514                 ibuf->ftype= DDS;
1515         }
1516 #endif
1517         else if (imtype==R_IMF_IMTYPE_BMP) {
1518                 ibuf->ftype= BMP;
1519         }
1520 #ifdef WITH_TIFF
1521         else if (imtype==R_IMF_IMTYPE_TIFF) {
1522                 ibuf->ftype= TIF;
1523
1524                 if(imf->depth == R_IMF_CHAN_DEPTH_16)
1525                         ibuf->ftype |= TIF_16BIT;
1526         }
1527 #endif
1528 #ifdef WITH_OPENEXR
1529         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER) {
1530                 ibuf->ftype= OPENEXR;
1531                 if(imf->depth == R_IMF_CHAN_DEPTH_16)
1532                         ibuf->ftype |= OPENEXR_HALF;
1533                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1534                 
1535                 if(!(imf->flag & R_IMF_FLAG_ZBUF))
1536                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1537                 
1538         }
1539 #endif
1540 #ifdef WITH_CINEON
1541         else if (imtype==R_IMF_IMTYPE_CINEON) {
1542                 ibuf->ftype = CINEON;
1543         }
1544         else if (imtype==R_IMF_IMTYPE_DPX) {
1545                 ibuf->ftype = DPX;
1546         }
1547 #endif
1548         else if (imtype==R_IMF_IMTYPE_TARGA) {
1549                 ibuf->ftype= TGA;
1550         }
1551         else if(imtype==R_IMF_IMTYPE_RAWTGA) {
1552                 ibuf->ftype= RAWTGA;
1553         }
1554 #ifdef WITH_OPENJPEG
1555         else if(imtype==R_IMF_IMTYPE_JP2) {
1556                 if(quality < 10) quality= 90;
1557                 ibuf->ftype= JP2|quality;
1558                 
1559                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1560                         ibuf->ftype |= JP2_16BIT;
1561                 } else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1562                         ibuf->ftype |= JP2_12BIT;
1563                 }
1564                 
1565                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1566                         ibuf->ftype |= JP2_YCC;
1567                 }
1568
1569                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1570                         ibuf->ftype |= JP2_CINE;
1571                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1572                                 ibuf->ftype |= JP2_CINE_48FPS;
1573                 }
1574         }
1575 #endif
1576         else {
1577                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1578                 if(quality < 10) quality= 90;
1579                 ibuf->ftype= JPG|quality;
1580                 if(ibuf->planes==32) ibuf->planes= 24;  /* unsupported feature only confuses other s/w */
1581         }
1582         
1583         BLI_make_existing_file(name);
1584         
1585         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1586         if (ok == 0) {
1587                 perror(name);
1588         }
1589         
1590         return(ok);
1591 }
1592
1593 int BKE_write_ibuf_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1594 {
1595         if(scene && scene->r.stamp & R_STAMP_ALL)
1596                 BKE_stamp_info(scene, camera, ibuf);
1597
1598         return BKE_write_ibuf(ibuf, name, imf);
1599 }
1600
1601
1602 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1603 {
1604         if (string==NULL) return;
1605         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1606         BLI_path_abs(string, relbase);
1607
1608         if(use_frames)
1609                 BLI_path_frame(string, frame, 4);
1610
1611         if(use_ext)
1612                 BKE_add_image_extension(string, imtype);
1613                 
1614 }
1615
1616 /* used by sequencer too */
1617 struct anim *openanim(const char *name, int flags, int streamindex)
1618 {
1619         struct anim *anim;
1620         struct ImBuf *ibuf;
1621         
1622         anim = IMB_open_anim(name, flags, streamindex);
1623         if (anim == NULL) return NULL;
1624
1625         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1626         if (ibuf == NULL) {
1627                 if(BLI_exists(name))
1628                         printf("not an anim: %s\n", name);
1629                 else
1630                         printf("anim file doesn't exist: %s\n", name);
1631                 IMB_free_anim(anim);
1632                 return NULL;
1633         }
1634         IMB_freeImBuf(ibuf);
1635         
1636         return(anim);
1637 }
1638
1639 /* ************************* New Image API *************** */
1640
1641
1642 /* Notes about Image storage 
1643 - packedfile
1644   -> written in .blend
1645 - filename
1646   -> written in .blend
1647 - movie
1648   -> comes from packedfile or filename
1649 - renderresult
1650   -> comes from packedfile or filename
1651 - listbase
1652   -> ibufs from exrhandle
1653 - flipbook array
1654   -> ibufs come from movie, temporary renderresult or sequence
1655 - ibuf
1656   -> comes from packedfile or filename or generated
1657
1658 */
1659
1660
1661 /* forces existence of 1 Image for renderout or nodes, returns Image */
1662 /* name is only for default, when making new one */
1663 Image *BKE_image_verify_viewer(int type, const char *name)
1664 {
1665         Image *ima;
1666         
1667         for(ima=G.main->image.first; ima; ima= ima->id.next)
1668                 if(ima->source==IMA_SRC_VIEWER)
1669                         if(ima->type==type)
1670                                 break;
1671         
1672         if(ima==NULL)
1673                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1674         
1675         /* happens on reload, imagewindow cannot be image user when hidden*/
1676         if(ima->id.us==0)
1677                 id_us_plus(&ima->id);
1678
1679         return ima;
1680 }
1681
1682 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1683 {
1684         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1685 }
1686
1687 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1688 {
1689         if(ima==NULL)
1690                 return;
1691         
1692         switch(signal) {
1693         case IMA_SIGNAL_FREE:
1694                 image_free_buffers(ima);
1695                 if(iuser)
1696                         iuser->ok= 1;
1697                 break;
1698         case IMA_SIGNAL_SRC_CHANGE:
1699                 if(ima->type == IMA_TYPE_UV_TEST)
1700                         if(ima->source != IMA_SRC_GENERATED)
1701                                 ima->type= IMA_TYPE_IMAGE;
1702
1703                 if(ima->source==IMA_SRC_GENERATED) {
1704                         if(ima->gen_x==0 || ima->gen_y==0) {
1705                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1706                                 if(ibuf) {
1707                                         ima->gen_x= ibuf->x;
1708                                         ima->gen_y= ibuf->y;
1709                                 }
1710                         }
1711                 }
1712
1713                 /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
1714                 if(ima->type!=IMA_TYPE_MULTILAYER)
1715                         image_free_buffers(ima);
1716
1717                 ima->ok= 1;
1718                 if(iuser)
1719                         iuser->ok= 1;
1720                 break;
1721                         
1722         case IMA_SIGNAL_RELOAD:
1723                 /* try to repack file */
1724                 if(ima->packedfile) {
1725                         PackedFile *pf;
1726                         pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
1727                         if (pf) {
1728                                 freePackedFile(ima->packedfile);
1729                                 ima->packedfile = pf;
1730                                 image_free_buffers(ima);
1731                         } else {
1732                                 printf("ERROR: Image not available. Keeping packed image\n");
1733                         }
1734                 }
1735                 else
1736                         image_free_buffers(ima);
1737                 
1738                 if(iuser)
1739                         iuser->ok= 1;
1740                 
1741                 break;
1742         case IMA_SIGNAL_USER_NEW_IMAGE:
1743                 if(iuser) {
1744                         iuser->ok= 1;
1745                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1746                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1747                                         iuser->multi_index= 0;
1748                                         iuser->layer= iuser->pass= 0;
1749                                 }
1750                         }
1751                 }
1752                 break;
1753         }
1754         
1755         /* dont use notifiers because they are not 100% sure to succseed
1756          * this also makes sure all scenes are accounted for. */
1757         {
1758                 Scene *scene;
1759                 for(scene= G.main->scene.first; scene; scene= scene->id.next) {
1760                         if(scene->nodetree) {
1761                                 nodeUpdateID(scene->nodetree, &ima->id);
1762                         }
1763                 }
1764         }
1765 }
1766
1767 /* if layer or pass changes, we need an index for the imbufs list */
1768 /* note it is called for rendered results, but it doesnt use the index! */
1769 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1770 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1771 {
1772         RenderLayer *rl;
1773         RenderPass *rpass= NULL;
1774         
1775         if(rr==NULL) 
1776                 return NULL;
1777         
1778         if(iuser) {
1779                 short index= 0, rl_index= 0, rp_index;
1780                 
1781                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1782                         rp_index= 0;
1783                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1784                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1785                                         break;
1786                         if(rpass)
1787                                 break;
1788                 }
1789                 
1790                 if(rpass)
1791                         iuser->multi_index= index;
1792                 else 
1793                         iuser->multi_index= 0;
1794         }
1795         if(rpass==NULL) {
1796                 rl= rr->layers.first;
1797                 if(rl)
1798                         rpass= rl->passes.first;
1799         }
1800         
1801         return rpass;
1802 }
1803
1804 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1805 {
1806         if(ima->rr) {
1807                 return ima->rr;
1808         }
1809         else if(ima->type==IMA_TYPE_R_RESULT) {
1810                 if(ima->render_slot == ima->last_render_slot)
1811                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1812                 else
1813                         return ima->renders[ima->render_slot];
1814         }
1815         else
1816                 return NULL;
1817 }
1818
1819 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1820 {
1821         if(ima->rr);
1822         else if(ima->type==IMA_TYPE_R_RESULT) {
1823                 if(ima->render_slot == ima->last_render_slot)
1824                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1825         }
1826 }
1827
1828 void BKE_image_backup_render(Scene *scene, Image *ima)
1829 {
1830         /* called right before rendering, ima->renders contains render
1831            result pointers for everything but the current render */
1832         Render *re= RE_GetRender(scene->id.name);
1833         int slot= ima->render_slot, last= ima->last_render_slot;
1834
1835         if(slot != last) {
1836                 if(ima->renders[slot]) {
1837                         RE_FreeRenderResult(ima->renders[slot]);
1838                         ima->renders[slot]= NULL;
1839                 }
1840
1841                 ima->renders[last]= NULL;
1842                 RE_SwapResult(re, &ima->renders[last]);
1843         }
1844
1845         ima->last_render_slot= slot;
1846 }
1847
1848 /* after imbuf load, openexr type can return with a exrhandle open */
1849 /* in that case we have to build a render-result */
1850 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1851 {
1852         
1853         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1854
1855 #ifdef WITH_OPENEXR
1856         IMB_exr_close(ibuf->userdata);
1857 #endif
1858
1859         ibuf->userdata= NULL;
1860         if(ima->rr)
1861                 ima->rr->framenr= framenr;
1862 }
1863
1864 /* common stuff to do with images after loading */
1865 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1866 {
1867         /* preview is NULL when it has never been used as an icon before */
1868         if(G.background==0 && ima->preview==NULL)
1869                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1870
1871         /* fields */
1872         if (ima->flag & IMA_FIELDS) {
1873                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1874                 else de_interlace_ng(ibuf);
1875         }
1876         /* timer */
1877         ima->lastused = clock() / CLOCKS_PER_SEC;
1878         
1879         ima->ok= IMA_OK_LOADED;
1880         
1881 }
1882
1883 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1884 {
1885         struct ImBuf *ibuf;
1886         unsigned short numlen;
1887         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1888         int flag;
1889         
1890         /* XXX temp stuff? */
1891         if(ima->lastframe != frame)
1892                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1893
1894         ima->lastframe= frame;
1895         BLI_strncpy(name, ima->name, sizeof(name));
1896         BLI_stringdec(name, head, tail, &numlen);
1897         BLI_stringenc(name, head, tail, numlen, frame);
1898
1899         BLI_path_abs(name, ID_BLEND_PATH(G.main, &ima->id));
1900         
1901         flag= IB_rect|IB_multilayer;
1902         if(ima->flag & IMA_DO_PREMUL)
1903                 flag |= IB_premul;
1904
1905         /* read ibuf */
1906         ibuf = IMB_loadiffname(name, flag);
1907
1908 #if 0
1909         if(ibuf) {
1910                 printf(AT" loaded %s\n", name);
1911         } else {
1912                 printf(AT" missed %s\n", name);
1913         }
1914 #endif
1915
1916         if (ibuf) {
1917 #ifdef WITH_OPENEXR
1918                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1919                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1920                         image_create_multilayer(ima, ibuf, frame);      
1921                         ima->type= IMA_TYPE_MULTILAYER;
1922                         IMB_freeImBuf(ibuf);
1923                         ibuf= NULL;
1924                 }
1925                 else {
1926                         image_initialize_after_load(ima, ibuf);
1927                         image_assign_ibuf(ima, ibuf, 0, frame);
1928                 }
1929 #else
1930                 image_initialize_after_load(ima, ibuf);
1931                 image_assign_ibuf(ima, ibuf, 0, frame);
1932 #endif
1933         }
1934         else
1935                 ima->ok= 0;
1936         
1937         if(iuser)
1938                 iuser->ok= ima->ok;
1939         
1940         return ibuf;
1941 }
1942
1943 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1944 {
1945         struct ImBuf *ibuf= NULL;
1946         
1947         /* either we load from RenderResult, or we have to load a new one */
1948         
1949         /* check for new RenderResult */
1950         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1951                 /* copy to survive not found multilayer image */
1952                 RenderResult *oldrr= ima->rr;
1953         
1954                 ima->rr= NULL;
1955                 ibuf = image_load_sequence_file(ima, iuser, frame);
1956                 
1957                 if(ibuf) { /* actually an error */
1958                         ima->type= IMA_TYPE_IMAGE;
1959                         printf("error, multi is normal image\n");
1960                 }
1961                 // printf("loaded new result %p\n", ima->rr);
1962                 /* free result if new one found */
1963                 if(ima->rr) {
1964                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1965                         if(oldrr) RE_FreeRenderResult(oldrr);
1966                 }
1967                 else {
1968                         ima->rr= oldrr;
1969                 }
1970
1971         }
1972         if(ima->rr) {
1973                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1974                 
1975                 if(rpass) {
1976                         // printf("load from pass %s\n", rpass->name);
1977                         /* since we free  render results, we copy the rect */
1978                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
1979                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1980                         ibuf->flags |= IB_rectfloat;
1981                         ibuf->mall= IB_rectfloat;
1982                         ibuf->channels= rpass->channels;
1983                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1984                         
1985                         image_initialize_after_load(ima, ibuf);
1986                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1987                         
1988                 }
1989                 // else printf("pass not found\n");
1990         }
1991         else
1992                 ima->ok= 0;
1993         
1994         if(iuser)
1995                 iuser->ok= ima->ok;
1996         
1997         return ibuf;
1998 }
1999
2000
2001 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2002 {
2003         struct ImBuf *ibuf= NULL;
2004         
2005         ima->lastframe= frame;
2006         
2007         if(ima->anim==NULL) {
2008                 char str[FILE_MAX];
2009                 
2010                 BLI_strncpy(str, ima->name, FILE_MAX);
2011                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2012
2013                 /* FIXME: make several stream accessible in image editor, too*/
2014                 ima->anim = openanim(str, IB_rect, 0);
2015                 
2016                 /* let's initialize this user */
2017                 if(ima->anim && iuser && iuser->frames==0)
2018                         iuser->frames= IMB_anim_get_duration(ima->anim,
2019                                                              IMB_TC_RECORD_RUN);
2020         }
2021         
2022         if(ima->anim) {
2023                 int dur = IMB_anim_get_duration(ima->anim,
2024                                                 IMB_TC_RECORD_RUN);
2025                 int fra= frame-1;
2026                 
2027                 if(fra<0) fra = 0;
2028                 if(fra>(dur-1)) fra= dur-1;
2029                 ibuf = IMB_makeSingleUser(
2030                         IMB_anim_absolute(ima->anim, fra,
2031                                           IMB_TC_RECORD_RUN,
2032                                           IMB_PROXY_NONE));
2033                 
2034                 if(ibuf) {
2035                         image_initialize_after_load(ima, ibuf);
2036                         image_assign_ibuf(ima, ibuf, 0, frame);
2037                 }
2038                 else
2039                         ima->ok= 0;
2040         }
2041         else
2042                 ima->ok= 0;
2043         
2044         if(iuser)
2045                 iuser->ok= ima->ok;
2046         
2047         return ibuf;
2048 }
2049
2050 /* warning, 'iuser' can be NULL */
2051 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2052 {
2053         struct ImBuf *ibuf;
2054         char str[FILE_MAX];
2055         int assign = 0, flag;
2056         
2057         /* always ensure clean ima */
2058         image_free_buffers(ima);
2059         
2060         /* is there a PackedFile with this image ? */
2061         if (ima->packedfile) {
2062                 flag = IB_rect|IB_multilayer;
2063                 if(ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2064                 
2065                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag, "<packed data>");
2066         } 
2067         else {
2068                 flag= IB_rect|IB_multilayer|IB_metadata;
2069                 if(ima->flag & IMA_DO_PREMUL)
2070                         flag |= IB_premul;
2071                         
2072                 /* get the right string */
2073                 BLI_strncpy(str, ima->name, sizeof(str));
2074                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2075                 
2076                 /* read ibuf */
2077                 ibuf = IMB_loadiffname(str, flag);
2078         }
2079         
2080         if (ibuf) {
2081                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2082                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
2083                         image_create_multilayer(ima, ibuf, cfra);       
2084                         ima->type= IMA_TYPE_MULTILAYER;
2085                         IMB_freeImBuf(ibuf);
2086                         ibuf= NULL;
2087                 }
2088                 else {
2089                         image_initialize_after_load(ima, ibuf);
2090                         assign= 1;
2091
2092                         /* check if the image is a font image... */
2093                         detectBitmapFont(ibuf);
2094                         
2095                         /* make packed file for autopack */
2096                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2097                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2098                 }
2099         }
2100         else
2101                 ima->ok= 0;
2102         
2103         if(assign)
2104                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2105
2106         if(iuser)
2107                 iuser->ok= ima->ok;
2108         
2109         return ibuf;
2110 }
2111
2112 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2113 {
2114         ImBuf *ibuf= NULL;
2115         
2116         if(ima->rr==NULL) {
2117                 ibuf = image_load_image_file(ima, iuser, 0);
2118                 if(ibuf) { /* actually an error */
2119                         ima->type= IMA_TYPE_IMAGE;
2120                         return ibuf;
2121                 }
2122         }
2123         if(ima->rr) {
2124                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2125
2126                 if(rpass) {
2127                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2128                         
2129                         image_initialize_after_load(ima, ibuf);
2130                         
2131                         ibuf->rect_float= rpass->rect;
2132                         ibuf->flags |= IB_rectfloat;
2133                         ibuf->channels= rpass->channels;
2134                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2135
2136                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2137                 }
2138         }
2139         
2140         if(ibuf==NULL) 
2141                 ima->ok= 0;
2142         if(iuser)
2143                 iuser->ok= ima->ok;
2144         
2145         return ibuf;
2146 }
2147
2148
2149 /* showing RGBA result itself (from compo/sequence) or
2150    like exr, using layers etc */
2151 /* always returns a single ibuf, also during render progress */
2152 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2153 {
2154         Render *re;
2155         RenderResult rres;
2156         float *rectf, *rectz;
2157         unsigned int *rect;
2158         float dither;
2159         int channels, layer, pass;
2160         ImBuf *ibuf;
2161         int from_render= (ima->render_slot == ima->last_render_slot);
2162
2163         if(!(iuser && iuser->scene))
2164                 return NULL;
2165
2166         /* if we the caller is not going to release the lock, don't give the image */
2167         if(!lock_r)
2168                 return NULL;
2169
2170         re= RE_GetRender(iuser->scene->id.name);
2171
2172         channels= 4;
2173         layer= (iuser)? iuser->layer: 0;
2174         pass= (iuser)? iuser->pass: 0;
2175
2176         if(from_render) {
2177                 RE_AcquireResultImage(re, &rres);
2178         }
2179         else if(ima->renders[ima->render_slot]) {
2180                 rres= *(ima->renders[ima->render_slot]);
2181                 rres.have_combined= rres.rectf != NULL;
2182         }
2183         else
2184                 memset(&rres, 0, sizeof(RenderResult));
2185         
2186         if(!(rres.rectx > 0 && rres.recty > 0)) {
2187                 if(from_render)
2188                         RE_ReleaseResultImage(re);
2189                 return NULL;
2190         }
2191
2192         /* release is done in BKE_image_release_ibuf using lock_r */
2193         if(from_render) {
2194                 BLI_lock_thread(LOCK_VIEWER);
2195                 *lock_r= re;
2196         }
2197
2198         /* this gives active layer, composite or seqence result */
2199         rect= (unsigned int *)rres.rect32;
2200         rectf= rres.rectf;
2201         rectz= rres.rectz;
2202         dither= iuser->scene->r.dither_intensity;
2203
2204         /* combined layer gets added as first layer */
2205         if(rres.have_combined && layer==0);
2206         else if(rres.layers.first) {
2207                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
2208                 if(rl) {
2209                         RenderPass *rpass;
2210
2211                         /* there's no combined pass, is in renderlayer itself */
2212                         if(pass==0) {
2213                                 rectf= rl->rectf;
2214                         }
2215                         else {
2216                                 rpass= BLI_findlink(&rl->passes, pass-1);
2217                                 if(rpass) {
2218                                         channels= rpass->channels;
2219                                         rectf= rpass->rect;
2220                                         dither= 0.0f; /* don't dither passes */
2221                                 }
2222                         }
2223
2224                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
2225                                 if(rpass->passtype == SCE_PASS_Z)
2226                                         rectz= rpass->rect;
2227                 }
2228         }
2229
2230         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2231
2232         /* make ibuf if needed, and initialize it */
2233         if(ibuf==NULL) {
2234                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2235                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2236         }
2237
2238         ibuf->x= rres.rectx;
2239         ibuf->y= rres.recty;
2240         
2241         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
2242                 imb_freerectImBuf(ibuf);
2243
2244         if(rect)
2245                 ibuf->rect= rect;
2246         
2247         if(rectf) {
2248                 ibuf->rect_float= rectf;
2249                 ibuf->flags |= IB_rectfloat;
2250                 ibuf->channels= channels;
2251         }
2252         else {
2253                 ibuf->rect_float= NULL;
2254                 ibuf->flags &= ~IB_rectfloat;
2255         }
2256
2257         if(rectz) {
2258                 ibuf->zbuf_float= rectz;
2259                 ibuf->flags |= IB_zbuffloat;
2260         }
2261         else {
2262                 ibuf->zbuf_float= NULL;
2263                 ibuf->flags &= ~IB_zbuffloat;
2264         }
2265
2266         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2267         ibuf->profile= (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2268
2269         ibuf->dither= dither;
2270
2271         ima->ok= IMA_OK_LOADED;
2272
2273         return ibuf;
2274 }
2275
2276 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2277 {
2278         ImBuf *ibuf = NULL;
2279         int frame = 0, index = 0;
2280
2281         /* see if we already have an appropriate ibuf, with image source and type */
2282         if(ima->source==IMA_SRC_MOVIE) {
2283                 frame= iuser?iuser->framenr:ima->lastframe;
2284                 ibuf= image_get_ibuf(ima, 0, frame);
2285                 /* XXX temp stuff? */
2286                 if(ima->lastframe != frame)
2287                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2288                 ima->lastframe = frame;
2289         }
2290         else if(ima->source==IMA_SRC_SEQUENCE) {
2291                 if(ima->type==IMA_TYPE_IMAGE) {
2292                         frame= iuser?iuser->framenr:ima->lastframe;
2293                         ibuf= image_get_ibuf(ima, 0, frame);
2294                         
2295                         /* XXX temp stuff? */
2296                         if(ima->lastframe != frame) {
2297                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2298                         }
2299                         ima->lastframe = frame;
2300                 }       
2301                 else if(ima->type==IMA_TYPE_MULTILAYER) {
2302                         frame= iuser?iuser->framenr:ima->lastframe;
2303                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2304                         ibuf= image_get_ibuf(ima, index, frame);
2305                 }
2306         }
2307         else if(ima->source==IMA_SRC_FILE) {
2308                 if(ima->type==IMA_TYPE_IMAGE)
2309                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2310                 else if(ima->type==IMA_TYPE_MULTILAYER)
2311                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2312         }
2313         else if(ima->source == IMA_SRC_GENERATED) {
2314                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2315         }
2316         else if(ima->source == IMA_SRC_VIEWER) {
2317                 /* always verify entirely, not that this shouldn't happen
2318                  * as part of texture sampling in rendering anyway, so not
2319                  * a big bottleneck */
2320         }
2321
2322         *frame_r = frame;
2323         *index_r = index;
2324
2325         return ibuf;
2326 }
2327
2328 /* Checks optional ImageUser and verifies/creates ImBuf. */
2329 /* use this one if you want to get a render result in progress,
2330  * if not, use BKE_image_get_ibuf which doesn't require a release */
2331 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2332 {
2333         ImBuf *ibuf= NULL;
2334         float color[] = {0, 0, 0, 1};
2335         int frame= 0, index= 0;
2336
2337         /* This function is intended to be thread-safe. It postpones the mutex lock
2338          * until it needs to load the image, if the image is already there it
2339          * should just get the pointer and return. The reason is that a lot of mutex
2340          * locks appears to be very slow on certain multicore macs, causing a render
2341          * with image textures to actually slow down as more threads are used.
2342          *
2343          * Note that all the image loading functions should also make sure they do
2344          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2345          * That means, the last two steps must be, 1) add the ibuf to the list and
2346          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2347         
2348         if(lock_r)
2349                 *lock_r= NULL;
2350
2351         /* quick reject tests */
2352         if(ima==NULL) 
2353                 return NULL;
2354         if(iuser) {
2355                 if(iuser->ok==0)
2356                         return NULL;
2357         }
2358         else if(ima->ok==0)
2359                 return NULL;
2360         
2361         /* try to get the ibuf without locking */
2362         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2363
2364         if(ibuf == NULL) {
2365                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2366                  * load the image */
2367                 BLI_lock_thread(LOCK_IMAGE);
2368
2369                 /* need to check ok flag and loading ibuf again, because the situation
2370                  * might have changed in the meantime */
2371                 if(iuser) {
2372                         if(iuser->ok==0) {
2373                                 BLI_unlock_thread(LOCK_IMAGE);
2374                                 return NULL;
2375                         }
2376                 }
2377                 else if(ima->ok==0) {
2378                         BLI_unlock_thread(LOCK_IMAGE);
2379                         return NULL;
2380                 }
2381
2382                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2383
2384                 if(ibuf == NULL) {
2385                         /* we are sure we have to load the ibuf, using source and type */
2386                         if(ima->source==IMA_SRC_MOVIE) {
2387                                 /* source is from single file, use flipbook to store ibuf */
2388                                 ibuf= image_load_movie_file(ima, iuser, frame);
2389                         }
2390                         else if(ima->source==IMA_SRC_SEQUENCE) {
2391                                 if(ima->type==IMA_TYPE_IMAGE) {
2392                                         /* regular files, ibufs in flipbook, allows saving */
2393                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2394                                 }
2395                                 /* no else; on load the ima type can change */
2396                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2397                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2398                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2399                                 }
2400                         }
2401                         else if(ima->source==IMA_SRC_FILE) {
2402                                 
2403                                 if(ima->type==IMA_TYPE_IMAGE)
2404                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2405                                 /* no else; on load the ima type can change */
2406                                 if(ima->type==IMA_TYPE_MULTILAYER)
2407                                         /* keeps render result, stores ibufs in listbase, allows saving */
2408                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2409                                         
2410                         }
2411                         else if(ima->source == IMA_SRC_GENERATED) {
2412                                 /* generated is: ibuf is allocated dynamically */
2413                                 /* UV testgrid or black or solid etc */
2414                                 if(ima->gen_x==0) ima->gen_x= 1024;
2415                                 if(ima->gen_y==0) ima->gen_y= 1024;
2416                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2417                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2418                                 ima->ok= IMA_OK_LOADED;
2419                         }
2420                         else if(ima->source == IMA_SRC_VIEWER) {
2421                                 if(ima->type==IMA_TYPE_R_RESULT) {
2422                                         /* always verify entirely, and potentially
2423                                            returns pointer to release later */
2424                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2425                                 }
2426                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2427                                         /* requires lock/unlock, otherwise don't return image */
2428                                         if(lock_r) {
2429                                                 /* unlock in BKE_image_release_ibuf */
2430                                                 BLI_lock_thread(LOCK_VIEWER);
2431                                                 *lock_r= ima;
2432
2433                                                 /* XXX anim play for viewer nodes not yet supported */
2434                                                 frame= 0; // XXX iuser?iuser->framenr:0;
2435                                                 ibuf= image_get_ibuf(ima, 0, frame);
2436
2437                                                 if(!ibuf) {
2438                                                         /* Composite Viewer, all handled in compositor */
2439                                                         /* fake ibuf, will be filled in compositor */
2440                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect);
2441                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2442                                                 }
2443                                         }
2444                                 }
2445                         }
2446                 }
2447
2448                 BLI_unlock_thread(LOCK_IMAGE);
2449         }
2450
2451         tag_image_time(ima);
2452
2453         return ibuf;
2454 }
2455
2456 void BKE_image_release_ibuf(Image *ima, void *lock)
2457 {
2458         /* for getting image during threaded render / compositing, need to release */
2459         if(lock == ima) {
2460                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2461         }
2462         else if(lock) {
2463                 RE_ReleaseResultImage(lock); /* render result */
2464                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2465         }
2466 }
2467
2468 /* warning, this can allocate generated images */
2469 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2470 {
2471         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2472         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2473 }
2474
2475 int BKE_image_user_get_frame(const ImageUser *iuser, int cfra, int fieldnr)
2476 {
2477         const int len= (iuser->fie_ima*iuser->frames)/2;
2478
2479         if(len==0) {
2480                 return 0;
2481         }
2482         else {
2483                 int framenr;
2484                 cfra= cfra - iuser->sfra+1;
2485
2486                 /* cyclic */
2487                 if(iuser->cycl) {
2488                         cfra= ( (cfra) % len );
2489                         if(cfra < 0) cfra+= len;
2490                         if(cfra==0) cfra= len;
2491                 }
2492
2493                 if(cfra<0) cfra= 0;
2494                 else if(cfra>len) cfra= len;
2495
2496                 /* convert current frame to current field */
2497                 cfra= 2*(cfra);
2498                 if(fieldnr) cfra++;
2499
2500                 /* transform to images space */
2501                 framenr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2502                 if(framenr>iuser->frames) framenr= iuser->frames;
2503                 framenr+= iuser->offset;
2504
2505                 if(iuser->cycl) {
2506                         framenr= ( (framenr) % len );
2507                         while(framenr < 0) framenr+= len;
2508                         if(framenr==0) framenr= len;
2509                 }
2510
2511                 return framenr;
2512         }
2513 }
2514
2515 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2516 {
2517         const int framenr= BKE_image_user_get_frame(iuser, cfra, fieldnr);
2518
2519         /* allows image users to handle redraws */
2520         if(iuser->flag & IMA_ANIM_ALWAYS)
2521                 if(framenr!=iuser->framenr)
2522                         iuser->flag |= IMA_ANIM_REFRESHED;
2523
2524         iuser->framenr= framenr;
2525         if(iuser->ok==0) iuser->ok= 1;
2526 }
2527
2528 int BKE_image_has_alpha(struct Image *image)
2529 {
2530         ImBuf *ibuf;
2531         void *lock;
2532         int planes;
2533         
2534         ibuf= BKE_image_acquire_ibuf(image, NULL, &lock);
2535         planes = (ibuf?ibuf->planes:0);
2536         BKE_image_release_ibuf(image, lock);
2537
2538         if (planes == 32)
2539                 return 1;
2540         else
2541                 return 0;
2542 }
2543