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