ac0bc910dbda5769ee9762d87317153401b40cb8
[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_texture_types.h"
56 #include "DNA_userdef_types.h"
57
58 #include "BLI_arithb.h"
59 #include "BLI_blenlib.h"
60 #include "BLI_threads.h"
61
62 #include "BKE_bmfont.h"
63 #include "BKE_global.h"
64 #include "BKE_icons.h"
65 #include "BKE_image.h"
66 #include "BKE_library.h"
67 #include "BKE_main.h"
68 #include "BKE_packedFile.h"
69 #include "BKE_scene.h"
70 #include "BKE_texture.h"
71 #include "BKE_utildefines.h"
72
73 #include "PIL_time.h"
74
75 #include "RE_pipeline.h"
76
77 /* bad level; call to free_realtime_image */
78 #include "BKE_bad_level_calls.h"        
79
80 /* max int, to indicate we don't store sequences in ibuf */
81 #define IMA_NO_INDEX    0x7FEFEFEF
82
83 /* quick lookup: supports 1 million frames, thousand passes */
84 #define IMA_MAKE_INDEX(frame, index)    ((frame)<<10)+index
85 #define IMA_INDEX_FRAME(index)                  (index>>10)
86
87 /* ******** IMAGE PROCESSING ************* */
88
89 /* used by sequencer */
90 void converttopremul(struct ImBuf *ibuf)
91 {
92         int x, y, val;
93         char *cp;
94         
95         if(ibuf==0) return;
96         if(ibuf->depth==24) {   /* put alpha at 255 */
97                 
98                 cp= (char *)(ibuf->rect);
99                 for(y=0; y<ibuf->y; y++) {
100                         for(x=0; x<ibuf->x; x++, cp+=4) {
101                                 cp[3]= 255;
102                         }
103                 }
104                 return;
105         }
106
107         cp= (char *)(ibuf->rect);
108         for(y=0; y<ibuf->y; y++) {
109                 for(x=0; x<ibuf->x; x++, cp+=4) {
110                         if(cp[3]==0) {
111                                 cp[0]= cp[1]= cp[2]= 0;
112                         }
113                         else if(cp[3]!=255) {
114                                 val= cp[3];
115                                 cp[0]= (cp[0]*val)>>8;
116                                 cp[1]= (cp[1]*val)>>8;
117                                 cp[2]= (cp[2]*val)>>8;
118                         }
119                 }
120         }
121 }
122
123 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
124 {
125         struct ImBuf * tbuf1, * tbuf2;
126         
127         if (ibuf == 0) return;
128         if (ibuf->flags & IB_fields) return;
129         ibuf->flags |= IB_fields;
130         
131         if (ibuf->rect) {
132                 /* make copies */
133                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect, (unsigned char)0);
134                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect, (unsigned char)0);
135                 
136                 ibuf->x *= 2;
137                 
138                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
139                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
140                 
141                 ibuf->x /= 2;
142                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
143                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
144                 
145                 IMB_freeImBuf(tbuf1);
146                 IMB_freeImBuf(tbuf2);
147         }
148         ibuf->y /= 2;
149 }
150
151 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
152 {
153         struct ImBuf * tbuf1, * tbuf2;
154         
155         if (ibuf == 0) return;
156         if (ibuf->flags & IB_fields) return;
157         ibuf->flags |= IB_fields;
158         
159         if (ibuf->rect) {
160                 /* make copies */
161                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect, 0);
162                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect, 0);
163                 
164                 ibuf->x *= 2;
165                 
166                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
167                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
168                 
169                 ibuf->x /= 2;
170                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
171                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
172                 
173                 IMB_freeImBuf(tbuf1);
174                 IMB_freeImBuf(tbuf2);
175         }
176         ibuf->y /= 2;
177 }
178
179 void image_de_interlace(Image *ima, int odd)
180 {
181         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
182         if(ibuf) {
183                 if(odd)
184                         de_interlace_st(ibuf);
185                 else
186                         de_interlace_ng(ibuf);
187         }
188 }
189
190 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
191
192 static void image_free_buffers(Image *ima)
193 {
194         ImBuf *ibuf;
195         
196         while((ibuf = ima->ibufs.first)) {
197                 BLI_remlink(&ima->ibufs, ibuf);
198                 
199                 if (ibuf->userdata) {
200                         MEM_freeN(ibuf->userdata);
201                         ibuf->userdata = NULL;
202                 }
203                 IMB_freeImBuf(ibuf);
204         }
205         
206         if(ima->anim) IMB_free_anim(ima->anim);
207         ima->anim= NULL;
208         
209         if (ima->preview) {
210                 MEM_freeN(ima->preview->rect);
211                 MEM_freeN(ima->preview);
212                 ima->preview = NULL;
213         }
214         
215         if(ima->rr) {
216                 RE_FreeRenderResult(ima->rr);
217                 ima->rr= NULL;
218         }       
219         
220         free_realtime_image(ima);
221         
222         ima->ok= IMA_OK;
223 }
224
225 /* called by library too, do not free ima itself */
226 void free_image(Image *ima)
227 {
228
229         image_free_buffers(ima);
230         if (ima->packedfile) {
231                 freePackedFile(ima->packedfile);
232                 ima->packedfile = NULL;
233         }
234         BKE_icon_delete(&ima->id);
235         ima->id.icon_id = 0;
236 }
237
238 /* only image block itself */
239 static Image *image_alloc(const char *name, short source, short type)
240 {
241         Image *ima;
242         
243         ima= alloc_libblock(&G.main->image, ID_IM, name);
244         if(ima) {
245                 ima->ok= IMA_OK;
246                 
247                 ima->xrep= ima->yrep= 1;
248                 ima->gen_x= 256; ima->gen_y= 256;
249                 ima->gen_type= 1;       /* no defines yet? */
250                 
251                 ima->source= source;
252                 ima->type= type;
253         }
254         return ima;
255 }
256
257 /* get the ibuf from an image cache, local use here only */
258 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
259 {
260         if(index==IMA_NO_INDEX)
261                 return ima->ibufs.first;
262         else {
263                 ImBuf *ibuf;
264                 
265                 index= IMA_MAKE_INDEX(frame, index);
266                 for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
267                         if(ibuf->index==index)
268                                 return ibuf;
269                 return NULL;
270         }
271 }
272
273 /* no ima->ibuf anymore, but listbase */
274 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
275 {
276         if(ibuf) {
277                 BLI_remlink(&ima->ibufs, ibuf);
278                 IMB_freeImBuf(ibuf);
279         }
280 }
281
282
283 /* no ima->ibuf anymore, but listbase */
284 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
285 {
286         if(ibuf) {
287                 ImBuf *link;
288                 
289                 if(index!=IMA_NO_INDEX)
290                         index= IMA_MAKE_INDEX(frame, index);
291                 
292                 /* insert based on index */
293                 for(link= ima->ibufs.first; link; link= link->next)
294                         if(link->index>=index)
295                                 break;
296                 /* now we don't want copies? */
297                 if(link && ibuf->index==link->index) {
298                         ImBuf *prev= ibuf->prev;
299                         image_remove_ibuf(ima, link);
300                         link= prev;
301                 }
302                 
303                 /* this function accepts link==NULL */
304                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
305                 
306                 ibuf->index= index;
307         }
308         
309 }
310
311 /* checks if image was already loaded, then returns same image */
312 /* otherwise creates new. */
313 /* does not load ibuf itself */
314 Image *BKE_add_image_file(const char *name)
315 {
316         Image *ima;
317         int file, len;
318         const char *libname;
319         char str[FILE_MAX], strtest[FILE_MAX];
320         
321         BLI_strncpy(str, name, sizeof(str));
322         BLI_convertstringcode(str, G.sce, G.scene->r.cfra);
323         
324         file= open(str, O_BINARY|O_RDONLY);
325         if(file== -1) return 0;
326         close(file);
327         
328         /* first search an identical image */
329         for(ima= G.main->image.first; ima; ima= ima->id.next) {
330                 if(ima->source!=IMA_SRC_VIEWER) {
331                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
332                         BLI_convertstringcode(strtest, G.sce, G.scene->r.cfra);
333                         
334                         if( strcmp(strtest, str)==0 ) {
335                                 if(ima->anim==NULL || ima->id.us==0) {
336                                         BLI_strncpy(ima->name, name, sizeof(ima->name));        /* for stringcode */
337                                         ima->id.us++;                                                                           /* officially should not, it doesn't link here! */
338                                         if(ima->ok==0)
339                                                 ima->ok= IMA_OK;
340                         /* RETURN! */
341                                         return ima;
342                                 }
343                         }
344                 }
345         }
346         /* add new image */
347         
348         /* create a short library name */
349         len= strlen(name);
350         
351         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
352         libname= name+len;
353         
354         ima= image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
355         BLI_strncpy(ima->name, name, sizeof(ima->name));
356         
357         /* do a wild guess! */
358         if(BLI_testextensie(name, ".avi") || BLI_testextensie(name, ".mov")
359                         || BLI_testextensie(name, ".mpg")  || BLI_testextensie(name, ".mp4"))
360                 ima->source= IMA_SRC_MOVIE;
361         
362         return ima;
363 }
364
365 static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid)
366 {
367         ImBuf *ibuf;
368         float h=0.0, hoffs=0.0, hue=0.0, s=0.9, v=0.9, r, g, b;
369         unsigned char *rect;
370         int x, y;
371         int checkerwidth=21, dark=1;
372         
373         ibuf= IMB_allocImBuf(width, height, 24, IB_rect, 0);
374         strcpy(ibuf->name, "Untitled");
375         ibuf->userflags |= IB_BITMAPDIRTY;
376         
377         rect= (unsigned char*)ibuf->rect;
378         
379         if (uvtestgrid) {
380                 /* these two passes could be combined into one, but it's more readable and 
381                 * easy to tweak like this, speed isn't really that much of an issue in this situation... */
382                 
383                 /* checkers */
384                 for(y=0; y<ibuf->y; y++) {
385                         dark = pow(-1, floor(y / checkerwidth));
386                         
387                         for(x=0; x<ibuf->x; x++, rect+=4) {
388                                 if (x % checkerwidth == 0) dark *= -1;
389                                 
390                                 if (dark > 0) {
391                                         rect[0] = rect[1] = rect[2] = 64;
392                                         rect[3] = 255;
393                                 } else {
394                                         rect[0] = rect[1] = rect[2] = 150;
395                                         rect[3] = 255;
396                                 }
397                         }
398                 }
399                 
400                 /* 2nd pass, coloured + */
401                 rect= (unsigned char*)ibuf->rect;
402                 
403                 for(y=0; y<ibuf->y; y++) {
404                         hoffs = 0.125 * floor(y / checkerwidth);
405                         
406                         for(x=0; x<ibuf->x; x++, rect+=4) {
407                                 h = 0.125 * floor(x / checkerwidth);
408                                 
409                                 if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 4) &&
410                                         (fabs((y % checkerwidth) - (checkerwidth / 2)) < 4)) {
411                                         
412                                         if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 1) ||
413                                                 (fabs((y % checkerwidth) - (checkerwidth / 2)) < 1)) {
414                                                 
415                                                 hue = fmod(fabs(h-hoffs), 1.0);
416                                                 hsv_to_rgb(hue, s, v, &r, &g, &b);
417                                                 
418                                                 rect[0]= (char)(r * 255.0);
419                                                 rect[1]= (char)(g * 255.0);
420                                                 rect[2]= (char)(b * 255.0);
421                                                 rect[3]= 255;
422                                         }
423                                 }
424                                 
425                         }
426                 }
427         } else {        /* blank image */
428                 for(y=0; y<ibuf->y; y++) {
429                         for(x=0; x<ibuf->x; x++, rect+=4) {
430                                 rect[0]= rect[1]= rect[2]= 0;
431                                 rect[3]= 255;
432                         }
433                 }
434         }
435         return ibuf;
436 }
437
438 /* adds new image block, creates ImBuf and initializes color */
439 Image *BKE_add_image_size(int width, int height, char *name, short uvtestgrid)
440 {
441         Image *ima;
442         
443         /* on save, type is changed to FILE in editsima.c */
444         ima= image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
445         
446         if (ima) {
447                 ImBuf *ibuf;
448                 
449                 BLI_strncpy(ima->name, name, FILE_MAX);
450                 ima->gen_x= width;
451                 ima->gen_y= height;
452                 ima->gen_type= uvtestgrid;
453                 
454                 ibuf= add_ibuf_size(width, height, name, uvtestgrid);
455                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
456                 
457                 ima->ok= IMA_OK_LOADED;
458         }
459
460         return ima;
461 }
462
463 /* packs rect from memory as PNG */
464 void BKE_image_memorypack(Image *ima)
465 {
466         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
467         
468         if(ibuf==NULL)
469                 return;
470         if (ima->packedfile) {
471                 freePackedFile(ima->packedfile);
472                 ima->packedfile = NULL;
473         }
474         
475         ibuf->ftype= PNG;
476         ibuf->depth= 32;
477         
478         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
479         if(ibuf->encodedbuffer==NULL) {
480                 printf("memory save for pack error\n");
481         }
482         else {
483                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
484                 
485                 pf->data = ibuf->encodedbuffer;
486                 pf->size = ibuf->encodedsize;
487                 ima->packedfile= pf;
488                 ibuf->encodedbuffer= NULL;
489                 ibuf->encodedsize= 0;
490                 ibuf->userflags &= ~IB_BITMAPDIRTY;
491                 
492                 if(ima->source==IMA_SRC_GENERATED) {
493                         ima->source= IMA_SRC_FILE;
494                         ima->type= IMA_TYPE_IMAGE;
495                 }
496         }
497 }
498
499 void tag_image_time(Image *ima)
500 {
501         if (ima)
502                 ima->lastused = (int)PIL_check_seconds_timer();
503 }
504
505 void tag_all_images_time() 
506 {
507         Image *ima;
508         int ctime = (int)PIL_check_seconds_timer();
509
510         ima= G.main->image.first;
511         while(ima) {
512                 if(ima->bindcode || ima->repbind || ima->ibufs.first) {
513                         ima->lastused = ctime;
514                 }
515         }
516 }
517
518 void free_old_images()
519 {
520         Image *ima;
521         static int lasttime = 0;
522         int ctime = (int)PIL_check_seconds_timer();
523         
524         /* 
525            Run garbage collector once for every collecting period of time 
526            if textimeout is 0, that's the option to NOT run the collector
527         */
528         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
529                 return;
530
531         lasttime = ctime;
532
533         ima= G.main->image.first;
534         while(ima) {
535                 if((ima->flag & IMA_NOCOLLECT)==0 && ctime - ima->lastused > U.textimeout) {
536                         /*
537                            If it's in GL memory, deallocate and set time tag to current time
538                            This gives textures a "second chance" to be used before dying.
539                         */
540                         if(ima->bindcode || ima->repbind) {
541                                 free_realtime_image(ima);
542                                 ima->lastused = ctime;
543                         }
544                         /* Otherwise, just kill the buffers */
545                         else if (ima->ibufs.first) {
546                                 image_free_buffers(ima);
547                         }
548                 }
549                 ima = ima->id.next;
550         }
551 }
552
553 void BKE_image_free_all_textures(void)
554 {
555         Tex *tex;
556         Image *ima;
557         unsigned int totsize= 0;
558         
559         for(ima= G.main->image.first; ima; ima= ima->id.next)
560                 ima->id.flag &= ~LIB_DOIT;
561         
562         for(tex= G.main->tex.first; tex; tex= tex->id.next)
563                 if(tex->ima)
564                         tex->ima->id.flag |= LIB_DOIT;
565         
566         for(ima= G.main->image.first; ima; ima= ima->id.next) {
567                 if(ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
568                         ImBuf *ibuf;
569                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
570                                 if(ibuf->mipmap[0]) 
571                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
572                                 else
573                                         totsize+= ibuf->x*ibuf->y*4;
574                         }
575                         image_free_buffers(ima);
576                 }
577         }
578         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
579 }
580
581 /* except_frame is weak, only works for seqs without offset... */
582 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
583 {
584         ImBuf *ibuf, *nbuf;
585
586         for(ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
587                 nbuf= ibuf->next;
588                 if(ibuf->userflags & IB_BITMAPDIRTY)
589                         continue;
590                 if(ibuf->index==IMA_NO_INDEX)
591                         continue;
592                 if(except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
593                         BLI_remlink(&ima->ibufs, ibuf);
594                         
595                         if (ibuf->userdata) {
596                                 MEM_freeN(ibuf->userdata);
597                                 ibuf->userdata = NULL;
598                         }
599                         IMB_freeImBuf(ibuf);
600                 }                                       
601         }
602 }
603
604 void BKE_image_all_free_anim_ibufs(int cfra)
605 {
606         Image *ima;
607         
608         for(ima= G.main->image.first; ima; ima= ima->id.next)
609                 if(ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
610                         BKE_image_free_anim_ibufs(ima, cfra);
611 }
612
613
614 /* *********** READ AND WRITE ************** */
615
616 int BKE_imtype_to_ftype(int imtype)
617 {
618         if(imtype==0)
619                 return TGA;
620         else if(imtype== R_IRIS) 
621                 return IMAGIC;
622         else if (imtype==R_RADHDR)
623                 return RADHDR;
624         else if (imtype==R_PNG)
625                 return PNG;
626         else if (imtype==R_BMP)
627                 return BMP;
628         else if (imtype==R_TIFF)
629                 return TIF;
630         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER)
631                 return OPENEXR;
632         else if (imtype==R_CINEON)
633                 return CINEON;
634         else if (imtype==R_DPX)
635                 return DPX;
636         else if (imtype==R_TARGA)
637                 return TGA;
638         else if(imtype==R_RAWTGA)
639                 return RAWTGA;
640         else if(imtype==R_HAMX)
641                 return AN_hamx;
642         else
643                 return JPG|90;
644 }
645
646 int BKE_ftype_to_imtype(int ftype)
647 {
648         if(ftype==0)
649                 return TGA;
650         else if(ftype == IMAGIC) 
651                 return R_IRIS;
652         else if (ftype & RADHDR)
653                 return R_RADHDR;
654         else if (ftype & PNG)
655                 return R_PNG;
656         else if (ftype & BMP)
657                 return R_BMP;
658         else if (ftype & TIF)
659                 return R_TIFF;
660         else if (ftype & OPENEXR)
661                 return R_OPENEXR;
662         else if (ftype & CINEON)
663                 return R_CINEON;
664         else if (ftype & DPX)
665                 return R_DPX;
666         else if (ftype & TGA)
667                 return R_TARGA;
668         else if(ftype & RAWTGA)
669                 return R_RAWTGA;
670         else if(ftype == AN_hamx)
671                 return R_HAMX;
672         else
673                 return R_JPEG90;
674 }
675
676
677 int BKE_imtype_is_movie(int imtype)
678 {
679         switch(imtype) {
680         case R_MOVIE:
681         case R_AVIRAW:
682         case R_AVIJPEG:
683         case R_AVICODEC:
684         case R_QUICKTIME:
685         case R_FFMPEG:
686         case R_FRAMESERVER:
687                         return 1;
688         }
689         return 0;
690 }
691
692 void BKE_add_image_extension(char *string, int imtype)
693 {
694         char *extension="";
695         
696         if(G.scene->r.imtype== R_IRIS) {
697                 if(!BLI_testextensie(string, ".rgb"))
698                         extension= ".rgb";
699         }
700         else if(imtype==R_IRIZ) {
701                 if(!BLI_testextensie(string, ".rgb"))
702                         extension= ".rgb";
703         }
704         else if(imtype==R_RADHDR) {
705                 if(!BLI_testextensie(string, ".hdr"))
706                         extension= ".hdr";
707         }
708         else if(imtype==R_PNG) {
709                 if(!BLI_testextensie(string, ".png"))
710                         extension= ".png";
711         }
712         else if(imtype==R_RAWTGA) {
713                 if(!BLI_testextensie(string, ".tga"))
714                         extension= ".tga";
715         }
716         else if(ELEM5(imtype, R_MOVIE, R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90)) {
717                 if(!BLI_testextensie(string, ".jpg"))
718                         extension= ".jpg";
719         }
720         else if(imtype==R_BMP) {
721                 if(!BLI_testextensie(string, ".bmp"))
722                         extension= ".bmp";
723         }
724         else if(G.have_libtiff && (imtype==R_TIFF)) {
725                 if(!BLI_testextensie(string, ".tif"))
726                         extension= ".tif";
727         }
728 #ifdef WITH_OPENEXR
729         else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
730                 if(!BLI_testextensie(string, ".exr"))
731                         extension= ".exr";
732         }
733 #endif
734         else if(imtype==R_CINEON){
735                 if (!BLI_testextensie(string, ".cin"))
736                         extension= ".cin";
737         }
738         else if(imtype==R_DPX){
739                 if (!BLI_testextensie(string, ".dpx"))
740                         extension= ".dpx";
741         }
742         else {  /* targa default */
743                 if(!BLI_testextensie(string, ".tga"))
744                         extension= ".tga";
745         }
746
747         strcat(string, extension);
748 }
749
750
751 int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
752 {
753         int ok;
754         
755         if(imtype==0);
756         else if(imtype== R_IRIS) 
757                 ibuf->ftype= IMAGIC;
758         else if ((imtype==R_RADHDR)) {
759                 ibuf->ftype= RADHDR;
760         }
761         else if ((imtype==R_PNG)) {
762                 ibuf->ftype= PNG;
763         }
764         else if ((imtype==R_BMP)) {
765                 ibuf->ftype= BMP;
766         }
767         else if ((G.have_libtiff) && (imtype==R_TIFF)) {
768                 ibuf->ftype= TIF;
769         }
770 #ifdef WITH_OPENEXR
771         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
772                 ibuf->ftype= OPENEXR;
773                 if(subimtype & R_OPENEXR_HALF)
774                         ibuf->ftype |= OPENEXR_HALF;
775                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
776                 
777                 if(!(subimtype & R_OPENEXR_ZBUF))
778                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
779                 
780         }
781 #endif
782         else if (imtype==R_CINEON) {
783                 ibuf->ftype = CINEON;
784         }
785         else if (imtype==R_DPX) {
786                 ibuf->ftype = DPX;
787         }
788         else if (imtype==R_TARGA) {
789                 ibuf->ftype= TGA;
790         }
791         else if(imtype==R_RAWTGA) {
792                 ibuf->ftype= RAWTGA;
793         }
794         else if(imtype==R_HAMX) {
795                 ibuf->ftype= AN_hamx;
796         }
797         else {
798                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
799                 if(quality < 10) quality= 90;
800                 ibuf->ftype= JPG|quality;
801                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
802         }
803         
804         BLI_make_existing_file(name);
805         
806         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
807         if (ok == 0) {
808                 perror(name);
809         }
810         
811         return(ok);
812 }
813
814
815 void BKE_makepicstring(char *string, char *base, int frame, int imtype)
816 {
817         short i, len, digits= 4;        /* digits in G.scene? */
818         char num[10];
819
820         if (string==NULL) return;
821
822         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
823         BLI_convertstringcode(string, G.sce, frame);
824
825         len= strlen(string);
826                         
827         i= digits - sprintf(num, "%d", frame);
828         for(; i>0; i--){
829                 string[len]= '0';
830                 len++;
831         }
832         string[len]= 0;
833         strcat(string, num);
834
835         if(G.scene->r.scemode & R_EXTENSION) 
836                 BKE_add_image_extension(string, imtype);
837                 
838 }
839
840 /* used by sequencer too */
841 struct anim *openanim(char *name, int flags)
842 {
843         struct anim *anim;
844         struct ImBuf *ibuf;
845         
846         anim = IMB_open_anim(name, flags);
847         if (anim == NULL) return(0);
848
849         ibuf = IMB_anim_absolute(anim, 0);
850         if (ibuf == NULL) {
851                 printf("not an anim; %s\n", name);
852                 IMB_free_anim(anim);
853                 return(0);
854         }
855         IMB_freeImBuf(ibuf);
856         
857         return(anim);
858 }
859
860 /* ************************* New Image API *************** */
861
862
863 /* Notes about Image storage 
864 - packedfile
865   -> written in .blend
866 - filename
867   -> written in .blend
868 - movie
869   -> comes from packedfile or filename
870 - renderresult
871   -> comes from packedfile or filename
872 - listbase
873   -> ibufs from exrhandle
874 - flipbook array
875   -> ibufs come from movie, temporary renderresult or sequence
876 - ibuf
877   -> comes from packedfile or filename or generated
878
879 */
880
881
882 /* forces existance of 1 Image for renderout or nodes, returns Image */
883 /* name is only for default, when making new one */
884 Image *BKE_image_verify_viewer(int type, const char *name)
885 {
886         Image *ima;
887         
888         for(ima=G.main->image.first; ima; ima= ima->id.next)
889                 if(ima->source==IMA_SRC_VIEWER)
890                         if(ima->type==type)
891                                 break;
892         
893         if(ima==NULL)
894                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
895         
896         /* happens on reload, imagewindow cannot be image user when hidden*/
897         if(ima->id.us==0)
898                 id_us_plus(&ima->id);
899
900         return ima;
901 }
902
903 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
904 {
905         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
906 }
907
908 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
909 {
910         if(ima==NULL)
911                 return;
912         
913         switch(signal) {
914         case IMA_SIGNAL_FREE:
915                 image_free_buffers(ima);
916                 if(iuser)
917                         iuser->ok= 1;
918                 break;
919         case IMA_SIGNAL_SRC_CHANGE:
920                 if(ima->type==IMA_TYPE_MULTILAYER)
921                         image_free_buffers(ima);
922                 else if(ima->source==IMA_SRC_GENERATED) {
923                         if(ima->gen_x==0 || ima->gen_y==0) {
924                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
925                                 if(ibuf) {
926                                         ima->gen_x= ibuf->x;
927                                         ima->gen_y= ibuf->y;
928                                 }
929                         }
930                 }
931                 ima->ok= 1;
932                 if(iuser)
933                         iuser->ok= 1;
934                 break;
935                         
936         case IMA_SIGNAL_RELOAD:
937                 /* try to repack file */
938                 if(ima->packedfile) {
939                         PackedFile *pf;
940                         pf = newPackedFile(ima->name);
941                         if (pf) {
942                                 freePackedFile(ima->packedfile);
943                                 ima->packedfile = pf;
944                                 image_free_buffers(ima);
945                         } else {
946                                 printf("ERROR: Image not available. Keeping packed image\n");
947                         }
948                 }
949                 else
950                         image_free_buffers(ima);
951                 
952                 if(iuser)
953                         iuser->ok= 1;
954                 
955                 break;
956         case IMA_SIGNAL_USER_NEW_IMAGE:
957                 if(iuser) {
958                         iuser->ok= 1;
959                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
960                                 if(ima->type==IMA_TYPE_MULTILAYER) {
961                                         iuser->multi_index= 0;
962                                         iuser->layer= iuser->pass= 0;
963                                 }
964                         }
965                 }
966                 break;
967         }
968 }
969
970 /* if layer or pass changes, we need an index for the imbufs list */
971 /* note it is called for rendered results, but it doesnt use the index! */
972 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
973 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
974 {
975         RenderLayer *rl;
976         RenderPass *rpass= NULL;
977         
978         if(rr==NULL) 
979                 return NULL;
980         
981         if(iuser) {
982                 short index= 0, rl_index= 0, rp_index;
983                 
984                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
985                         rp_index= 0;
986                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
987                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
988                                         break;
989                         if(rpass)
990                                 break;
991                 }
992                 
993                 if(rpass)
994                         iuser->multi_index= index;
995                 else 
996                         iuser->multi_index= 0;
997         }
998         if(rpass==NULL) {
999                 rl= rr->layers.first;
1000                 if(rl)
1001                         rpass= rl->passes.first;
1002         }
1003         
1004         return rpass;
1005 }
1006
1007 RenderResult *BKE_image_get_renderresult(Image *ima)
1008 {
1009         if(ima->rr)
1010                 return ima->rr;
1011         if(ima->type==IMA_TYPE_R_RESULT)
1012                 return RE_GetResult(RE_GetRender(G.scene->id.name));
1013         return NULL;
1014 }
1015
1016 /* after imbuf load, openexr type can return with a exrhandle open */
1017 /* in that case we have to build a render-result */
1018 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1019 {
1020         
1021         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1022
1023 #ifdef WITH_OPENEXR
1024         IMB_exr_close(ibuf->userdata);
1025 #endif
1026
1027         ibuf->userdata= NULL;
1028         if(ima->rr)
1029                 ima->rr->framenr= framenr;
1030 }
1031
1032 /* common stuff to do with images after loading */
1033 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1034 {
1035         
1036         
1037         /* preview is NULL when it has never been used as an icon before */
1038         if(G.background==0 && ima->preview==NULL)
1039                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1040         
1041         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1042         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1043         
1044         /* fields */
1045         if (ima->flag & IMA_FIELDS) {
1046                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1047                 else de_interlace_ng(ibuf);
1048         }
1049         /* timer */
1050         ima->lastused = clock() / CLOCKS_PER_SEC;
1051         
1052         ima->ok= IMA_OK_LOADED;
1053         
1054 }
1055
1056 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1057 {
1058         struct ImBuf *ibuf;
1059         unsigned short numlen;
1060         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1061         
1062         ima->lastframe= frame;
1063
1064         BLI_stringdec(ima->name, head, tail, &numlen);
1065         BLI_stringenc(ima->name, head, tail, numlen, frame);
1066         BLI_strncpy(name, ima->name, sizeof(name));
1067         
1068         if(ima->id.lib)
1069                 BLI_convertstringcode(name, ima->id.lib->filename, frame);
1070         else
1071                 BLI_convertstringcode(name, G.sce, frame);
1072         
1073         /* read ibuf */
1074         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1075         printf("loaded %s\n", name);
1076         
1077         if (ibuf) {
1078 #ifdef WITH_OPENEXR
1079                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1080                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1081                         image_create_multilayer(ima, ibuf, frame);      
1082                         ima->type= IMA_TYPE_MULTILAYER;
1083                         IMB_freeImBuf(ibuf);
1084                         ibuf= NULL;
1085                 }
1086                 else {
1087                         image_assign_ibuf(ima, ibuf, 0, frame);
1088                         image_initialize_after_load(ima, ibuf);
1089                 }
1090 #else
1091                 image_assign_ibuf(ima, ibuf, 0, frame);
1092                 image_initialize_after_load(ima, ibuf);
1093 #endif
1094         }
1095         else
1096                 ima->ok= 0;
1097         
1098         if(iuser)
1099                 iuser->ok= ima->ok;
1100         
1101         return ibuf;
1102 }
1103
1104 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1105 {
1106         struct ImBuf *ibuf= NULL;
1107         
1108         /* either we load from RenderResult, or we have to load a new one */
1109         
1110         /* check for new RenderResult */
1111         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1112                 /* copy to survive not found multilayer image */
1113                 RenderResult *oldrr= ima->rr;
1114         
1115                 ima->rr= NULL;
1116                 ibuf = image_load_sequence_file(ima, iuser, frame);
1117                 
1118                 if(ibuf) { /* actually an error */
1119                         ima->type= IMA_TYPE_IMAGE;
1120                         printf("error, multi is normal image\n");
1121                 }
1122                 // printf("loaded new result %p\n", ima->rr);
1123                 /* free result if new one found */
1124                 if(ima->rr) {
1125                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1126                         if(oldrr) RE_FreeRenderResult(oldrr);
1127                 }
1128                 else
1129                         ima->rr= oldrr;
1130
1131         }
1132         if(ima->rr) {
1133                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1134                 
1135                 if(rpass) {
1136                         // printf("load from pass %s\n", rpass->name);
1137                         /* since we free  render results, we copy the rect */
1138                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1139                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1140                         ibuf->flags |= IB_rectfloat;
1141                         ibuf->mall= IB_rectfloat;
1142                         ibuf->channels= rpass->channels;
1143                         
1144                         image_assign_ibuf(ima, ibuf, iuser->multi_index, frame);
1145                         image_initialize_after_load(ima, ibuf);
1146                         
1147                 }
1148                 // else printf("pass not found\n");
1149         }
1150         else
1151                 ima->ok= 0;
1152         
1153         if(iuser)
1154                 iuser->ok= ima->ok;
1155         
1156         return ibuf;
1157 }
1158
1159
1160 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1161 {
1162         struct ImBuf *ibuf= NULL;
1163         
1164         ima->lastframe= frame;
1165         
1166         if(ima->anim==NULL) {
1167                 char str[FILE_MAX];
1168                 
1169                 BLI_strncpy(str, ima->name, FILE_MAX);
1170                 if(ima->id.lib)
1171                         BLI_convertstringcode(str, ima->id.lib->filename, 0);
1172                 else
1173                         BLI_convertstringcode(str, G.sce, 0);
1174                 
1175                 ima->anim = openanim(str, IB_cmap | IB_rect);
1176                 
1177                 /* let's initialize this user */
1178                 if(ima->anim && iuser && iuser->frames==0)
1179                         iuser->frames= IMB_anim_get_duration(ima->anim);
1180         }
1181         
1182         if(ima->anim) {
1183                 int dur = IMB_anim_get_duration(ima->anim);
1184                 int fra= frame-1;
1185                 
1186                 if(fra<0) fra = 0;
1187                 if(fra>(dur-1)) fra= dur-1;
1188                 ibuf = IMB_anim_absolute(ima->anim, fra);
1189                 
1190                 if(ibuf) {
1191                         image_assign_ibuf(ima, ibuf, 0, frame);
1192                         image_initialize_after_load(ima, ibuf);
1193                 }
1194                 else
1195                         ima->ok= 0;
1196         }
1197         else
1198                 ima->ok= 0;
1199         
1200         if(iuser)
1201                 iuser->ok= ima->ok;
1202         
1203         return ibuf;
1204 }
1205
1206 /* cfra used for # code, Image can only have this # for all its users */
1207 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1208 {
1209         struct ImBuf *ibuf;
1210         char str[FILE_MAX];
1211         
1212         /* always ensure clean ima */
1213         image_free_buffers(ima);
1214         
1215         /* is there a PackedFile with this image ? */
1216         if (ima->packedfile) {
1217                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1218         } 
1219         else {
1220                         
1221                 /* get the right string */
1222                 BLI_strncpy(str, ima->name, sizeof(str));
1223                 if(ima->id.lib)
1224                         BLI_convertstringcode(str, ima->id.lib->filename, cfra);
1225                 else
1226                         BLI_convertstringcode(str, G.sce, cfra);
1227                 
1228                 /* read ibuf */
1229                 ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer);
1230         }
1231         
1232         if (ibuf) {
1233                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1234                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1235                         image_create_multilayer(ima, ibuf, cfra);       
1236                         ima->type= IMA_TYPE_MULTILAYER;
1237                         IMB_freeImBuf(ibuf);
1238                         ibuf= NULL;
1239                 }
1240                 else {
1241                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1242                         image_initialize_after_load(ima, ibuf);
1243
1244                         /* check if the image is a font image... */
1245                         detectBitmapFont(ibuf);
1246                         
1247                         /* make packed file for autopack */
1248                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1249                                 ima->packedfile = newPackedFile(str);
1250                 }
1251         }
1252         else
1253                 ima->ok= 0;
1254         
1255         if(iuser)
1256                 iuser->ok= ima->ok;
1257         
1258         return ibuf;
1259 }
1260
1261 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1262 {
1263         ImBuf *ibuf= NULL;
1264         
1265         if(ima->rr==NULL) {
1266                 ibuf = image_load_image_file(ima, iuser, 0);
1267                 if(ibuf) { /* actually an error */
1268                         ima->type= IMA_TYPE_IMAGE;
1269                         return ibuf;
1270                 }
1271         }
1272         if(ima->rr) {
1273                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1274
1275                 if(rpass) {
1276                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1277                         
1278                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1279                         image_initialize_after_load(ima, ibuf);
1280                         
1281                         ibuf->rect_float= rpass->rect;
1282                         ibuf->flags |= IB_rectfloat;
1283                         ibuf->channels= rpass->channels;
1284                 }
1285         }
1286         
1287         if(ibuf==NULL) 
1288                 ima->ok= 0;
1289         if(iuser)
1290                 iuser->ok= ima->ok;
1291         
1292         return ibuf;
1293 }
1294
1295
1296 /* showing RGBA result itself (from compo/sequence) or
1297    like exr, using layers etc */
1298 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
1299 {
1300         RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
1301         
1302         if(rr && iuser) {
1303                 RenderResult rres;
1304                 float *rectf;
1305                 unsigned int *rect;
1306                 int channels= 4, layer= iuser->layer;
1307                 
1308                 /* this gives active layer, composite or seqence result */
1309                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
1310                 rect= (unsigned int *)rres.rect32;
1311                 rectf= rres.rectf;
1312                 
1313                 /* get compo/seq result by default */
1314                 if(rr->rectf && layer==0);
1315                 else if(rr->layers.first) {
1316                         RenderLayer *rl= BLI_findlink(&rr->layers, iuser->layer-(rr->rectf?1:0));
1317                         if(rl) {
1318                                 /* there's no combined pass, is in renderlayer itself */
1319                                 if(iuser->pass==0) {
1320                                         rectf= rl->rectf;
1321                                 }
1322                                 else {
1323                                         RenderPass *rpass= BLI_findlink(&rl->passes, iuser->pass-1);
1324                                         if(rpass) {
1325                                                 channels= rpass->channels;
1326                                                 rectf= rpass->rect;
1327                                         }
1328                                 }
1329                         }
1330                 }
1331                 
1332                 if(rectf || rect) {
1333                         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1334
1335                         /* make ibuf if needed, and initialize it */
1336                         if(ibuf==NULL) {
1337                                 ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, 0, 0);
1338                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1339                         }
1340                         ibuf->x= rr->rectx;
1341                         ibuf->y= rr->recty;
1342                         
1343                         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1344                                 imb_freerectImBuf(ibuf);
1345                         if(rect)
1346                                 ibuf->rect= rect;
1347                         
1348                         ibuf->rect_float= rectf;
1349                         ibuf->flags |= IB_rectfloat;
1350                         ibuf->channels= channels;
1351                         
1352                         ima->ok= IMA_OK_LOADED;
1353                         return ibuf;
1354                 }
1355         }
1356         
1357         return NULL;
1358 }
1359
1360 /* Checks optional ImageUser and verifies/creates ImBuf. */
1361 /* returns ibuf */
1362 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
1363 {
1364         ImBuf *ibuf= NULL;
1365
1366         /* quick reject tests */
1367         if(ima==NULL) 
1368                 return NULL;
1369         if(iuser) {
1370                 if(iuser->ok==0)
1371                         return NULL;
1372         }
1373         else if(ima->ok==0)
1374                 return NULL;
1375         
1376         BLI_lock_thread(LOCK_IMAGE);
1377         
1378         /* handle image source and types */
1379         if(ima->source==IMA_SRC_MOVIE) {
1380                 /* source is from single file, use flipbook to store ibuf */
1381                 int frame= iuser?iuser->framenr:ima->lastframe;
1382                 
1383                 ibuf= image_get_ibuf(ima, 0, frame);
1384                 if(ibuf==NULL)
1385                         ibuf= image_load_movie_file(ima, iuser, frame);
1386         }
1387         else if(ima->source==IMA_SRC_SEQUENCE) {
1388                 
1389                 if(ima->type==IMA_TYPE_IMAGE) {
1390                         /* regular files, ibufs in flipbook, allows saving */
1391                         int frame= iuser?iuser->framenr:ima->lastframe;
1392                         
1393                         ibuf= image_get_ibuf(ima, 0, frame);
1394                         if(ibuf==NULL)
1395                                 ibuf= image_load_sequence_file(ima, iuser, frame);
1396                         else
1397                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1398                 }
1399                 /* no else; on load the ima type can change */
1400                 if(ima->type==IMA_TYPE_MULTILAYER) {
1401                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
1402                         int frame= iuser?iuser->framenr:ima->lastframe;
1403                         int index= iuser?iuser->multi_index:IMA_NO_INDEX;
1404                         
1405                         ibuf= image_get_ibuf(ima, index, frame);
1406                         if(G.rt) printf("seq multi fra %d id %d ibuf %p %s\n", frame, index, ibuf, ima->id.name);
1407                         if(ibuf==NULL)
1408                                 ibuf= image_load_sequence_multilayer(ima, iuser, frame);
1409                         else
1410                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1411                 }
1412
1413         }
1414         else if(ima->source==IMA_SRC_FILE) {
1415                 
1416                 if(ima->type==IMA_TYPE_IMAGE) {
1417                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1418                         if(ibuf==NULL)
1419                                 ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra);       /* cfra only for '#', this global is OK */
1420                 }
1421                 /* no else; on load the ima type can change */
1422                 if(ima->type==IMA_TYPE_MULTILAYER) {
1423                         /* keeps render result, stores ibufs in listbase, allows saving */
1424                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1425                         if(ibuf==NULL)
1426                                 ibuf= image_get_ibuf_multilayer(ima, iuser);
1427                 }
1428                         
1429         }
1430         else if(ima->source == IMA_SRC_GENERATED) {
1431                 /* generated is: ibuf is allocated dynamically */
1432                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1433                 
1434                 if(ibuf==NULL) {
1435                         if(ima->type==IMA_TYPE_VERSE) {
1436                                 /* todo */
1437                         }
1438                         else { /* always fall back to IMA_TYPE_UV_TEST */
1439                                 /* UV testgrid or black or solid etc */
1440                                 if(ima->gen_x==0) ima->gen_x= 256;
1441                                 if(ima->gen_y==0) ima->gen_y= 256;
1442                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, ima->gen_type);
1443                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1444                         }
1445                 }
1446         }
1447         else if(ima->source == IMA_SRC_VIEWER) {
1448                 if(ima->type==IMA_TYPE_R_RESULT) {
1449                         /* always verify entirely */
1450                         ibuf= image_get_render_result(ima, iuser);
1451                 }
1452                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1453                         int frame= iuser?iuser->framenr:0;
1454                         
1455                         /* Composite Viewer, all handled in compositor */
1456                         ibuf= image_get_ibuf(ima, 0, frame);
1457                         if(ibuf==NULL) {
1458                                 /* fake ibuf, will be filled in compositor */
1459                                 ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
1460                                 image_assign_ibuf(ima, ibuf, 0, frame);
1461                         }
1462                 }
1463         }
1464
1465         if(G.rendering==0)
1466                 tag_image_time(ima);
1467
1468         BLI_unlock_thread(LOCK_IMAGE);
1469
1470         return ibuf;
1471 }
1472
1473
1474 void BKE_image_user_calc_imanr(ImageUser *iuser, int cfra, int fieldnr)
1475 {
1476         int imanr, len;
1477         
1478         /* here (+fie_ima/2-1) makes sure that division happens correctly */
1479         len= (iuser->fie_ima*iuser->frames)/2;
1480         
1481         if(len==0) {
1482                 iuser->framenr= 0;
1483         }
1484         else {
1485                 cfra= cfra - iuser->sfra+1;
1486                 
1487                 /* cyclic */
1488                 if(iuser->cycl) {
1489                         cfra= ( (cfra) % len );
1490                         if(cfra < 0) cfra+= len;
1491                         if(cfra==0) cfra= len;
1492                 }
1493                 
1494                 if(cfra<1) cfra= 1;
1495                 else if(cfra>len) cfra= len;
1496                 
1497                 /* convert current frame to current field */
1498                 cfra= 2*(cfra);
1499                 if(fieldnr) cfra++;
1500                 
1501                 /* transform to images space */
1502                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
1503                 if(imanr>iuser->frames) imanr= iuser->frames;
1504                 imanr+= iuser->offset;
1505                 
1506                 if(iuser->cycl) {
1507                         imanr= ( (imanr) % len );
1508                         while(imanr < 0) imanr+= len;
1509                         if(imanr==0) imanr= len;
1510                 }
1511         
1512                 /* allows image users to handle redraws */
1513                 if(iuser->flag & IMA_ANIM_ALWAYS)
1514                         if(imanr!=iuser->framenr)
1515                                 iuser->flag |= IMA_ANIM_REFRESHED;
1516                 
1517                 iuser->framenr= imanr;
1518                 if(iuser->ok==0) iuser->ok= 1;
1519         }
1520 }
1521