Revert last merge from trunk
[blender.git] / source / blender / blenkernel / intern / image.c
1 /*  image.c        
2  * 
3  * $Id$
4  *
5  * ***** BEGIN GPL LICENSE BLOCK *****
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software Foundation,
19  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20  *
21  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
22  * All rights reserved.
23  *
24  * The Original Code is: all of this file.
25  *
26  * Contributor(s): Blender Foundation, 2006
27  *
28  * ***** END GPL LICENSE BLOCK *****
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 #include "MEM_guardedalloc.h"
44
45 #include "IMB_imbuf_types.h"
46 #include "IMB_imbuf.h"
47
48 #ifdef WITH_OPENEXR
49 #include "intern/openexr/openexr_multi.h"
50 #endif
51
52 #include "DNA_image_types.h"
53 #include "DNA_packedFile_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_camera_types.h"
56 #include "DNA_texture_types.h"
57 #include "DNA_userdef_types.h"
58
59 #include "BLI_arithb.h"
60 #include "BLI_blenlib.h"
61 #include "BLI_threads.h"
62
63 #include "BKE_bmfont.h"
64 #include "BKE_global.h"
65 #include "BKE_icons.h"
66 #include "BKE_image.h"
67 #include "BKE_library.h"
68 #include "BKE_main.h"
69 #include "BKE_packedFile.h"
70 #include "BKE_scene.h"
71 #include "BKE_texture.h"
72 #include "BKE_utildefines.h"
73
74 #include "BIF_editseq.h"
75
76 #include "PIL_time.h"
77
78 #include "RE_pipeline.h"
79
80 /* bad level; call to free_realtime_image */
81 #include "BKE_bad_level_calls.h"        
82
83 /* for stamp drawing to an image */
84 #include "BMF_Api.h"
85
86 #include "blendef.h"
87 #include "BSE_time.h"
88
89 #include "BLO_sys_types.h" // for intptr_t support
90
91 /* max int, to indicate we don't store sequences in ibuf */
92 #define IMA_NO_INDEX    0x7FEFEFEF
93
94 /* quick lookup: supports 1 million frames, thousand passes */
95 #define IMA_MAKE_INDEX(frame, index)    ((frame)<<10)+index
96 #define IMA_INDEX_FRAME(index)                  (index>>10)
97
98 /* ******** IMAGE PROCESSING ************* */
99
100 /* used by sequencer and image premul option - IMA_DO_PREMUL */
101 void converttopremul(struct ImBuf *ibuf)
102 {
103         int x, y;
104         
105         if(ibuf==0) return;
106         if (ibuf->rect) {
107                 int val;
108                 char *cp;
109                 if(ibuf->depth==24) {   /* put alpha at 255 */
110                         cp= (char *)(ibuf->rect);
111                         for(y=0; y<ibuf->y; y++) {
112                                 for(x=0; x<ibuf->x; x++, cp+=4) {
113                                         cp[3]= 255;
114                                 }
115                         }
116                 } else {
117                         cp= (char *)(ibuf->rect);
118                         for(y=0; y<ibuf->y; y++) {
119                                 for(x=0; x<ibuf->x; x++, cp+=4) {
120                                         val= cp[3];
121                                         cp[0]= (cp[0]*val)>>8;
122                                         cp[1]= (cp[1]*val)>>8;
123                                         cp[2]= (cp[2]*val)>>8;
124                                 }
125                         }
126                 }
127         }
128         if (ibuf->rect_float) {
129                 float val;
130                 float *cp;
131                 if(ibuf->depth==24) {   /* put alpha at 1.0 */
132                         cp= ibuf->rect_float;;
133                         for(y=0; y<ibuf->y; y++) {
134                                 for(x=0; x<ibuf->x; x++, cp+=4) {
135                                         cp[3]= 1.0;
136                                 }
137                         }
138                 } else {
139                         cp= ibuf->rect_float;
140                         for(y=0; y<ibuf->y; y++) {
141                                 for(x=0; x<ibuf->x; x++, cp+=4) {
142                                         val= cp[3];
143                                         cp[0]= cp[0]*val;
144                                         cp[1]= cp[1]*val;
145                                         cp[2]= cp[2]*val;
146                                 }
147                         }
148                 }
149         }
150 }
151
152 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
153 {
154         struct ImBuf * tbuf1, * tbuf2;
155         
156         if (ibuf == 0) return;
157         if (ibuf->flags & IB_fields) return;
158         ibuf->flags |= IB_fields;
159         
160         if (ibuf->rect) {
161                 /* make copies */
162                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect, (unsigned char)0);
163                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect, (unsigned char)0);
164                 
165                 ibuf->x *= 2;
166                 
167                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
168                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
169                 
170                 ibuf->x /= 2;
171                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
172                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
173                 
174                 IMB_freeImBuf(tbuf1);
175                 IMB_freeImBuf(tbuf2);
176         }
177         ibuf->y /= 2;
178 }
179
180 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
181 {
182         struct ImBuf * tbuf1, * tbuf2;
183         
184         if (ibuf == 0) return;
185         if (ibuf->flags & IB_fields) return;
186         ibuf->flags |= IB_fields;
187         
188         if (ibuf->rect) {
189                 /* make copies */
190                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect, 0);
191                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect, 0);
192                 
193                 ibuf->x *= 2;
194                 
195                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
196                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
197                 
198                 ibuf->x /= 2;
199                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
200                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
201                 
202                 IMB_freeImBuf(tbuf1);
203                 IMB_freeImBuf(tbuf2);
204         }
205         ibuf->y /= 2;
206 }
207
208 void image_de_interlace(Image *ima, int odd)
209 {
210         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
211         if(ibuf) {
212                 if(odd)
213                         de_interlace_st(ibuf);
214                 else
215                         de_interlace_ng(ibuf);
216         }
217 }
218
219 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
220
221 static void image_free_buffers(Image *ima)
222 {
223         ImBuf *ibuf;
224         
225         while((ibuf = ima->ibufs.first)) {
226                 BLI_remlink(&ima->ibufs, ibuf);
227                 
228                 if (ibuf->userdata) {
229                         MEM_freeN(ibuf->userdata);
230                         ibuf->userdata = NULL;
231                 }
232                 IMB_freeImBuf(ibuf);
233         }
234         
235         if(ima->anim) IMB_free_anim(ima->anim);
236         ima->anim= NULL;
237         
238         if(ima->rr) {
239                 RE_FreeRenderResult(ima->rr);
240                 ima->rr= NULL;
241         }       
242         
243         free_realtime_image(ima);
244         
245         ima->ok= IMA_OK;
246 }
247
248 /* called by library too, do not free ima itself */
249 void free_image(Image *ima)
250 {
251         image_free_buffers(ima);
252         if (ima->packedfile) {
253                 freePackedFile(ima->packedfile);
254                 ima->packedfile = NULL;
255         }
256         BKE_icon_delete(&ima->id);
257         ima->id.icon_id = 0;
258         if (ima->preview) {
259                 BKE_previewimg_free(&ima->preview);
260         }
261 }
262
263 /* only image block itself */
264 static Image *image_alloc(const char *name, short source, short type)
265 {
266         Image *ima;
267         
268         ima= alloc_libblock(&G.main->image, ID_IM, name);
269         if(ima) {
270                 ima->ok= IMA_OK;
271                 
272                 ima->xrep= ima->yrep= 1;
273                 ima->aspx= ima->aspy= 1.0;
274                 ima->gen_x= 256; ima->gen_y= 256;
275                 ima->gen_type= 1;       /* no defines yet? */
276                 
277                 ima->source= source;
278                 ima->type= type;
279         }
280         return ima;
281 }
282
283 /* get the ibuf from an image cache, local use here only */
284 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
285 {
286         /* this function is intended to be thread safe. with IMA_NO_INDEX this
287          * should be OK, but when iterating over the list this is more tricky
288          * */
289         if(index==IMA_NO_INDEX)
290                 return ima->ibufs.first;
291         else {
292                 ImBuf *ibuf;
293
294                 index= IMA_MAKE_INDEX(frame, index);
295                 for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
296                         if(ibuf->index==index)
297                                 return ibuf;
298
299                 return NULL;
300         }
301 }
302
303 /* no ima->ibuf anymore, but listbase */
304 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
305 {
306         if(ibuf) {
307                 BLI_remlink(&ima->ibufs, ibuf);
308                 IMB_freeImBuf(ibuf);
309         }
310 }
311
312
313 /* no ima->ibuf anymore, but listbase */
314 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
315 {
316         if(ibuf) {
317                 ImBuf *link;
318                 
319                 if(index!=IMA_NO_INDEX)
320                         index= IMA_MAKE_INDEX(frame, index);
321                 
322                 /* insert based on index */
323                 for(link= ima->ibufs.first; link; link= link->next)
324                         if(link->index>=index)
325                                 break;
326
327                 ibuf->index= index;
328
329                 /* this function accepts link==NULL */
330                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
331
332                 /* now we don't want copies? */
333                 if(link && ibuf->index==link->index)
334                         image_remove_ibuf(ima, link);
335         }
336 }
337
338 /* checks if image was already loaded, then returns same image */
339 /* otherwise creates new. */
340 /* does not load ibuf itself */
341 Image *BKE_add_image_file(const char *name)
342 {
343         Image *ima;
344         int file, len;
345         const char *libname;
346         char str[FILE_MAX], strtest[FILE_MAX];
347         
348         /* escape when name is directory */
349         len= strlen(name);
350         if(len) {
351                 if(name[len-1]=='/' || name[len-1]=='\\')
352                         return NULL;
353         }
354         
355         BLI_strncpy(str, name, sizeof(str));
356         BLI_convertstringcode(str, G.sce);
357         BLI_convertstringframe(str, G.scene->r.cfra); /* TODO - should this realy be here? */
358         
359         /* exists? */
360         file= open(str, O_BINARY|O_RDONLY);
361         if(file== -1) return NULL;
362         close(file);
363         
364         /* first search an identical image */
365         for(ima= G.main->image.first; ima; ima= ima->id.next) {
366                 if(ima->source!=IMA_SRC_VIEWER && ima->source!=IMA_SRC_GENERATED) {
367                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
368                         BLI_convertstringcode(strtest, G.sce);
369                         BLI_convertstringframe(strtest, G.scene->r.cfra); /* TODO - should this be here? */
370                         
371                         if( strcmp(strtest, str)==0 ) {
372                                 if(ima->anim==NULL || ima->id.us==0) {
373                                         BLI_strncpy(ima->name, name, sizeof(ima->name));        /* for stringcode */
374                                         ima->id.us++;                                                                           /* officially should not, it doesn't link here! */
375                                         if(ima->ok==0)
376                                                 ima->ok= IMA_OK;
377                         /* RETURN! */
378                                         return ima;
379                                 }
380                         }
381                 }
382         }
383         /* add new image */
384         
385         /* create a short library name */
386         len= strlen(name);
387         
388         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
389         libname= name+len;
390         
391         ima= image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
392         BLI_strncpy(ima->name, name, sizeof(ima->name));
393         
394         /* do a wild guess! */
395         if(BLI_testextensie(name, ".avi") || BLI_testextensie(name, ".mov")
396                         || BLI_testextensie(name, ".mpg")  || BLI_testextensie(name, ".mp4"))
397                 ima->source= IMA_SRC_MOVIE;
398         
399         return ima;
400 }
401
402 static ImBuf *add_ibuf_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4])
403 {
404         ImBuf *ibuf;
405         float h=0.0, hoffs=0.0, hue=0.0, s=0.9, v=0.9, r, g, b;
406         unsigned char *rect= NULL;
407         float *rect_float= NULL;
408         int x, y;
409         int checkerwidth=21, dark=1;
410         
411         if (floatbuf) {
412                 ibuf= IMB_allocImBuf(width, height, 24, IB_rectfloat, 0);
413                 rect_float= (float*)ibuf->rect_float;
414         }
415         else {
416                 ibuf= IMB_allocImBuf(width, height, 24, IB_rect, 0);
417                 rect= (unsigned char*)ibuf->rect;
418         }
419         
420         strcpy(ibuf->name, "Untitled");
421         ibuf->userflags |= IB_BITMAPDIRTY;
422         
423         if (uvtestgrid) {
424                 /* these two passes could be combined into one, but it's more readable and 
425                 * easy to tweak like this, speed isn't really that much of an issue in this situation... */
426                 
427                 /* checkers */
428                 for(y=0; y<ibuf->y; y++) {
429                         dark = pow(-1, floor(y / checkerwidth));
430                         
431                         for(x=0; x<ibuf->x; x++) {
432                                 if (x % checkerwidth == 0) dark *= -1;
433                                 
434                                 if (floatbuf) {
435                                         if (dark > 0) {
436                                                 rect_float[0] = rect_float[1] = rect_float[2] = 0.25;
437                                                 rect_float[3] = 1.0;
438                                         } else {
439                                                 rect_float[0] = rect_float[1] = rect_float[2] = 0.58;
440                                                 rect_float[3] = 1.0;
441                                         }
442                                         rect_float+=4;
443                                 }
444                                 else {
445                                         if (dark > 0) {
446                                                 rect[0] = rect[1] = rect[2] = 64;
447                                                 rect[3] = 255;
448                                         } else {
449                                                 rect[0] = rect[1] = rect[2] = 150;
450                                                 rect[3] = 255;
451                                         }
452                                         rect += 4;
453                                 }
454                         }
455                 }
456                 
457                 /* 2nd pass, colored + */
458                 if (floatbuf) rect_float= (float*)ibuf->rect_float;
459                 else rect= (unsigned char*)ibuf->rect;
460                 
461                 for(y=0; y<ibuf->y; y++) {
462                         hoffs = 0.125 * floor(y / checkerwidth);
463                         
464                         for(x=0; x<ibuf->x; x++) {
465                                 h = 0.125 * floor(x / checkerwidth);
466                                 
467                                 if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 4) &&
468                                         (fabs((y % checkerwidth) - (checkerwidth / 2)) < 4)) {
469                                         
470                                         if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 1) ||
471                                                 (fabs((y % checkerwidth) - (checkerwidth / 2)) < 1)) {
472                                                 
473                                                 hue = fmod(fabs(h-hoffs), 1.0);
474                                                 hsv_to_rgb(hue, s, v, &r, &g, &b);
475                                                 
476                                                 if (floatbuf) {
477                                                         rect_float[0]= r;
478                                                         rect_float[1]= g;
479                                                         rect_float[2]= b;
480                                                         rect_float[3]= 1.0;
481                                                 }
482                                                 else {
483                                                         rect[0]= (char)(r * 255.0);
484                                                         rect[1]= (char)(g * 255.0);
485                                                         rect[2]= (char)(b * 255.0);
486                                                         rect[3]= 255;
487                                                 }
488                                         }
489                                 }
490
491                                 if (floatbuf)
492                                         rect_float+=4;
493                                 else
494                                         rect+=4;
495                         }
496                 }
497         } else {        /* blank image */
498                 for(y=0; y<ibuf->y; y++) {
499                         for(x=0; x<ibuf->x; x++) {
500                                 if (floatbuf) {
501                                         rect_float[0]= color[0];
502                                         rect_float[1]= color[1];
503                                         rect_float[2]= color[2];
504                                         rect_float[3]= color[3];
505                                         rect_float+=4;
506                                 }
507                                 else {
508                                         rect[0]= (char)(color[0] * 255.0);
509                                         rect[1]= (char)(color[1] * 255.0);
510                                         rect[2]= (char)(color[2] * 255.0);
511                                         rect[3]= (char)(color[3] * 255.0);
512                                         rect+=4;
513                                 }
514                         }
515                 }
516         }
517         return ibuf;
518 }
519
520 /* adds new image block, creates ImBuf and initializes color */
521 Image *BKE_add_image_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4])
522 {
523         Image *ima;
524         
525         /* on save, type is changed to FILE in editsima.c */
526         ima= image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
527         
528         if (ima) {
529                 ImBuf *ibuf;
530                 
531                 BLI_strncpy(ima->name, name, FILE_MAX);
532                 ima->gen_x= width;
533                 ima->gen_y= height;
534                 ima->gen_type= uvtestgrid;
535                 
536                 ibuf= add_ibuf_size(width, height, name, floatbuf, uvtestgrid, color);
537                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
538                 
539                 ima->ok= IMA_OK_LOADED;
540         }
541
542         return ima;
543 }
544
545 /* packs rect from memory as PNG */
546 void BKE_image_memorypack(Image *ima)
547 {
548         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
549         
550         if(ibuf==NULL)
551                 return;
552         if (ima->packedfile) {
553                 freePackedFile(ima->packedfile);
554                 ima->packedfile = NULL;
555         }
556         
557         ibuf->ftype= PNG;
558         ibuf->depth= 32;
559         
560         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
561         if(ibuf->encodedbuffer==NULL) {
562                 printf("memory save for pack error\n");
563         }
564         else {
565                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
566                 
567                 pf->data = ibuf->encodedbuffer;
568                 pf->size = ibuf->encodedsize;
569                 ima->packedfile= pf;
570                 ibuf->encodedbuffer= NULL;
571                 ibuf->encodedsize= 0;
572                 ibuf->userflags &= ~IB_BITMAPDIRTY;
573                 
574                 if(ima->source==IMA_SRC_GENERATED) {
575                         ima->source= IMA_SRC_FILE;
576                         ima->type= IMA_TYPE_IMAGE;
577                 }
578         }
579 }
580
581 void tag_image_time(Image *ima)
582 {
583         if (ima)
584                 ima->lastused = (int)PIL_check_seconds_timer();
585 }
586
587 void tag_all_images_time() 
588 {
589         Image *ima;
590         int ctime = (int)PIL_check_seconds_timer();
591
592         ima= G.main->image.first;
593         while(ima) {
594                 if(ima->bindcode || ima->repbind || ima->ibufs.first) {
595                         ima->lastused = ctime;
596                 }
597         }
598 }
599
600 void free_old_images()
601 {
602         Image *ima;
603         static int lasttime = 0;
604         int ctime = (int)PIL_check_seconds_timer();
605         
606         /* 
607            Run garbage collector once for every collecting period of time 
608            if textimeout is 0, that's the option to NOT run the collector
609         */
610         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
611                 return;
612
613         lasttime = ctime;
614
615         ima= G.main->image.first;
616         while(ima) {
617                 if((ima->flag & IMA_NOCOLLECT)==0 && ctime - ima->lastused > U.textimeout) {
618                         /*
619                            If it's in GL memory, deallocate and set time tag to current time
620                            This gives textures a "second chance" to be used before dying.
621                         */
622                         if(ima->bindcode || ima->repbind) {
623                                 free_realtime_image(ima);
624                                 ima->lastused = ctime;
625                         }
626                         /* Otherwise, just kill the buffers */
627                         else if (ima->ibufs.first) {
628                                 image_free_buffers(ima);
629                         }
630                 }
631                 ima = ima->id.next;
632         }
633 }
634
635 static uintptr_t image_mem_size(Image *ima)
636 {
637         ImBuf *ibuf, *ibufm;
638         int level;
639         uintptr_t size = 0;
640
641         size= 0;
642         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
643                 if(ibuf->rect) size += MEM_allocN_len(ibuf->rect);
644                 else if(ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
645
646                 for(level=0; level<IB_MIPMAP_LEVELS; level++) {
647                         ibufm= ibuf->mipmap[level];
648                         if(ibufm) {
649                                 if(ibufm->rect) size += MEM_allocN_len(ibufm->rect);
650                                 else if(ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
651                         }
652                 }
653         }
654
655         return size;
656 }
657
658 void BKE_image_print_memlist(void)
659 {
660         Image *ima;
661         uintptr_t size, totsize= 0;
662
663         for(ima= G.main->image.first; ima; ima= ima->id.next)
664                 totsize += image_mem_size(ima);
665
666         printf("\ntotal image memory len: %.3lf MB\n", (double)totsize/(double)(1024*1024));
667
668         for(ima= G.main->image.first; ima; ima= ima->id.next) {
669                 size= image_mem_size(ima);
670
671                 if(size)
672                         printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
673         }
674 }
675
676 void BKE_image_free_all_textures(void)
677 {
678         Tex *tex;
679         Image *ima;
680         unsigned int totsize= 0;
681         
682         for(ima= G.main->image.first; ima; ima= ima->id.next)
683                 ima->id.flag &= ~LIB_DOIT;
684         
685         for(tex= G.main->tex.first; tex; tex= tex->id.next)
686                 if(tex->ima)
687                         tex->ima->id.flag |= LIB_DOIT;
688         
689         for(ima= G.main->image.first; ima; ima= ima->id.next) {
690                 if(ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
691                         ImBuf *ibuf;
692                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
693                                 if(ibuf->mipmap[0]) 
694                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
695                                 else
696                                         totsize+= ibuf->x*ibuf->y*4;
697                         }
698                         image_free_buffers(ima);
699                 }
700         }
701         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
702 }
703
704 /* except_frame is weak, only works for seqs without offset... */
705 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
706 {
707         ImBuf *ibuf, *nbuf;
708
709         for(ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
710                 nbuf= ibuf->next;
711                 if(ibuf->userflags & IB_BITMAPDIRTY)
712                         continue;
713                 if(ibuf->index==IMA_NO_INDEX)
714                         continue;
715                 if(except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
716                         BLI_remlink(&ima->ibufs, ibuf);
717                         
718                         if (ibuf->userdata) {
719                                 MEM_freeN(ibuf->userdata);
720                                 ibuf->userdata = NULL;
721                         }
722                         IMB_freeImBuf(ibuf);
723                 }                                       
724         }
725 }
726
727 void BKE_image_all_free_anim_ibufs(int cfra)
728 {
729         Image *ima;
730         
731         for(ima= G.main->image.first; ima; ima= ima->id.next)
732                 if(ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
733                         BKE_image_free_anim_ibufs(ima, cfra);
734 }
735
736
737 /* *********** READ AND WRITE ************** */
738
739 int BKE_imtype_to_ftype(int imtype)
740 {
741         if(imtype==0)
742                 return TGA;
743         else if(imtype== R_IRIS) 
744                 return IMAGIC;
745         else if (imtype==R_RADHDR)
746                 return RADHDR;
747         else if (imtype==R_PNG)
748                 return PNG;
749 #ifdef WITH_DDS
750         else if (imtype==R_DDS)
751                 return DDS;
752 #endif
753         else if (imtype==R_BMP)
754                 return BMP;
755         else if (imtype==R_TIFF)
756                 return TIF;
757         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER)
758                 return OPENEXR;
759         else if (imtype==R_CINEON)
760                 return CINEON;
761         else if (imtype==R_DPX)
762                 return DPX;
763         else if (imtype==R_TARGA)
764                 return TGA;
765         else if(imtype==R_RAWTGA)
766                 return RAWTGA;
767         else if(imtype==R_HAMX)
768                 return AN_hamx;
769         else
770                 return JPG|90;
771 }
772
773 int BKE_ftype_to_imtype(int ftype)
774 {
775         if(ftype==0)
776                 return TGA;
777         else if(ftype == IMAGIC) 
778                 return R_IRIS;
779         else if (ftype & RADHDR)
780                 return R_RADHDR;
781         else if (ftype & PNG)
782                 return R_PNG;
783 #ifdef WITH_DDS
784         else if (ftype & DDS)
785                 return R_DDS;
786 #endif
787         else if (ftype & BMP)
788                 return R_BMP;
789         else if (ftype & TIF)
790                 return R_TIFF;
791         else if (ftype & OPENEXR)
792                 return R_OPENEXR;
793         else if (ftype & CINEON)
794                 return R_CINEON;
795         else if (ftype & DPX)
796                 return R_DPX;
797         else if (ftype & TGA)
798                 return R_TARGA;
799         else if(ftype & RAWTGA)
800                 return R_RAWTGA;
801         else if(ftype == AN_hamx)
802                 return R_HAMX;
803         else
804                 return R_JPEG90;
805 }
806
807
808 int BKE_imtype_is_movie(int imtype)
809 {
810         switch(imtype) {
811         case R_MOVIE:
812         case R_AVIRAW:
813         case R_AVIJPEG:
814         case R_AVICODEC:
815         case R_QUICKTIME:
816         case R_FFMPEG:
817         case R_FRAMESERVER:
818                         return 1;
819         }
820         return 0;
821 }
822
823 void BKE_add_image_extension(char *string, int imtype)
824 {
825         char *extension="";
826         
827         if(G.scene->r.imtype== R_IRIS) {
828                 if(!BLI_testextensie(string, ".rgb"))
829                         extension= ".rgb";
830         }
831         else if(imtype==R_IRIZ) {
832                 if(!BLI_testextensie(string, ".rgb"))
833                         extension= ".rgb";
834         }
835         else if(imtype==R_RADHDR) {
836                 if(!BLI_testextensie(string, ".hdr"))
837                         extension= ".hdr";
838         }
839         else if(imtype==R_PNG || imtype==R_FFMPEG) {
840                 if(!BLI_testextensie(string, ".png"))
841                         extension= ".png";
842         }
843 #ifdef WITH_DDS
844         else if(imtype==R_DDS) {
845                 if(!BLI_testextensie(string, ".dds"))
846                         extension= ".dds";
847         }
848 #endif
849         else if(imtype==R_RAWTGA) {
850                 if(!BLI_testextensie(string, ".tga"))
851                         extension= ".tga";
852         }
853         else if(imtype==R_BMP) {
854                 if(!BLI_testextensie(string, ".bmp"))
855                         extension= ".bmp";
856         }
857         else if(G.have_libtiff && (imtype==R_TIFF)) {
858                 if(!BLI_testextensie(string, ".tif") && 
859                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
860         }
861 #ifdef WITH_OPENEXR
862         else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
863                 if(!BLI_testextensie(string, ".exr"))
864                         extension= ".exr";
865         }
866 #endif
867         else if(imtype==R_CINEON){
868                 if (!BLI_testextensie(string, ".cin"))
869                         extension= ".cin";
870         }
871         else if(imtype==R_DPX){
872                 if (!BLI_testextensie(string, ".dpx"))
873                         extension= ".dpx";
874         }
875         else if(imtype==R_TARGA) {
876                 if(!BLI_testextensie(string, ".tga"))
877                         extension= ".tga";
878         }
879         else { //   R_MOVIE, R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90, R_QUICKTIME etc
880                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
881                         extension= ".jpg";
882         }
883
884         strcat(string, extension);
885 }
886
887 /* could allow access externally - 512 is for long names, 64 is for id names */
888 typedef struct StampData {
889         char    file[512];
890         char    note[512];
891         char    date[512];
892         char    marker[512];
893         char    time[512];
894         char    frame[512];
895         char    camera[64];
896         char    scene[64];
897         char    strip[64];
898 } StampData;
899
900 static void stampdata(StampData *stamp_data, int do_prefix)
901 {
902         char text[256];
903         
904 #ifndef WIN32
905         struct tm *tl;
906         time_t t;
907 #else
908         char sdate[9];
909 #endif /* WIN32 */
910         
911         if (G.scene->r.stamp & R_STAMP_FILENAME) {
912                 if (G.relbase_valid) {
913                         if (do_prefix)          sprintf(stamp_data->file, "File %s", G.sce);
914                         else                            sprintf(stamp_data->file, "%s", G.sce);
915                 } else {
916                         if (do_prefix)          strcpy(stamp_data->file, "File <untitled>");
917                         else                            strcpy(stamp_data->file, "<untitled>");
918                 }
919                 stamp_data->note[0] = '\0';
920         } else {
921                 stamp_data->file[0] = '\0';
922         }
923         
924         if (G.scene->r.stamp & R_STAMP_NOTE) {
925                 /* Never do prefix for Note */
926                 sprintf(stamp_data->note, "%s", G.scene->r.stamp_udata);
927         } else {
928                 stamp_data->note[0] = '\0';
929         }
930         
931         if (G.scene->r.stamp & R_STAMP_DATE) {
932 #ifdef WIN32
933                 _strdate (sdate);
934                 sprintf (text, "%s", sdate);
935 #else
936                 t = time (NULL);
937                 tl = localtime (&t);
938                 sprintf (text, "%04d-%02d-%02d", tl->tm_year+1900, tl->tm_mon+1, tl->tm_mday);
939 #endif /* WIN32 */
940                 if (do_prefix)          sprintf(stamp_data->date, "Date %s", text);
941                 else                            sprintf(stamp_data->date, "%s", text);
942         } else {
943                 stamp_data->date[0] = '\0';
944         }
945         
946         if (G.scene->r.stamp & R_STAMP_MARKER) {
947                 TimeMarker *marker = get_frame_marker(CFRA);
948         
949                 if (marker) strcpy(text, marker->name);
950                 else            strcpy(text, "<none>");
951                 
952                 if (do_prefix)          sprintf(stamp_data->marker, "Marker %s", text);
953                 else                            sprintf(stamp_data->marker, "%s", text);
954         } else {
955                 stamp_data->marker[0] = '\0';
956         }
957         
958         if (G.scene->r.stamp & R_STAMP_TIME) {
959                 int h, m, s, f;
960                 h= m= s= f= 0;
961                 f = (int)(G.scene->r.cfra % G.scene->r.frs_sec);
962                 s = (int)(G.scene->r.cfra / G.scene->r.frs_sec);
963
964                 if (s) {
965                         m = (int)(s / 60);
966                         s %= 60;
967
968                         if (m) {
969                                 h = (int)(m / 60);
970                                 m %= 60;
971                         }
972                 }
973
974                 if (G.scene->r.frs_sec < 100)
975                         sprintf (text, "%02d:%02d:%02d.%02d", h, m, s, f);
976                 else
977                         sprintf (text, "%02d:%02d:%02d.%03d", h, m, s, f);
978                 
979                 if (do_prefix)          sprintf(stamp_data->time, "Time %s", text);
980                 else                            sprintf(stamp_data->time, "%s", text);
981         } else {
982                 stamp_data->time[0] = '\0';
983         }
984         
985         if (G.scene->r.stamp & R_STAMP_FRAME) {
986                 char format[32];
987                 if (do_prefix)          sprintf(format, "Frame %%0%di\n", 1 + (int) log10(G.scene->r.efra));
988                 else                            sprintf(format, "%%0%di\n", 1 + (int) log10(G.scene->r.efra));
989                 sprintf (stamp_data->frame, format, G.scene->r.cfra);
990         } else {
991                 stamp_data->frame[0] = '\0';
992         }
993
994         if (G.scene->r.stamp & R_STAMP_CAMERA) {
995                 if (G.scene->camera) strcpy(text, ((Camera *) G.scene->camera)->id.name+2);
996                 else            strcpy(text, "<none>");
997                 
998                 if (do_prefix)          sprintf(stamp_data->camera, "Camera %s", text);
999                 else                            sprintf(stamp_data->camera, "%s", text);
1000         } else {
1001                 stamp_data->camera[0] = '\0';
1002         }
1003
1004         if (G.scene->r.stamp & R_STAMP_SCENE) {
1005                 if (do_prefix)          sprintf(stamp_data->scene, "Scene %s", G.scene->id.name+2);
1006                 else                            sprintf(stamp_data->scene, "%s", G.scene->id.name+2);
1007         } else {
1008                 stamp_data->scene[0] = '\0';
1009         }
1010         
1011         if (G.scene->r.stamp & R_STAMP_SEQSTRIP) {
1012                 Sequence *seq = get_forground_frame_seq(CFRA);
1013         
1014                 if (seq) strcpy(text, seq->name+2);
1015                 else            strcpy(text, "<none>");
1016                 
1017                 if (do_prefix)          sprintf(stamp_data->strip, "Strip %s", text);
1018                 else                            sprintf(stamp_data->strip, "%s", text);
1019         } else {
1020                 stamp_data->strip[0] = '\0';
1021         }
1022 }
1023
1024 void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height, int channels)
1025 {
1026         struct StampData stamp_data;
1027         
1028         int x=1,y=1;
1029         int font_height;
1030         int text_width;
1031         int text_pad;
1032         struct BMF_Font *font;
1033         
1034         if (!rect && !rectf)
1035                 return;
1036         
1037         stampdata(&stamp_data, 1);
1038         
1039         switch (G.scene->r.stamp_font_id) {
1040         case 1: /* tiny */
1041                 font = BMF_GetFont(BMF_kHelveticaBold8);
1042                 break;
1043         case 2: /* small */
1044                 font = BMF_GetFont(BMF_kHelveticaBold10);
1045                 break;
1046         case 3: /* medium */
1047                 font = BMF_GetFont(BMF_kScreen12);
1048                 break;
1049         case 0: /* large - default */
1050                 font = BMF_GetFont(BMF_kScreen15);
1051                 break;
1052         case 4: /* huge */
1053                 font = BMF_GetFont(BMF_kHelveticaBold14);
1054                 break;
1055         default:
1056                 font = NULL;
1057                 break;
1058         }
1059         
1060         font_height = BMF_GetFontHeight(font);
1061         /* All texts get halfspace+1 pixel on each side and 1 pix
1062         above and below as padding against their backing rectangles */
1063         text_pad = BMF_GetStringWidth(font, " ");
1064         
1065         x = 1; /* Inits for everyone, text position, so 1 for padding, not 0 */
1066         y = height - font_height - 1; /* Also inits for everyone, notice padding pixel */
1067         
1068         if (stamp_data.file[0]) {
1069                 /* Top left corner */
1070                 text_width = BMF_GetStringWidth(font, stamp_data.file);
1071                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1072                 BMF_DrawStringBuf(font, stamp_data.file, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1073                 y -= font_height+2; /* Top and bottom 1 pix padding each */
1074         }
1075
1076         /* Top left corner, below File */
1077         if (stamp_data.note[0]) {
1078                 text_width = BMF_GetStringWidth(font, stamp_data.note);
1079                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1080                 BMF_DrawStringBuf(font, stamp_data.note, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1081                 y -= font_height+2; /* Top and bottom 1 pix padding each */
1082         }
1083         
1084         /* Top left corner, below File (or Note) */
1085         if (stamp_data.date[0]) {
1086                 text_width = BMF_GetStringWidth(font, stamp_data.date);
1087                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1088                 BMF_DrawStringBuf(font, stamp_data.date, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1089         }
1090
1091         /* Bottom left corner, leaving space for timing */
1092         if (stamp_data.marker[0]) {
1093                 x = 1;
1094                 y = font_height+2+1; /* 2 for padding in TIME|FRAME fields below and 1 for padding in this one */
1095                 text_width = BMF_GetStringWidth(font, stamp_data.marker);
1096                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1097                 BMF_DrawStringBuf(font, stamp_data.marker, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1098         }
1099         
1100         /* Left bottom corner */
1101         if (stamp_data.time[0]) {
1102                 x = 1;
1103                 y = 1;
1104                 text_width = BMF_GetStringWidth(font, stamp_data.time);
1105                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1106                 BMF_DrawStringBuf(font, stamp_data.time, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1107                 x += text_width+text_pad+2; /* Both sides have 1 pix additional padding each */
1108         }
1109         
1110         if (stamp_data.frame[0]) {
1111                 text_width = BMF_GetStringWidth(font, stamp_data.frame);
1112                 /* Left bottom corner (after SMPTE if exists) */
1113                 if (!stamp_data.time[0])        x = 1;
1114                 y = 1;
1115                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1116                 BMF_DrawStringBuf(font, stamp_data.frame, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1117         }
1118
1119         if (stamp_data.camera[0]) {
1120                 text_width = BMF_GetStringWidth(font, stamp_data.camera);
1121                 /* Center of bottom edge */
1122                 x = (width/2) - (BMF_GetStringWidth(font, stamp_data.camera)/2);
1123                 y = 1;
1124                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1125                 BMF_DrawStringBuf(font, stamp_data.camera, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1126         }
1127         
1128         if (stamp_data.scene[0]) {
1129                 text_width = BMF_GetStringWidth(font, stamp_data.scene);
1130                 /* Bottom right corner */
1131                 x = width - (text_width+1+text_pad);
1132                 y = 1;
1133                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1134                 BMF_DrawStringBuf(font, stamp_data.scene, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1135         }
1136         
1137         if (stamp_data.strip[0]) {
1138                 text_width = BMF_GetStringWidth(font, stamp_data.strip);
1139                 /* Top right corner */
1140                 x = width - (text_width+1+text_pad);
1141                 y = height - font_height - 1;
1142                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1143                 BMF_DrawStringBuf(font, stamp_data.strip, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1144         }
1145         
1146 }
1147
1148 void BKE_stamp_info(struct ImBuf *ibuf)
1149 {
1150         struct StampData stamp_data;
1151
1152         if (!ibuf)      return;
1153         
1154         /* fill all the data values, no prefix */
1155         stampdata(&stamp_data, 0);
1156         
1157         if (stamp_data.file[0])         IMB_imginfo_change_field (ibuf, "File",         stamp_data.file);
1158         if (stamp_data.note[0])         IMB_imginfo_change_field (ibuf, "Note",         stamp_data.note);
1159         if (stamp_data.date[0])         IMB_imginfo_change_field (ibuf, "Date",         stamp_data.date);
1160         if (stamp_data.marker[0])       IMB_imginfo_change_field (ibuf, "Marker",       stamp_data.marker);
1161         if (stamp_data.time[0])         IMB_imginfo_change_field (ibuf, "Time",         stamp_data.time);
1162         if (stamp_data.frame[0])        IMB_imginfo_change_field (ibuf, "Frame",        stamp_data.frame);
1163         if (stamp_data.camera[0])       IMB_imginfo_change_field (ibuf, "Camera",       stamp_data.camera);
1164         if (stamp_data.scene[0])        IMB_imginfo_change_field (ibuf, "Scene",        stamp_data.scene);
1165         if (stamp_data.strip[0])        IMB_imginfo_change_field (ibuf, "Strip",        stamp_data.strip);
1166 }
1167
1168 int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
1169 {
1170         int ok;
1171         
1172         if(imtype==0);
1173         else if(imtype== R_IRIS) 
1174                 ibuf->ftype= IMAGIC;
1175         else if ((imtype==R_RADHDR)) {
1176                 ibuf->ftype= RADHDR;
1177         }
1178         else if (imtype==R_PNG || imtype==R_FFMPEG) {
1179                 ibuf->ftype= PNG;
1180         }
1181 #ifdef WITH_DDS
1182         else if ((imtype==R_DDS)) {
1183                 ibuf->ftype= DDS;
1184         }
1185 #endif
1186         else if ((imtype==R_BMP)) {
1187                 ibuf->ftype= BMP;
1188         }
1189         else if ((G.have_libtiff) && (imtype==R_TIFF)) {
1190                 ibuf->ftype= TIF;
1191
1192                 if(subimtype & R_TIFF_16BIT)
1193                         ibuf->ftype |= TIF_16BIT;
1194         }
1195 #ifdef WITH_OPENEXR
1196         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1197                 ibuf->ftype= OPENEXR;
1198                 if(subimtype & R_OPENEXR_HALF)
1199                         ibuf->ftype |= OPENEXR_HALF;
1200                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1201                 
1202                 if(!(subimtype & R_OPENEXR_ZBUF))
1203                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1204                 
1205         }
1206 #endif
1207         else if (imtype==R_CINEON) {
1208                 ibuf->ftype = CINEON;
1209         }
1210         else if (imtype==R_DPX) {
1211                 ibuf->ftype = DPX;
1212         }
1213         else if (imtype==R_TARGA) {
1214                 ibuf->ftype= TGA;
1215         }
1216         else if(imtype==R_RAWTGA) {
1217                 ibuf->ftype= RAWTGA;
1218         }
1219         else if(imtype==R_HAMX) {
1220                 ibuf->ftype= AN_hamx;
1221         }
1222         else {
1223                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
1224                 if(quality < 10) quality= 90;
1225                 ibuf->ftype= JPG|quality;
1226                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1227         }
1228         
1229         BLI_make_existing_file(name);
1230
1231         if(G.scene->r.scemode & R_STAMP_INFO)
1232                 BKE_stamp_info(ibuf);
1233         
1234         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1235         if (ok == 0) {
1236                 perror(name);
1237         }
1238         
1239         return(ok);
1240 }
1241
1242
1243 void BKE_makepicstring(char *string, char *base, int frame, int imtype)
1244 {
1245         if (string==NULL) return;
1246
1247         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1248         
1249         /* if we dont have any #'s to insert numbers into, use 4 numbers by default */
1250         if (strchr(string, '#')==NULL)
1251                 strcat(string, "####"); /* 4 numbers */
1252         
1253         BLI_convertstringcode(string, G.sce);
1254         BLI_convertstringframe(string, frame);
1255
1256         if(G.scene->r.scemode & R_EXTENSION) 
1257                 BKE_add_image_extension(string, imtype);
1258                 
1259 }
1260
1261 /* used by sequencer too */
1262 struct anim *openanim(char *name, int flags)
1263 {
1264         struct anim *anim;
1265         struct ImBuf *ibuf;
1266         
1267         anim = IMB_open_anim(name, flags);
1268         if (anim == NULL) return(0);
1269
1270         ibuf = IMB_anim_absolute(anim, 0);
1271         if (ibuf == NULL) {
1272                 printf("not an anim; %s\n", name);
1273                 IMB_free_anim(anim);
1274                 return(0);
1275         }
1276         IMB_freeImBuf(ibuf);
1277         
1278         return(anim);
1279 }
1280
1281 /* ************************* New Image API *************** */
1282
1283
1284 /* Notes about Image storage 
1285 - packedfile
1286   -> written in .blend
1287 - filename
1288   -> written in .blend
1289 - movie
1290   -> comes from packedfile or filename
1291 - renderresult
1292   -> comes from packedfile or filename
1293 - listbase
1294   -> ibufs from exrhandle
1295 - flipbook array
1296   -> ibufs come from movie, temporary renderresult or sequence
1297 - ibuf
1298   -> comes from packedfile or filename or generated
1299
1300 */
1301
1302
1303 /* forces existance of 1 Image for renderout or nodes, returns Image */
1304 /* name is only for default, when making new one */
1305 Image *BKE_image_verify_viewer(int type, const char *name)
1306 {
1307         Image *ima;
1308         
1309         for(ima=G.main->image.first; ima; ima= ima->id.next)
1310                 if(ima->source==IMA_SRC_VIEWER)
1311                         if(ima->type==type)
1312                                 break;
1313         
1314         if(ima==NULL)
1315                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1316         
1317         /* happens on reload, imagewindow cannot be image user when hidden*/
1318         if(ima->id.us==0)
1319                 id_us_plus(&ima->id);
1320
1321         return ima;
1322 }
1323
1324 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1325 {
1326         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1327 }
1328
1329 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1330 {
1331         if(ima==NULL)
1332                 return;
1333         
1334         switch(signal) {
1335         case IMA_SIGNAL_FREE:
1336                 image_free_buffers(ima);
1337                 if(iuser)
1338                         iuser->ok= 1;
1339                 break;
1340         case IMA_SIGNAL_SRC_CHANGE:
1341                 if(ima->type==IMA_TYPE_MULTILAYER)
1342                         image_free_buffers(ima);
1343                 else if(ima->source==IMA_SRC_GENERATED) {
1344                         if(ima->gen_x==0 || ima->gen_y==0) {
1345                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1346                                 if(ibuf) {
1347                                         ima->gen_x= ibuf->x;
1348                                         ima->gen_y= ibuf->y;
1349                                 }
1350                         }
1351                 }
1352                 ima->ok= 1;
1353                 if(iuser)
1354                         iuser->ok= 1;
1355                 break;
1356                         
1357         case IMA_SIGNAL_RELOAD:
1358                 /* try to repack file */
1359                 if(ima->packedfile) {
1360                         PackedFile *pf;
1361                         pf = newPackedFile(ima->name);
1362                         if (pf) {
1363                                 freePackedFile(ima->packedfile);
1364                                 ima->packedfile = pf;
1365                                 image_free_buffers(ima);
1366                         } else {
1367                                 printf("ERROR: Image not available. Keeping packed image\n");
1368                         }
1369                 }
1370                 else
1371                         image_free_buffers(ima);
1372                 
1373                 if(iuser)
1374                         iuser->ok= 1;
1375                 
1376                 break;
1377         case IMA_SIGNAL_USER_NEW_IMAGE:
1378                 if(iuser) {
1379                         iuser->ok= 1;
1380                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1381                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1382                                         iuser->multi_index= 0;
1383                                         iuser->layer= iuser->pass= 0;
1384                                 }
1385                         }
1386                 }
1387                 break;
1388         }
1389 }
1390
1391 /* if layer or pass changes, we need an index for the imbufs list */
1392 /* note it is called for rendered results, but it doesnt use the index! */
1393 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1394 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1395 {
1396         RenderLayer *rl;
1397         RenderPass *rpass= NULL;
1398         
1399         if(rr==NULL) 
1400                 return NULL;
1401         
1402         if(iuser) {
1403                 short index= 0, rl_index= 0, rp_index;
1404                 
1405                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1406                         rp_index= 0;
1407                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1408                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1409                                         break;
1410                         if(rpass)
1411                                 break;
1412                 }
1413                 
1414                 if(rpass)
1415                         iuser->multi_index= index;
1416                 else 
1417                         iuser->multi_index= 0;
1418         }
1419         if(rpass==NULL) {
1420                 rl= rr->layers.first;
1421                 if(rl)
1422                         rpass= rl->passes.first;
1423         }
1424         
1425         return rpass;
1426 }
1427
1428 RenderResult *BKE_image_get_renderresult(Image *ima)
1429 {
1430         if(ima->rr)
1431                 return ima->rr;
1432         if(ima->type==IMA_TYPE_R_RESULT)
1433                 return RE_GetResult(RE_GetRender(G.scene->id.name));
1434         return NULL;
1435 }
1436
1437 /* after imbuf load, openexr type can return with a exrhandle open */
1438 /* in that case we have to build a render-result */
1439 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1440 {
1441         
1442         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1443
1444 #ifdef WITH_OPENEXR
1445         IMB_exr_close(ibuf->userdata);
1446 #endif
1447
1448         ibuf->userdata= NULL;
1449         if(ima->rr)
1450                 ima->rr->framenr= framenr;
1451 }
1452
1453 /* common stuff to do with images after loading */
1454 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1455 {
1456         
1457         
1458         /* preview is NULL when it has never been used as an icon before */
1459         if(G.background==0 && ima->preview==NULL)
1460                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1461         
1462         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1463         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1464         
1465         /* fields */
1466         if (ima->flag & IMA_FIELDS) {
1467                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1468                 else de_interlace_ng(ibuf);
1469         }
1470         /* timer */
1471         ima->lastused = clock() / CLOCKS_PER_SEC;
1472         
1473         ima->ok= IMA_OK_LOADED;
1474         
1475 }
1476
1477 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1478 {
1479         struct ImBuf *ibuf;
1480         unsigned short numlen;
1481         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1482         
1483         ima->lastframe= frame;
1484
1485         BLI_stringdec(ima->name, head, tail, &numlen);
1486         BLI_stringenc(ima->name, head, tail, numlen, frame);
1487         BLI_strncpy(name, ima->name, sizeof(name));
1488         
1489         if(ima->id.lib)
1490                 BLI_convertstringcode(name, ima->id.lib->filename);
1491         else
1492                 BLI_convertstringcode(name, G.sce);
1493         
1494         BLI_convertstringframe(name, frame); /* TODO - should this be here? */
1495         
1496         /* read ibuf */
1497         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1498         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1499         
1500         if (ibuf) {
1501 #ifdef WITH_OPENEXR
1502                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1503                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1504                         image_create_multilayer(ima, ibuf, frame);      
1505                         ima->type= IMA_TYPE_MULTILAYER;
1506                         IMB_freeImBuf(ibuf);
1507                         ibuf= NULL;
1508                 }
1509                 else {
1510                         image_initialize_after_load(ima, ibuf);
1511                         image_assign_ibuf(ima, ibuf, 0, frame);
1512                 }
1513 #else
1514                 image_initialize_after_load(ima, ibuf);
1515                 image_assign_ibuf(ima, ibuf, 0, frame);
1516 #endif
1517                 
1518                 if(ima->flag & IMA_DO_PREMUL)
1519                         converttopremul(ibuf);
1520                 
1521         }
1522         else
1523                 ima->ok= 0;
1524         
1525         if(iuser)
1526                 iuser->ok= ima->ok;
1527         
1528         return ibuf;
1529 }
1530
1531 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1532 {
1533         struct ImBuf *ibuf= NULL;
1534         
1535         /* either we load from RenderResult, or we have to load a new one */
1536         
1537         /* check for new RenderResult */
1538         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1539                 /* copy to survive not found multilayer image */
1540                 RenderResult *oldrr= ima->rr;
1541         
1542                 ima->rr= NULL;
1543                 ibuf = image_load_sequence_file(ima, iuser, frame);
1544                 
1545                 if(ibuf) { /* actually an error */
1546                         ima->type= IMA_TYPE_IMAGE;
1547                         printf("error, multi is normal image\n");
1548                 }
1549                 // printf("loaded new result %p\n", ima->rr);
1550                 /* free result if new one found */
1551                 if(ima->rr) {
1552                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1553                         if(oldrr) RE_FreeRenderResult(oldrr);
1554                 }
1555                 else {
1556                         ima->rr= oldrr;
1557                 }
1558
1559         }
1560         if(ima->rr) {
1561                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1562                 
1563                 if(rpass) {
1564                         // printf("load from pass %s\n", rpass->name);
1565                         /* since we free  render results, we copy the rect */
1566                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1567                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1568                         ibuf->flags |= IB_rectfloat;
1569                         ibuf->mall= IB_rectfloat;
1570                         ibuf->channels= rpass->channels;
1571                         
1572                         image_initialize_after_load(ima, ibuf);
1573                         image_assign_ibuf(ima, ibuf, iuser->multi_index, frame);
1574                         
1575                 }
1576                 // else printf("pass not found\n");
1577         }
1578         else
1579                 ima->ok= 0;
1580         
1581         if(iuser)
1582                 iuser->ok= ima->ok;
1583         
1584         return ibuf;
1585 }
1586
1587
1588 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1589 {
1590         struct ImBuf *ibuf= NULL;
1591         
1592         ima->lastframe= frame;
1593         
1594         if(ima->anim==NULL) {
1595                 char str[FILE_MAX];
1596                 
1597                 BLI_strncpy(str, ima->name, FILE_MAX);
1598                 if(ima->id.lib)
1599                         BLI_convertstringcode(str, ima->id.lib->filename);
1600                 else
1601                         BLI_convertstringcode(str, G.sce);
1602                 
1603                 ima->anim = openanim(str, IB_cmap | IB_rect);
1604                 
1605                 /* let's initialize this user */
1606                 if(ima->anim && iuser && iuser->frames==0)
1607                         iuser->frames= IMB_anim_get_duration(ima->anim);
1608         }
1609         
1610         if(ima->anim) {
1611                 int dur = IMB_anim_get_duration(ima->anim);
1612                 int fra= frame-1;
1613                 
1614                 if(fra<0) fra = 0;
1615                 if(fra>(dur-1)) fra= dur-1;
1616                 ibuf = IMB_anim_absolute(ima->anim, fra);
1617                 
1618                 if(ibuf) {
1619                         image_initialize_after_load(ima, ibuf);
1620                         image_assign_ibuf(ima, ibuf, 0, frame);
1621                 }
1622                 else
1623                         ima->ok= 0;
1624         }
1625         else
1626                 ima->ok= 0;
1627         
1628         if(iuser)
1629                 iuser->ok= ima->ok;
1630         
1631         return ibuf;
1632 }
1633
1634 /* cfra used for # code, Image can only have this # for all its users */
1635 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1636 {
1637         struct ImBuf *ibuf;
1638         char str[FILE_MAX];
1639         int assign = 0;
1640         
1641         /* always ensure clean ima */
1642         image_free_buffers(ima);
1643         
1644         /* is there a PackedFile with this image ? */
1645         if (ima->packedfile) {
1646                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1647         } 
1648         else {
1649                         
1650                 /* get the right string */
1651                 BLI_strncpy(str, ima->name, sizeof(str));
1652                 if(ima->id.lib)
1653                         BLI_convertstringcode(str, ima->id.lib->filename);
1654                 else
1655                         BLI_convertstringcode(str, G.sce);
1656                 
1657                 BLI_convertstringframe(str, cfra);
1658                 
1659                 /* read ibuf */
1660                 ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
1661         }
1662         
1663         if (ibuf) {
1664                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1665                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1666                         image_create_multilayer(ima, ibuf, cfra);       
1667                         ima->type= IMA_TYPE_MULTILAYER;
1668                         IMB_freeImBuf(ibuf);
1669                         ibuf= NULL;
1670                 }
1671                 else {
1672                         image_initialize_after_load(ima, ibuf);
1673                         assign= 1;
1674
1675                         /* check if the image is a font image... */
1676                         detectBitmapFont(ibuf);
1677                         
1678                         /* make packed file for autopack */
1679                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1680                                 ima->packedfile = newPackedFile(str);
1681                 }
1682                 
1683                 if(ima->flag & IMA_DO_PREMUL)
1684                         converttopremul(ibuf);
1685         }
1686         else
1687                 ima->ok= 0;
1688         
1689         if(assign)
1690                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1691
1692         if(iuser)
1693                 iuser->ok= ima->ok;
1694         
1695         return ibuf;
1696 }
1697
1698 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1699 {
1700         ImBuf *ibuf= NULL;
1701         
1702         if(ima->rr==NULL) {
1703                 ibuf = image_load_image_file(ima, iuser, 0);
1704                 if(ibuf) { /* actually an error */
1705                         ima->type= IMA_TYPE_IMAGE;
1706                         return ibuf;
1707                 }
1708         }
1709         if(ima->rr) {
1710                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1711
1712                 if(rpass) {
1713                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1714                         
1715                         image_initialize_after_load(ima, ibuf);
1716                         
1717                         ibuf->rect_float= rpass->rect;
1718                         ibuf->flags |= IB_rectfloat;
1719                         ibuf->channels= rpass->channels;
1720
1721                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1722                 }
1723         }
1724         
1725         if(ibuf==NULL) 
1726                 ima->ok= 0;
1727         if(iuser)
1728                 iuser->ok= ima->ok;
1729         
1730         return ibuf;
1731 }
1732
1733
1734 /* showing RGBA result itself (from compo/sequence) or
1735    like exr, using layers etc */
1736 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
1737 {
1738         RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
1739         
1740         if(rr) {
1741                 RenderResult rres;
1742                 float *rectf;
1743                 unsigned int *rect;
1744                 float dither;
1745                 int channels, layer, pass;
1746
1747                 channels= 4;
1748                 layer= (iuser)? iuser->layer: 0;
1749                 pass= (iuser)? iuser->pass: 0;
1750                 
1751                 /* this gives active layer, composite or seqence result */
1752                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
1753                 rect= (unsigned int *)rres.rect32;
1754                 rectf= rres.rectf;
1755                 dither= G.scene->r.dither_intensity;
1756
1757                 /* get compo/seq result by default */
1758                 if(rr->rectf && layer==0);
1759                 else if(rr->layers.first) {
1760                         RenderLayer *rl= BLI_findlink(&rr->layers, layer-(rr->rectf?1:0));
1761                         if(rl) {
1762                                 /* there's no combined pass, is in renderlayer itself */
1763                                 if(pass==0) {
1764                                         rectf= rl->rectf;
1765                                 }
1766                                 else {
1767                                         RenderPass *rpass= BLI_findlink(&rl->passes, pass-1);
1768                                         if(rpass) {
1769                                                 channels= rpass->channels;
1770                                                 rectf= rpass->rect;
1771                                                 dither= 0.0f; /* don't dither passes */
1772                                         }
1773                                 }
1774                         }
1775                 }
1776                 
1777                 if(rectf || rect) {
1778                         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1779
1780                         /* make ibuf if needed, and initialize it */
1781                         if(ibuf==NULL) {
1782                                 ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, 0, 0);
1783                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1784                         }
1785                         ibuf->x= rr->rectx;
1786                         ibuf->y= rr->recty;
1787                         
1788                         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1789                                 imb_freerectImBuf(ibuf);
1790                         if(rect)
1791                                 ibuf->rect= rect;
1792                         
1793                         ibuf->rect_float= rectf;
1794                         ibuf->flags |= IB_rectfloat;
1795                         ibuf->channels= channels;
1796                         ibuf->zbuf_float= rres.rectz;
1797                         ibuf->flags |= IB_zbuffloat;
1798                         ibuf->dither= dither;
1799                         
1800                         ima->ok= IMA_OK_LOADED;
1801                         return ibuf;
1802                 }
1803         }
1804         
1805         return NULL;
1806 }
1807
1808 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
1809 {
1810         ImBuf *ibuf = NULL;
1811         int frame = 0, index = 0;
1812
1813         /* see if we already have an appropriate ibuf, with image source and type */
1814         if(ima->source==IMA_SRC_MOVIE) {
1815                 frame= iuser?iuser->framenr:ima->lastframe;
1816                 ibuf= image_get_ibuf(ima, 0, frame);
1817         }
1818         else if(ima->source==IMA_SRC_SEQUENCE) {
1819                 if(ima->type==IMA_TYPE_IMAGE) {
1820                         frame= iuser?iuser->framenr:ima->lastframe;
1821                         ibuf= image_get_ibuf(ima, 0, frame);
1822                 }
1823                 else if(ima->type==IMA_TYPE_MULTILAYER) {
1824                         frame= iuser?iuser->framenr:ima->lastframe;
1825                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
1826                         ibuf= image_get_ibuf(ima, index, frame);
1827                 }
1828         }
1829         else if(ima->source==IMA_SRC_FILE) {
1830                 if(ima->type==IMA_TYPE_IMAGE)
1831                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1832                 else if(ima->type==IMA_TYPE_MULTILAYER)
1833                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1834         }
1835         else if(ima->source == IMA_SRC_GENERATED) {
1836                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1837         }
1838         else if(ima->source == IMA_SRC_VIEWER) {
1839                 if(ima->type==IMA_TYPE_R_RESULT) {
1840                         /* always verify entirely, not that this shouldn't happen
1841                          * during render anyway */
1842                 }
1843                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1844                         frame= iuser?iuser->framenr:0;
1845                         ibuf= image_get_ibuf(ima, 0, frame);
1846                 }
1847         }
1848
1849         *frame_r = frame;
1850         *index_r = index;
1851
1852         return ibuf;
1853 }
1854
1855 /* Checks optional ImageUser and verifies/creates ImBuf. */
1856 /* returns ibuf */
1857 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
1858 {
1859         ImBuf *ibuf= NULL;
1860         float color[] = {0, 0, 0, 1};
1861         int frame= 0, index= 0;
1862
1863         /* This function is intended to be thread-safe. It postpones the mutex lock
1864          * until it needs to load the image, if the image is already there it
1865          * should just get the pointer and return. The reason is that a lot of mutex
1866          * locks appears to be very slow on certain multicore macs, causing a render
1867          * with image textures to actually slow down as more threads are used.
1868          *
1869          * Note that all the image loading functions should also make sure they do
1870          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
1871          * That means, the last two steps must be, 1) add the ibuf to the list and
1872          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
1873
1874         /* quick reject tests */
1875         if(ima==NULL) 
1876                 return NULL;
1877         if(iuser) {
1878                 if(iuser->ok==0)
1879                         return NULL;
1880         }
1881         else if(ima->ok==0)
1882                 return NULL;
1883         
1884         /* try to get the ibuf without locking */
1885         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
1886
1887         if(ibuf == NULL) {
1888                 /* couldn't get ibuf and image is not ok, so let's lock and try to
1889                  * load the image */
1890                 BLI_lock_thread(LOCK_IMAGE);
1891
1892                 /* need to check ok flag and loading ibuf again, because the situation
1893                  * might have changed in the meantime */
1894                 if(iuser) {
1895                         if(iuser->ok==0) {
1896                                 BLI_unlock_thread(LOCK_IMAGE);
1897                                 return NULL;
1898                         }
1899                 }
1900                 else if(ima->ok==0) {
1901                         BLI_unlock_thread(LOCK_IMAGE);
1902                         return NULL;
1903                 }
1904
1905                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
1906
1907                 if(ibuf == NULL) {
1908                         /* we are sure we have to load the ibuf, using source and type */
1909                         if(ima->source==IMA_SRC_MOVIE) {
1910                                 /* source is from single file, use flipbook to store ibuf */
1911                                 ibuf= image_load_movie_file(ima, iuser, frame);
1912                         }
1913                         else if(ima->source==IMA_SRC_SEQUENCE) {
1914                                 if(ima->type==IMA_TYPE_IMAGE) {
1915                                         /* regular files, ibufs in flipbook, allows saving */
1916                                         ibuf= image_load_sequence_file(ima, iuser, frame);
1917                                 }
1918                                 /* no else; on load the ima type can change */
1919                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1920                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
1921                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
1922                                 }
1923
1924                                 if(ibuf)
1925                                         BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1926                         }
1927                         else if(ima->source==IMA_SRC_FILE) {
1928                                 
1929                                 if(ima->type==IMA_TYPE_IMAGE)
1930                                         ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra);       /* cfra only for '#', this global is OK */
1931                                 /* no else; on load the ima type can change */
1932                                 if(ima->type==IMA_TYPE_MULTILAYER)
1933                                         /* keeps render result, stores ibufs in listbase, allows saving */
1934                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
1935                                         
1936                         }
1937                         else if(ima->source == IMA_SRC_GENERATED) {
1938                                 /* generated is: ibuf is allocated dynamically */
1939                                 if(ima->type==IMA_TYPE_VERSE) {
1940                                         /* todo */
1941                                 }
1942                                 else { /* always fall back to IMA_TYPE_UV_TEST */
1943                                         /* UV testgrid or black or solid etc */
1944                                         if(ima->gen_x==0) ima->gen_x= 256;
1945                                         if(ima->gen_y==0) ima->gen_y= 256;
1946                                         ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
1947                                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1948                                         ima->ok= IMA_OK_LOADED;
1949                                 }
1950                         }
1951                         else if(ima->source == IMA_SRC_VIEWER) {
1952                                 if(ima->type==IMA_TYPE_R_RESULT) {
1953                                         /* always verify entirely */
1954                                         ibuf= image_get_render_result(ima, iuser);
1955                                 }
1956                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1957                                         /* Composite Viewer, all handled in compositor */
1958                                         /* fake ibuf, will be filled in compositor */
1959                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
1960                                         image_assign_ibuf(ima, ibuf, 0, frame);
1961                                 }
1962                         }
1963                 }
1964
1965                 BLI_unlock_thread(LOCK_IMAGE);
1966         }
1967
1968         /* we assuming that if it is not rendering, it's also not multithreaded
1969          * (a somewhat weak assumption) */
1970         if(G.rendering==0)
1971                 tag_image_time(ima);
1972
1973         return ibuf;
1974 }
1975
1976
1977 void BKE_image_user_calc_imanr(ImageUser *iuser, int cfra, int fieldnr)
1978 {
1979         int imanr, len;
1980         
1981         /* here (+fie_ima/2-1) makes sure that division happens correctly */
1982         len= (iuser->fie_ima*iuser->frames)/2;
1983         
1984         if(len==0) {
1985                 iuser->framenr= 0;
1986         }
1987         else {
1988                 cfra= cfra - iuser->sfra+1;
1989                 
1990                 /* cyclic */
1991                 if(iuser->cycl) {
1992                         cfra= ( (cfra) % len );
1993                         if(cfra < 0) cfra+= len;
1994                         if(cfra==0) cfra= len;
1995                 }
1996                 
1997                 if(cfra<1) cfra= 1;
1998                 else if(cfra>len) cfra= len;
1999                 
2000                 /* convert current frame to current field */
2001                 cfra= 2*(cfra);
2002                 if(fieldnr) cfra++;
2003                 
2004                 /* transform to images space */
2005                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2006                 if(imanr>iuser->frames) imanr= iuser->frames;
2007                 imanr+= iuser->offset;
2008                 
2009                 if(iuser->cycl) {
2010                         imanr= ( (imanr) % len );
2011                         while(imanr < 0) imanr+= len;
2012                         if(imanr==0) imanr= len;
2013                 }
2014         
2015                 /* allows image users to handle redraws */
2016                 if(iuser->flag & IMA_ANIM_ALWAYS)
2017                         if(imanr!=iuser->framenr)
2018                                 iuser->flag |= IMA_ANIM_REFRESHED;
2019                 
2020                 iuser->framenr= imanr;
2021                 if(iuser->ok==0) iuser->ok= 1;
2022         }
2023 }
2024