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