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