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