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