svn merge ^/trunk/blender -r44189:44204
[blender.git] / source / blender / blenkernel / intern / image.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2006, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/image.c
27  *  \ingroup bke
28  */
29
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #ifndef WIN32 
36 #include <unistd.h>
37 #else
38 #include <io.h>
39 #endif
40
41 #include <time.h>
42
43 #ifdef _WIN32
44 #define open _open
45 #define close _close
46 #endif
47
48 #include "MEM_guardedalloc.h"
49
50 #include "IMB_imbuf_types.h"
51 #include "IMB_imbuf.h"
52
53 #ifdef WITH_OPENEXR
54 #include "intern/openexr/openexr_multi.h"
55 #endif
56
57 #include "DNA_packedFile_types.h"
58 #include "DNA_scene_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_camera_types.h"
61 #include "DNA_sequence_types.h"
62 #include "DNA_userdef_types.h"
63 #include "DNA_brush_types.h"
64 #include "DNA_mesh_types.h"
65 #include "DNA_meshdata_types.h"
66
67 #include "BLI_blenlib.h"
68 #include "BLI_threads.h"
69 #include "BLI_utildefines.h"
70 #include "BLI_bpath.h"
71
72 #include "BKE_bmfont.h"
73 #include "BKE_global.h"
74 #include "BKE_icons.h"
75 #include "BKE_image.h"
76 #include "BKE_library.h"
77 #include "BKE_main.h"
78 #include "BKE_packedFile.h"
79 #include "BKE_scene.h"
80 #include "BKE_node.h"
81 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
82 #include "BKE_utildefines.h"
83
84 #include "BLF_api.h"
85
86 #include "PIL_time.h"
87
88 #include "RE_pipeline.h"
89
90 #include "GPU_draw.h"
91
92 #include "BLO_sys_types.h" // for intptr_t support
93
94 /* max int, to indicate we don't store sequences in ibuf */
95 #define IMA_NO_INDEX    0x7FEFEFEF
96
97 /* quick lookup: supports 1 million frames, thousand passes */
98 #define IMA_MAKE_INDEX(frame, index)    ((frame)<<10)+index
99 #define IMA_INDEX_FRAME(index)                  (index>>10)
100 #define IMA_INDEX_PASS(index)                   (index & ~1023)
101
102 /* ******** IMAGE PROCESSING ************* */
103
104 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
105 {
106         struct ImBuf * tbuf1, * tbuf2;
107         
108         if (ibuf == NULL) return;
109         if (ibuf->flags & IB_fields) return;
110         ibuf->flags |= IB_fields;
111         
112         if (ibuf->rect) {
113                 /* make copies */
114                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
115                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
116                 
117                 ibuf->x *= 2;
118                 
119                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
120                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
121                 
122                 ibuf->x /= 2;
123                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
124                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
125                 
126                 IMB_freeImBuf(tbuf1);
127                 IMB_freeImBuf(tbuf2);
128         }
129         ibuf->y /= 2;
130 }
131
132 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
133 {
134         struct ImBuf * tbuf1, * tbuf2;
135         
136         if (ibuf == NULL) return;
137         if (ibuf->flags & IB_fields) return;
138         ibuf->flags |= IB_fields;
139         
140         if (ibuf->rect) {
141                 /* make copies */
142                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
143                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
144                 
145                 ibuf->x *= 2;
146                 
147                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
148                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
149                 
150                 ibuf->x /= 2;
151                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
152                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
153                 
154                 IMB_freeImBuf(tbuf1);
155                 IMB_freeImBuf(tbuf2);
156         }
157         ibuf->y /= 2;
158 }
159
160 void image_de_interlace(Image *ima, int odd)
161 {
162         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
163         if(ibuf) {
164                 if(odd)
165                         de_interlace_st(ibuf);
166                 else
167                         de_interlace_ng(ibuf);
168         }
169 }
170
171 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
172
173 static void image_free_buffers(Image *ima)
174 {
175         ImBuf *ibuf;
176         
177         while((ibuf = ima->ibufs.first)) {
178                 BLI_remlink(&ima->ibufs, ibuf);
179                 
180                 if (ibuf->userdata) {
181                         MEM_freeN(ibuf->userdata);
182                         ibuf->userdata = NULL;
183                 }
184                 IMB_freeImBuf(ibuf);
185         }
186         
187         if(ima->anim) IMB_free_anim(ima->anim);
188         ima->anim= NULL;
189
190         if(ima->rr) {
191                 RE_FreeRenderResult(ima->rr);
192                 ima->rr= NULL;
193         }       
194         
195         GPU_free_image(ima);
196         
197         ima->ok= IMA_OK;
198 }
199
200 /* called by library too, do not free ima itself */
201 void free_image(Image *ima)
202 {
203         int a;
204
205         image_free_buffers(ima);
206         if (ima->packedfile) {
207                 freePackedFile(ima->packedfile);
208                 ima->packedfile = NULL;
209         }
210         BKE_icon_delete(&ima->id);
211         ima->id.icon_id = 0;
212
213         BKE_previewimg_free(&ima->preview);
214
215         for(a=0; a<IMA_MAX_RENDER_SLOT; a++) {
216                 if(ima->renders[a]) {
217                         RE_FreeRenderResult(ima->renders[a]);
218                         ima->renders[a]= NULL;
219                 }
220         }
221 }
222
223 /* only image block itself */
224 static Image *image_alloc(const char *name, short source, short type)
225 {
226         Image *ima;
227         
228         ima= alloc_libblock(&G.main->image, ID_IM, name);
229         if(ima) {
230                 ima->ok= IMA_OK;
231                 
232                 ima->xrep= ima->yrep= 1;
233                 ima->aspx= ima->aspy= 1.0;
234                 ima->gen_x= 1024; ima->gen_y= 1024;
235                 ima->gen_type= 1;       /* no defines yet? */
236                 
237                 ima->source= source;
238                 ima->type= type;
239         }
240         return ima;
241 }
242
243 /* get the ibuf from an image cache, local use here only */
244 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
245 {
246         /* this function is intended to be thread safe. with IMA_NO_INDEX this
247          * should be OK, but when iterating over the list this is more tricky
248          * */
249         if(index==IMA_NO_INDEX)
250                 return ima->ibufs.first;
251         else {
252                 ImBuf *ibuf;
253
254                 index= IMA_MAKE_INDEX(frame, index);
255                 for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
256                         if(ibuf->index==index)
257                                 return ibuf;
258
259                 return NULL;
260         }
261 }
262
263 /* no ima->ibuf anymore, but listbase */
264 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
265 {
266         if(ibuf) {
267                 BLI_remlink(&ima->ibufs, ibuf);
268                 IMB_freeImBuf(ibuf);
269         }
270 }
271
272
273 /* no ima->ibuf anymore, but listbase */
274 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
275 {
276         if(ibuf) {
277                 ImBuf *link;
278                 
279                 if(index!=IMA_NO_INDEX)
280                         index= IMA_MAKE_INDEX(frame, index);
281                 
282                 /* insert based on index */
283                 for(link= ima->ibufs.first; link; link= link->next)
284                         if(link->index>=index)
285                                 break;
286
287                 ibuf->index= index;
288                 if(ima->flag & IMA_CM_PREDIVIDE)
289                         ibuf->flags |= IB_cm_predivide;
290                 else
291                         ibuf->flags &= ~IB_cm_predivide;
292
293                 /* this function accepts link==NULL */
294                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
295
296                 /* now we don't want copies? */
297                 if(link && ibuf->index==link->index)
298                         image_remove_ibuf(ima, link);
299         }
300 }
301
302 /* empty image block, of similar type and filename */
303 Image *copy_image(Image *ima)
304 {
305         Image *nima= image_alloc(ima->id.name+2, ima->source, ima->type);
306
307         BLI_strncpy(nima->name, ima->name, sizeof(ima->name));
308
309         nima->flag= ima->flag;
310         nima->tpageflag= ima->tpageflag;
311         
312         nima->gen_x= ima->gen_x;
313         nima->gen_y= ima->gen_y;
314         nima->gen_type= ima->gen_type;
315
316         nima->animspeed= ima->animspeed;
317
318         nima->aspx= ima->aspx;
319         nima->aspy= ima->aspy;
320
321         return nima;
322 }
323
324 static void extern_local_image(Image *UNUSED(ima))
325 {
326         /* Nothing to do: images don't link to other IDs. This function exists to
327            match id_make_local pattern. */
328 }
329
330 void make_local_image(struct Image *ima)
331 {
332         Main *bmain= G.main;
333         Tex *tex;
334         Brush *brush;
335         Mesh *me;
336         int is_local= FALSE, is_lib= FALSE;
337
338         /* - only lib users: do nothing
339          * - only local users: set flag
340          * - mixed: make copy
341          */
342
343         if(ima->id.lib==NULL) return;
344
345         /* Can't take short cut here: must check meshes at least because of bogus
346            texface ID refs. - z0r */
347 #if 0
348         if(ima->id.us==1) {
349                 id_clear_lib_data(bmain, &ima->id);
350                 extern_local_image(ima);
351                 return;
352         }
353 #endif
354
355         for(tex= bmain->tex.first; tex; tex= tex->id.next) {
356                 if(tex->ima == ima) {
357                         if(tex->id.lib) is_lib= TRUE;
358                         else is_local= TRUE;
359                 }
360         }
361         for(brush= bmain->brush.first; brush; brush= brush->id.next) {
362                 if(brush->clone.image == ima) {
363                         if(brush->id.lib) is_lib= TRUE;
364                         else is_local= TRUE;
365                 }
366         }
367         for(me= bmain->mesh.first; me; me= me->id.next) {
368                 if(me->mtface) {
369                         MTFace *tface;
370                         int a, i;
371
372                         for(i=0; i<me->fdata.totlayer; i++) {
373                                 if(me->fdata.layers[i].type == CD_MTFACE) {
374                                         tface= (MTFace*)me->fdata.layers[i].data;
375
376                                         for(a=0; a<me->totface; a++, tface++) {
377                                                 if(tface->tpage == ima) {
378                                                         if(me->id.lib) is_lib= TRUE;
379                                                         else is_local= TRUE;
380                                                 }
381                                         }
382                                 }
383                         }
384                 }
385
386                 if(me->mtpoly) {
387                         MTexPoly *mtpoly;
388                         int a, i;
389
390                         for(i=0; i<me->pdata.totlayer; i++) {
391                                 if(me->pdata.layers[i].type == CD_MTEXPOLY) {
392                                         mtpoly= (MTexPoly*)me->pdata.layers[i].data;
393
394                                         for(a=0; a<me->totpoly; a++, mtpoly++) {
395                                                 if(mtpoly->tpage == ima) {
396                                                         if(me->id.lib) is_lib= TRUE;
397                                                         else is_local= TRUE;
398                                                 }
399                                         }
400                                 }
401                         }
402                 }
403
404         }
405
406         if(is_local && is_lib == FALSE) {
407                 id_clear_lib_data(bmain, &ima->id);
408                 extern_local_image(ima);
409         }
410         else if(is_local && is_lib) {
411                 Image *ima_new= copy_image(ima);
412
413                 ima_new->id.us= 0;
414
415                 /* Remap paths of new ID using old library as base. */
416                 BKE_id_lib_local_paths(bmain, ima->id.lib, &ima_new->id);
417
418                 tex= bmain->tex.first;
419                 while(tex) {
420                         if(tex->id.lib==NULL) {
421                                 if(tex->ima==ima) {
422                                         tex->ima = ima_new;
423                                         ima_new->id.us++;
424                                         ima->id.us--;
425                                 }
426                         }
427                         tex= tex->id.next;
428                 }
429                 brush= bmain->brush.first;
430                 while(brush) {
431                         if(brush->id.lib==NULL) {
432                                 if(brush->clone.image==ima) {
433                                         brush->clone.image = ima_new;
434                                         ima_new->id.us++;
435                                         ima->id.us--;
436                                 }
437                         }
438                         brush= brush->id.next;
439                 }
440                 /* Transfer references in texfaces. Texfaces don't add to image ID
441                    user count *unless* there are no other users. See
442                    readfile.c:lib_link_mtface. */
443                 me= bmain->mesh.first;
444                 while(me) {
445                         if(me->mtface) {
446                                 MTFace *tface;
447                                 int a, i;
448
449                                 for(i=0; i<me->fdata.totlayer; i++) {
450                                         if(me->fdata.layers[i].type == CD_MTFACE) {
451                                                 tface= (MTFace*)me->fdata.layers[i].data;
452
453                                                 for(a=0; a<me->totface; a++, tface++) { 
454                                                         if(tface->tpage == ima) {
455                                                                 tface->tpage = ima_new;
456                                                                 if(ima_new->id.us == 0) {
457                                                                         tface->tpage->id.us= 1;
458                                                                 }
459                                                                 id_lib_extern((ID*)ima_new);
460                                                         }
461                                                 }
462                                         }
463                                 }
464                         }
465
466                         if(me->mtpoly) {
467                                 MTexPoly *mtpoly;
468                                 int a, i;
469
470                                 for(i=0; i<me->pdata.totlayer; i++) {
471                                         if(me->pdata.layers[i].type == CD_MTEXPOLY) {
472                                                 mtpoly= (MTexPoly*)me->pdata.layers[i].data;
473
474                                                 for(a=0; a<me->totpoly; a++, mtpoly++) {
475                                                         if(mtpoly->tpage == ima) {
476                                                                 mtpoly->tpage = ima_new;
477                                                                 if(ima_new->id.us == 0) {
478                                                                         mtpoly->tpage->id.us= 1;
479                                                                 }
480                                                                 id_lib_extern((ID*)ima_new);
481                                                         }
482                                                 }
483                                         }
484                                 }
485                         }
486
487                         me= me->id.next;
488                 }
489         }
490 }
491
492 void BKE_image_merge(Image *dest, Image *source)
493 {
494         ImBuf *ibuf;
495         
496         /* sanity check */
497         if(dest && source && dest!=source) {
498         
499                 while((ibuf= source->ibufs.first)) {
500                         BLI_remlink(&source->ibufs, ibuf);
501                         image_assign_ibuf(dest, ibuf, IMA_INDEX_PASS(ibuf->index), IMA_INDEX_FRAME(ibuf->index));
502                 }
503                 
504                 free_libblock(&G.main->image, source);
505         }
506 }
507
508
509 /* checks if image was already loaded, then returns same image */
510 /* otherwise creates new. */
511 /* does not load ibuf itself */
512 /* pass on optional frame for #name images */
513 Image *BKE_add_image_file(const char *name)
514 {
515         Image *ima;
516         int file, len;
517         const char *libname;
518         char str[FILE_MAX], strtest[FILE_MAX];
519         
520         BLI_strncpy(str, name, sizeof(str));
521         BLI_path_abs(str, G.main->name);
522         
523         /* exists? */
524         file= open(str, O_BINARY|O_RDONLY);
525         if(file== -1) return NULL;
526         close(file);
527         
528         /* first search an identical image */
529         for(ima= G.main->image.first; ima; ima= ima->id.next) {
530                 if(ima->source!=IMA_SRC_VIEWER && ima->source!=IMA_SRC_GENERATED) {
531                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
532                         BLI_path_abs(strtest, G.main->name);
533                         
534                         if( strcmp(strtest, str)==0 ) {
535                                 if(ima->anim==NULL || ima->id.us==0) {
536                                         BLI_strncpy(ima->name, name, sizeof(ima->name));        /* for stringcode */
537                                         ima->id.us++;                                                                           /* officially should not, it doesn't link here! */
538                                         if(ima->ok==0)
539                                                 ima->ok= IMA_OK;
540                         /* RETURN! */
541                                         return ima;
542                                 }
543                         }
544                 }
545         }
546         /* add new image */
547         
548         /* create a short library name */
549         len= strlen(name);
550         
551         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
552         libname= name+len;
553         
554         ima= image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
555         BLI_strncpy(ima->name, name, sizeof(ima->name));
556         
557         if(BLI_testextensie_array(name, imb_ext_movie))
558                 ima->source= IMA_SRC_MOVIE;
559         
560         return ima;
561 }
562
563 static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
564 {
565         ImBuf *ibuf;
566         unsigned char *rect= NULL;
567         float *rect_float= NULL;
568         
569         if (floatbuf) {
570                 ibuf= IMB_allocImBuf(width, height, depth, IB_rectfloat);
571                 rect_float= (float*)ibuf->rect_float;
572         }
573         else {
574                 ibuf= IMB_allocImBuf(width, height, depth, IB_rect);
575                 rect= (unsigned char*)ibuf->rect;
576         }
577         
578         BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
579         ibuf->userflags |= IB_BITMAPDIRTY;
580         
581         switch(uvtestgrid) {
582         case 1:
583                 BKE_image_buf_fill_checker(rect, rect_float, width, height);
584                 break;
585         case 2:
586                 BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
587                 break;
588         default:
589                 BKE_image_buf_fill_color(rect, rect_float, width, height, color);
590         }
591
592         return ibuf;
593 }
594
595 /* adds new image block, creates ImBuf and initializes color */
596 Image *BKE_add_image_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
597 {
598         /* on save, type is changed to FILE in editsima.c */
599         Image *ima= image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
600         
601         if (ima) {
602                 ImBuf *ibuf;
603                 
604                 /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* dont do this, this writes in ain invalid filepath! */
605                 ima->gen_x= width;
606                 ima->gen_y= height;
607                 ima->gen_type= uvtestgrid;
608                 ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
609                 
610                 ibuf= add_ibuf_size(width, height, ima->name, depth, floatbuf, uvtestgrid, color);
611                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
612                 
613                 ima->ok= IMA_OK_LOADED;
614         }
615
616         return ima;
617 }
618
619 /* creates an image image owns the imbuf passed */
620 Image *BKE_add_image_imbuf(ImBuf *ibuf)
621 {
622         /* on save, type is changed to FILE in editsima.c */
623         Image *ima;
624
625         ima= image_alloc(BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
626
627         if (ima) {
628                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
629                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
630                 ima->ok= IMA_OK_LOADED;
631         }
632
633         return ima;
634 }
635
636 /* packs rect from memory as PNG */
637 void BKE_image_memorypack(Image *ima)
638 {
639         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
640         
641         if(ibuf==NULL)
642                 return;
643         if (ima->packedfile) {
644                 freePackedFile(ima->packedfile);
645                 ima->packedfile = NULL;
646         }
647         
648         ibuf->ftype= PNG;
649         ibuf->planes= R_IMF_PLANES_RGBA;
650         
651         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
652         if(ibuf->encodedbuffer==NULL) {
653                 printf("memory save for pack error\n");
654         }
655         else {
656                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
657                 
658                 pf->data = ibuf->encodedbuffer;
659                 pf->size = ibuf->encodedsize;
660                 ima->packedfile= pf;
661                 ibuf->encodedbuffer= NULL;
662                 ibuf->encodedsize= 0;
663                 ibuf->userflags &= ~IB_BITMAPDIRTY;
664                 
665                 if(ima->source==IMA_SRC_GENERATED) {
666                         ima->source= IMA_SRC_FILE;
667                         ima->type= IMA_TYPE_IMAGE;
668                 }
669         }
670 }
671
672 void tag_image_time(Image *ima)
673 {
674         if (ima)
675                 ima->lastused = (int)PIL_check_seconds_timer();
676 }
677
678 #if 0
679 static void tag_all_images_time() 
680 {
681         Image *ima;
682         int ctime = (int)PIL_check_seconds_timer();
683
684         ima= G.main->image.first;
685         while(ima) {
686                 if(ima->bindcode || ima->repbind || ima->ibufs.first) {
687                         ima->lastused = ctime;
688                 }
689         }
690 }
691 #endif
692
693 void free_old_images(void)
694 {
695         Image *ima;
696         static int lasttime = 0;
697         int ctime = (int)PIL_check_seconds_timer();
698         
699         /* 
700            Run garbage collector once for every collecting period of time 
701            if textimeout is 0, that's the option to NOT run the collector
702         */
703         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
704                 return;
705
706         /* of course not! */
707         if (G.rendering)
708                 return;
709         
710         lasttime = ctime;
711
712         ima= G.main->image.first;
713         while(ima) {
714                 if((ima->flag & IMA_NOCOLLECT)==0 && ctime - ima->lastused > U.textimeout) {
715                         /*
716                            If it's in GL memory, deallocate and set time tag to current time
717                            This gives textures a "second chance" to be used before dying.
718                         */
719                         if(ima->bindcode || ima->repbind) {
720                                 GPU_free_image(ima);
721                                 ima->lastused = ctime;
722                         }
723                         /* Otherwise, just kill the buffers */
724                         else if (ima->ibufs.first) {
725                                 image_free_buffers(ima);
726                         }
727                 }
728                 ima = ima->id.next;
729         }
730 }
731
732 static uintptr_t image_mem_size(Image *ima)
733 {
734         ImBuf *ibuf, *ibufm;
735         int level;
736         uintptr_t size = 0;
737
738         size= 0;
739         
740         /* viewers have memory depending on other rules, has no valid rect pointer */
741         if(ima->source==IMA_SRC_VIEWER)
742                 return 0;
743         
744         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
745                 if(ibuf->rect) size += MEM_allocN_len(ibuf->rect);
746                 else if(ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
747
748                 for(level=0; level<IB_MIPMAP_LEVELS; level++) {
749                         ibufm= ibuf->mipmap[level];
750                         if(ibufm) {
751                                 if(ibufm->rect) size += MEM_allocN_len(ibufm->rect);
752                                 else if(ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
753                         }
754                 }
755         }
756
757         return size;
758 }
759
760 void BKE_image_print_memlist(void)
761 {
762         Image *ima;
763         uintptr_t size, totsize= 0;
764
765         for(ima= G.main->image.first; ima; ima= ima->id.next)
766                 totsize += image_mem_size(ima);
767
768         printf("\ntotal image memory len: %.3f MB\n", (double)totsize/(double)(1024*1024));
769
770         for(ima= G.main->image.first; ima; ima= ima->id.next) {
771                 size= image_mem_size(ima);
772
773                 if(size)
774                         printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
775         }
776 }
777
778 void BKE_image_free_all_textures(void)
779 {
780         Tex *tex;
781         Image *ima;
782         /* unsigned int totsize= 0; */
783         
784         for(ima= G.main->image.first; ima; ima= ima->id.next)
785                 ima->id.flag &= ~LIB_DOIT;
786         
787         for(tex= G.main->tex.first; tex; tex= tex->id.next)
788                 if(tex->ima)
789                         tex->ima->id.flag |= LIB_DOIT;
790         
791         for(ima= G.main->image.first; ima; ima= ima->id.next) {
792                 if(ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
793                         ImBuf *ibuf;
794                         
795                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
796                                 /* escape when image is painted on */
797                                 if(ibuf->userflags & IB_BITMAPDIRTY)
798                                         break;
799                                 
800                                 /* if(ibuf->mipmap[0]) 
801                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
802                                 else
803                                         totsize+= ibuf->x*ibuf->y*4;*/
804                                 
805                         }
806                         if(ibuf==NULL)
807                                 image_free_buffers(ima);
808                 }
809         }
810         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
811 }
812
813 /* except_frame is weak, only works for seqs without offset... */
814 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
815 {
816         ImBuf *ibuf, *nbuf;
817
818         for(ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
819                 nbuf= ibuf->next;
820                 if(ibuf->userflags & IB_BITMAPDIRTY)
821                         continue;
822                 if(ibuf->index==IMA_NO_INDEX)
823                         continue;
824                 if(except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
825                         BLI_remlink(&ima->ibufs, ibuf);
826                         
827                         if (ibuf->userdata) {
828                                 MEM_freeN(ibuf->userdata);
829                                 ibuf->userdata = NULL;
830                         }
831                         IMB_freeImBuf(ibuf);
832                 }                                       
833         }
834 }
835
836 void BKE_image_all_free_anim_ibufs(int cfra)
837 {
838         Image *ima;
839         
840         for(ima= G.main->image.first; ima; ima= ima->id.next)
841                 if(ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
842                         BKE_image_free_anim_ibufs(ima, cfra);
843 }
844
845
846 /* *********** READ AND WRITE ************** */
847
848 int BKE_imtype_to_ftype(const char imtype)
849 {
850         if(imtype==R_IMF_IMTYPE_TARGA)
851                 return TGA;
852         else if(imtype==R_IMF_IMTYPE_RAWTGA)
853                 return RAWTGA;
854         else if(imtype== R_IMF_IMTYPE_IRIS) 
855                 return IMAGIC;
856 #ifdef WITH_HDR
857         else if (imtype==R_IMF_IMTYPE_RADHDR)
858                 return RADHDR;
859 #endif
860         else if (imtype==R_IMF_IMTYPE_PNG)
861                 return PNG;
862 #ifdef WITH_DDS
863         else if (imtype==R_IMF_IMTYPE_DDS)
864                 return DDS;
865 #endif
866         else if (imtype==R_IMF_IMTYPE_BMP)
867                 return BMP;
868 #ifdef WITH_TIFF
869         else if (imtype==R_IMF_IMTYPE_TIFF)
870                 return TIF;
871 #endif
872         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER)
873                 return OPENEXR;
874 #ifdef WITH_CINEON
875         else if (imtype==R_IMF_IMTYPE_CINEON)
876                 return CINEON;
877         else if (imtype==R_IMF_IMTYPE_DPX)
878                 return DPX;
879 #endif
880 #ifdef WITH_OPENJPEG
881         else if(imtype==R_IMF_IMTYPE_JP2)
882                 return JP2;
883 #endif
884         else
885                 return JPG|90;
886 }
887
888 char BKE_ftype_to_imtype(const int ftype)
889 {
890         if(ftype==0)
891                 return R_IMF_IMTYPE_TARGA;
892         else if(ftype == IMAGIC) 
893                 return R_IMF_IMTYPE_IRIS;
894 #ifdef WITH_HDR
895         else if (ftype & RADHDR)
896                 return R_IMF_IMTYPE_RADHDR;
897 #endif
898         else if (ftype & PNG)
899                 return R_IMF_IMTYPE_PNG;
900 #ifdef WITH_DDS
901         else if (ftype & DDS)
902                 return R_IMF_IMTYPE_DDS;
903 #endif
904         else if (ftype & BMP)
905                 return R_IMF_IMTYPE_BMP;
906 #ifdef WITH_TIFF
907         else if (ftype & TIF)
908                 return R_IMF_IMTYPE_TIFF;
909 #endif
910         else if (ftype & OPENEXR)
911                 return R_IMF_IMTYPE_OPENEXR;
912 #ifdef WITH_CINEON
913         else if (ftype & CINEON)
914                 return R_IMF_IMTYPE_CINEON;
915         else if (ftype & DPX)
916                 return R_IMF_IMTYPE_DPX;
917 #endif
918         else if (ftype & TGA)
919                 return R_IMF_IMTYPE_TARGA;
920         else if(ftype & RAWTGA)
921                 return R_IMF_IMTYPE_RAWTGA;
922 #ifdef WITH_OPENJPEG
923         else if(ftype & JP2)
924                 return R_IMF_IMTYPE_JP2;
925 #endif
926         else
927                 return R_IMF_IMTYPE_JPEG90;
928 }
929
930
931 int BKE_imtype_is_movie(const char imtype)
932 {
933         switch(imtype) {
934         case R_IMF_IMTYPE_AVIRAW:
935         case R_IMF_IMTYPE_AVIJPEG:
936         case R_IMF_IMTYPE_AVICODEC:
937         case R_IMF_IMTYPE_QUICKTIME:
938         case R_IMF_IMTYPE_FFMPEG:
939         case R_IMF_IMTYPE_H264:
940         case R_IMF_IMTYPE_THEORA:
941         case R_IMF_IMTYPE_XVID:
942         case R_IMF_IMTYPE_FRAMESERVER:
943                         return 1;
944         }
945         return 0;
946 }
947
948 int BKE_imtype_supports_zbuf(const char imtype)
949 {
950         switch(imtype) {
951         case R_IMF_IMTYPE_IRIZ:
952         case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
953                         return 1;
954         }
955         return 0;
956 }
957
958 int BKE_imtype_supports_compress(const char imtype)
959 {
960         switch(imtype) {
961         case R_IMF_IMTYPE_PNG:
962                         return 1;
963         }
964         return 0;
965 }
966
967 int BKE_imtype_supports_quality(const char imtype)
968 {
969         switch(imtype) {
970         case R_IMF_IMTYPE_JPEG90:
971         case R_IMF_IMTYPE_JP2:
972         case R_IMF_IMTYPE_AVIJPEG:
973                         return 1;
974         }
975         return 0;
976 }
977
978 char BKE_imtype_valid_channels(const char imtype)
979 {
980         char chan_flag= IMA_CHAN_FLAG_RGB; /* assume all support rgb */
981
982         /* alpha */
983         switch(imtype) {
984         case R_IMF_IMTYPE_TARGA:
985         case R_IMF_IMTYPE_IRIS:
986         case R_IMF_IMTYPE_PNG:
987         /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
988         case R_IMF_IMTYPE_RADHDR:
989         case R_IMF_IMTYPE_TIFF:
990         case R_IMF_IMTYPE_OPENEXR:
991         case R_IMF_IMTYPE_MULTILAYER:
992         case R_IMF_IMTYPE_DDS:
993         case R_IMF_IMTYPE_JP2:
994         case R_IMF_IMTYPE_QUICKTIME:
995                         chan_flag |= IMA_CHAN_FLAG_ALPHA;
996         }
997
998         /* bw */
999         switch(imtype) {
1000         case R_IMF_IMTYPE_PNG:
1001         case R_IMF_IMTYPE_JPEG90:
1002         case R_IMF_IMTYPE_TARGA:
1003         case R_IMF_IMTYPE_RAWTGA:
1004         case R_IMF_IMTYPE_TIFF:
1005         case R_IMF_IMTYPE_IRIS:
1006                         chan_flag |= IMA_CHAN_FLAG_BW;
1007         }
1008
1009         return chan_flag;
1010 }
1011
1012 char BKE_imtype_valid_depths(const char imtype)
1013 {
1014         switch (imtype) {
1015         case R_IMF_IMTYPE_RADHDR:
1016                 return R_IMF_CHAN_DEPTH_32;
1017         case R_IMF_IMTYPE_TIFF:
1018                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1019         case R_IMF_IMTYPE_OPENEXR:
1020                 return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1021         case R_IMF_IMTYPE_MULTILAYER:
1022                 return R_IMF_CHAN_DEPTH_32;
1023         /* eeh, cineone does some strange 10bits per channel */
1024         case R_IMF_IMTYPE_DPX:
1025         case R_IMF_IMTYPE_CINEON:
1026                 return R_IMF_CHAN_DEPTH_12;
1027         case R_IMF_IMTYPE_JP2:
1028                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1029         /* most formats are 8bit only */
1030         default:
1031                 return R_IMF_CHAN_DEPTH_8;
1032         }
1033 }
1034
1035
1036 /* string is from command line --render-format arg, keep in sync with
1037  * creator.c help info */
1038 char BKE_imtype_from_arg(const char *imtype_arg)
1039 {
1040         if      (!strcmp(imtype_arg,"TGA")) return R_IMF_IMTYPE_TARGA;
1041         else if (!strcmp(imtype_arg,"IRIS")) return R_IMF_IMTYPE_IRIS;
1042 #ifdef WITH_DDS
1043         else if (!strcmp(imtype_arg,"DDS")) return R_IMF_IMTYPE_DDS;
1044 #endif
1045         else if (!strcmp(imtype_arg,"JPEG")) return R_IMF_IMTYPE_JPEG90;
1046         else if (!strcmp(imtype_arg,"IRIZ")) return R_IMF_IMTYPE_IRIZ;
1047         else if (!strcmp(imtype_arg,"RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
1048         else if (!strcmp(imtype_arg,"AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
1049         else if (!strcmp(imtype_arg,"AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
1050         else if (!strcmp(imtype_arg,"PNG")) return R_IMF_IMTYPE_PNG;
1051         else if (!strcmp(imtype_arg,"AVICODEC")) return R_IMF_IMTYPE_AVICODEC;
1052         else if (!strcmp(imtype_arg,"QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
1053         else if (!strcmp(imtype_arg,"BMP")) return R_IMF_IMTYPE_BMP;
1054 #ifdef WITH_HDR
1055         else if (!strcmp(imtype_arg,"HDR")) return R_IMF_IMTYPE_RADHDR;
1056 #endif
1057 #ifdef WITH_TIFF
1058         else if (!strcmp(imtype_arg,"TIFF")) return R_IMF_IMTYPE_TIFF;
1059 #endif
1060 #ifdef WITH_OPENEXR
1061         else if (!strcmp(imtype_arg,"EXR")) return R_IMF_IMTYPE_OPENEXR;
1062         else if (!strcmp(imtype_arg,"MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1063 #endif
1064         else if (!strcmp(imtype_arg,"MPEG")) return R_IMF_IMTYPE_FFMPEG;
1065         else if (!strcmp(imtype_arg,"FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
1066 #ifdef WITH_CINEON
1067         else if (!strcmp(imtype_arg,"CINEON")) return R_IMF_IMTYPE_CINEON;
1068         else if (!strcmp(imtype_arg,"DPX")) return R_IMF_IMTYPE_DPX;
1069 #endif
1070 #ifdef WITH_OPENJPEG
1071         else if (!strcmp(imtype_arg,"JP2")) return R_IMF_IMTYPE_JP2;
1072 #endif
1073         else return R_IMF_IMTYPE_INVALID;
1074 }
1075
1076 int BKE_add_image_extension(char *string, const char imtype)
1077 {
1078         const char *extension= NULL;
1079         
1080         if(imtype== R_IMF_IMTYPE_IRIS) {
1081                 if(!BLI_testextensie(string, ".rgb"))
1082                         extension= ".rgb";
1083         }
1084         else if(imtype==R_IMF_IMTYPE_IRIZ) {
1085                 if(!BLI_testextensie(string, ".rgb"))
1086                         extension= ".rgb";
1087         }
1088 #ifdef WITH_HDR
1089         else if(imtype==R_IMF_IMTYPE_RADHDR) {
1090                 if(!BLI_testextensie(string, ".hdr"))
1091                         extension= ".hdr";
1092         }
1093 #endif
1094         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1095                 if(!BLI_testextensie(string, ".png"))
1096                         extension= ".png";
1097         }
1098 #ifdef WITH_DDS
1099         else if(imtype==R_IMF_IMTYPE_DDS) {
1100                 if(!BLI_testextensie(string, ".dds"))
1101                         extension= ".dds";
1102         }
1103 #endif
1104         else if(imtype==R_IMF_IMTYPE_RAWTGA) {
1105                 if(!BLI_testextensie(string, ".tga"))
1106                         extension= ".tga";
1107         }
1108         else if(imtype==R_IMF_IMTYPE_BMP) {
1109                 if(!BLI_testextensie(string, ".bmp"))
1110                         extension= ".bmp";
1111         }
1112 #ifdef WITH_TIFF
1113         else if(imtype==R_IMF_IMTYPE_TIFF) {
1114                 if(!BLI_testextensie(string, ".tif") && 
1115                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
1116         }
1117 #endif
1118 #ifdef WITH_OPENEXR
1119         else if( ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1120                 if(!BLI_testextensie(string, ".exr"))
1121                         extension= ".exr";
1122         }
1123 #endif
1124 #ifdef WITH_CINEON
1125         else if(imtype==R_IMF_IMTYPE_CINEON){
1126                 if (!BLI_testextensie(string, ".cin"))
1127                         extension= ".cin";
1128         }
1129         else if(imtype==R_IMF_IMTYPE_DPX){
1130                 if (!BLI_testextensie(string, ".dpx"))
1131                         extension= ".dpx";
1132         }
1133 #endif
1134         else if(imtype==R_IMF_IMTYPE_TARGA) {
1135                 if(!BLI_testextensie(string, ".tga"))
1136                         extension= ".tga";
1137         }
1138 #ifdef WITH_OPENJPEG
1139         else if(imtype==R_IMF_IMTYPE_JP2) {
1140                 if(!BLI_testextensie(string, ".jp2"))
1141                         extension= ".jp2";
1142         }
1143 #endif
1144         else { //   R_IMF_IMTYPE_AVICODEC, R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1145                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1146                         extension= ".jpg";
1147         }
1148
1149         if(extension) {
1150                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1151                 /* remove any other known image extension */
1152                 if(BLI_testextensie_array(string, imb_ext_image)
1153                                   || (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt))) {
1154                         return BLI_replace_extension(string, FILE_MAX, extension);
1155                 }
1156                 else {
1157                         return BLI_ensure_extension(string, FILE_MAX, extension);
1158                 }
1159                 
1160         }
1161         else {
1162                 return FALSE;
1163         }
1164 }
1165
1166 /* could allow access externally - 512 is for long names, 64 is for id names */
1167 typedef struct StampData {
1168         char    file[512];
1169         char    note[512];
1170         char    date[512];
1171         char    marker[512];
1172         char    time[512];
1173         char    frame[512];
1174         char    camera[64];
1175         char    cameralens[64];
1176         char    scene[64];
1177         char    strip[64];
1178         char    rendertime[64];
1179 } StampData;
1180
1181 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1182 {
1183         char text[256];
1184         struct tm *tl;
1185         time_t t;
1186
1187         if (scene->r.stamp & R_STAMP_FILENAME) {
1188                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s":"%s", G.relbase_valid ? G.main->name:"<untitled>");
1189         } else {
1190                 stamp_data->file[0] = '\0';
1191         }
1192         
1193         if (scene->r.stamp & R_STAMP_NOTE) {
1194                 /* Never do prefix for Note */
1195                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1196         } else {
1197                 stamp_data->note[0] = '\0';
1198         }
1199         
1200         if (scene->r.stamp & R_STAMP_DATE) {
1201                 t = time(NULL);
1202                 tl = localtime(&t);
1203                 BLI_snprintf(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d", tl->tm_year+1900, tl->tm_mon+1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
1204                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s":"%s", text);
1205         } else {
1206                 stamp_data->date[0] = '\0';
1207         }
1208         
1209         if (scene->r.stamp & R_STAMP_MARKER) {
1210                 char *name = scene_find_last_marker_name(scene, CFRA);
1211
1212                 if (name)       BLI_strncpy(text, name, sizeof(text));
1213                 else            BLI_strncpy(text, "<none>", sizeof(text));
1214
1215                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s":"%s", text);
1216         } else {
1217                 stamp_data->marker[0] = '\0';
1218         }
1219         
1220         if (scene->r.stamp & R_STAMP_TIME) {
1221                 int f = (int)(scene->r.cfra % scene->r.frs_sec);
1222                 int s = (int)(scene->r.cfra / scene->r.frs_sec);
1223                 int h= 0;
1224                 int m= 0;
1225
1226                 if (s) {
1227                         m = (int)(s / 60);
1228                         s %= 60;
1229
1230                         if (m) {
1231                                 h = (int)(m / 60);
1232                                 m %= 60;
1233                         }
1234                 }
1235
1236                 if (scene->r.frs_sec < 100)
1237                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%02d", h, m, s, f);
1238                 else
1239                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%03d", h, m, s, f);
1240
1241                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s":"%s", text);
1242         } else {
1243                 stamp_data->time[0] = '\0';
1244         }
1245         
1246         if (scene->r.stamp & R_STAMP_FRAME) {
1247                 char fmtstr[32];
1248                 int digits= 1;
1249                 
1250                 if(scene->r.efra>9)
1251                         digits= 1 + (int) log10(scene->r.efra);
1252
1253                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di":"%%0%di", digits);
1254                 BLI_snprintf (stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1255         } else {
1256                 stamp_data->frame[0] = '\0';
1257         }
1258
1259         if (scene->r.stamp & R_STAMP_CAMERA) {
1260                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s":"%s", camera ? camera->id.name+2 : "<none>");
1261         } else {
1262                 stamp_data->camera[0] = '\0';
1263         }
1264
1265         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1266                 if (camera && camera->type == OB_CAMERA) {
1267                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1268                 }
1269                 else            BLI_strncpy(text, "<none>", sizeof(text));
1270
1271                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s":"%s", text);
1272         } else {
1273                 stamp_data->cameralens[0] = '\0';
1274         }
1275
1276         if (scene->r.stamp & R_STAMP_SCENE) {
1277                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s":"%s", scene->id.name+2);
1278         } else {
1279                 stamp_data->scene[0] = '\0';
1280         }
1281         
1282         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1283                 Sequence *seq= seq_foreground_frame_get(scene, scene->r.cfra);
1284         
1285                 if (seq)        BLI_strncpy(text, seq->name+2, sizeof(text));
1286                 else            BLI_strncpy(text, "<none>", sizeof(text));
1287
1288                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s":"%s", text);
1289         } else {
1290                 stamp_data->strip[0] = '\0';
1291         }
1292
1293         {
1294                 Render *re= RE_GetRender(scene->id.name);
1295                 RenderStats *stats= re ? RE_GetStats(re):NULL;
1296
1297                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1298                         BLI_timestr(stats->lastframetime, text);
1299
1300                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s":"%s", text);
1301                 } else {
1302                         stamp_data->rendertime[0] = '\0';
1303                 }
1304         }
1305 }
1306
1307 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1308 {
1309         struct StampData stamp_data;
1310         float w, h, pad;
1311         int x, y, y_ofs;
1312         float h_fixed;
1313         const int mono= blf_mono_font_render; // XXX
1314
1315 #define BUFF_MARGIN_X 2
1316 #define BUFF_MARGIN_Y 1
1317
1318         if (!rect && !rectf)
1319                 return;
1320         
1321         stampdata(scene, camera, &stamp_data, 1);
1322
1323         /* TODO, do_versions */
1324         if(scene->r.stamp_font_id < 8)
1325                 scene->r.stamp_font_id= 12;
1326
1327         /* set before return */
1328         BLF_size(mono, scene->r.stamp_font_id, 72);
1329         
1330         BLF_buffer(mono, rectf, rect, width, height, channels);
1331         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1332         pad= BLF_width_max(mono);
1333
1334         /* use 'h_fixed' rather than 'h', aligns better */
1335         h_fixed= BLF_height_max(mono);
1336         y_ofs = -BLF_descender(mono);
1337
1338         x= 0;
1339         y= height;
1340
1341         if (stamp_data.file[0]) {
1342                 /* Top left corner */
1343                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1344                 y -= h;
1345
1346                 /* also a little of space to the background. */
1347                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1348
1349                 /* and draw the text. */
1350                 BLF_position(mono, x, y + y_ofs, 0.0);
1351                 BLF_draw_buffer(mono, stamp_data.file);
1352
1353                 /* the extra pixel for background. */
1354                 y -= BUFF_MARGIN_Y * 2;
1355         }
1356
1357         /* Top left corner, below File */
1358         if (stamp_data.note[0]) {
1359                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1360                 y -= h;
1361
1362                 /* and space for background. */
1363                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1364
1365                 BLF_position(mono, x, y + y_ofs, 0.0);
1366                 BLF_draw_buffer(mono, stamp_data.note);
1367
1368                 /* the extra pixel for background. */
1369                 y -= BUFF_MARGIN_Y * 2;
1370         }
1371         
1372         /* Top left corner, below File (or Note) */
1373         if (stamp_data.date[0]) {
1374                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1375                 y -= h;
1376
1377                 /* and space for background. */
1378                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1379
1380                 BLF_position(mono, x, y + y_ofs, 0.0);
1381                 BLF_draw_buffer(mono, stamp_data.date);
1382
1383                 /* the extra pixel for background. */
1384                 y -= BUFF_MARGIN_Y * 2;
1385         }
1386
1387         /* Top left corner, below File, Date or Note */
1388         if (stamp_data.rendertime[0]) {
1389                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1390                 y -= h;
1391
1392                 /* and space for background. */
1393                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1394
1395                 BLF_position(mono, x, y + y_ofs, 0.0);
1396                 BLF_draw_buffer(mono, stamp_data.rendertime);
1397         }
1398
1399         x= 0;
1400         y= 0;
1401
1402         /* Bottom left corner, leaving space for timing */
1403         if (stamp_data.marker[0]) {
1404                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1405
1406                 /* extra space for background. */
1407                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1408
1409                 /* and pad the text. */
1410                 BLF_position(mono, x, y + y_ofs, 0.0);
1411                 BLF_draw_buffer(mono, stamp_data.marker);
1412
1413                 /* space width. */
1414                 x += w + pad;
1415         }
1416         
1417         /* Left bottom corner */
1418         if (stamp_data.time[0]) {
1419                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h= h_fixed;
1420
1421                 /* extra space for background */
1422                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1423
1424                 /* and pad the text. */
1425                 BLF_position(mono, x, y + y_ofs, 0.0);
1426                 BLF_draw_buffer(mono, stamp_data.time);
1427
1428                 /* space width. */
1429                 x += w + pad;
1430         }
1431         
1432         if (stamp_data.frame[0]) {
1433                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h= h_fixed;
1434
1435                 /* extra space for background. */
1436                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1437
1438                 /* and pad the text. */
1439                 BLF_position(mono, x, y + y_ofs, 0.0);
1440                 BLF_draw_buffer(mono, stamp_data.frame);
1441
1442                 /* space width. */
1443                 x += w + pad;
1444         }
1445
1446         if (stamp_data.camera[0]) {
1447                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1448
1449                 /* extra space for background. */
1450                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1451                 BLF_position(mono, x, y + y_ofs, 0.0);
1452                 BLF_draw_buffer(mono, stamp_data.camera);
1453
1454                 /* space width. */
1455                 x += w + pad;
1456         }
1457
1458         if (stamp_data.cameralens[0]) {
1459                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h= h_fixed;
1460
1461                 /* extra space for background. */
1462                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1463                 BLF_position(mono, x, y + y_ofs, 0.0);
1464                 BLF_draw_buffer(mono, stamp_data.cameralens);
1465         }
1466         
1467         if (stamp_data.scene[0]) {
1468                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1469
1470                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1471                 x= width - w - 2;
1472
1473                 /* extra space for background. */
1474                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1475
1476                 /* and pad the text. */
1477                 BLF_position(mono, x, y+y_ofs, 0.0);
1478                 BLF_draw_buffer(mono, stamp_data.scene);
1479         }
1480         
1481         if (stamp_data.strip[0]) {
1482                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h= h_fixed;
1483
1484                 /* Top right corner, with an extra space because blenfont is too strict! */
1485                 x= width - w - pad;
1486                 y= height - h;
1487
1488                 /* extra space for background. */
1489                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x-BUFF_MARGIN_X, y-BUFF_MARGIN_Y, x+w+BUFF_MARGIN_X, y+h+BUFF_MARGIN_Y);
1490
1491                 BLF_position(mono, x, y + y_ofs, 0.0);
1492                 BLF_draw_buffer(mono, stamp_data.strip);
1493         }
1494
1495         /* cleanup the buffer. */
1496         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1497
1498 #undef BUFF_MARGIN_X
1499 #undef BUFF_MARGIN_Y
1500 }
1501
1502 void BKE_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1503 {
1504         struct StampData stamp_data;
1505
1506         if (!ibuf)      return;
1507         
1508         /* fill all the data values, no prefix */
1509         stampdata(scene, camera, &stamp_data, 0);
1510         
1511         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1512         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1513         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1514         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1515         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1516         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1517         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1518         if (stamp_data.cameralens[0]) IMB_metadata_change_field (ibuf, "Lens",  stamp_data.cameralens);
1519         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1520         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1521         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1522 }
1523
1524 int BKE_alphatest_ibuf(ImBuf *ibuf)
1525 {
1526         int tot;
1527         if(ibuf->rect_float) {
1528                 float *buf= ibuf->rect_float;
1529                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1530                         if(buf[3] < 1.0f) {
1531                                 return TRUE;
1532                         }
1533                 }
1534         }
1535         else if (ibuf->rect) {
1536                 unsigned char *buf= (unsigned char *)ibuf->rect;
1537                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1538                         if(buf[3] != 255) {
1539                                 return TRUE;
1540                         }
1541                 }
1542         }
1543
1544         return FALSE;
1545 }
1546
1547 /* note: imf->planes is ignored here, its assumed the image channels
1548  * are already set */
1549 int BKE_write_ibuf(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1550 {
1551         char imtype= imf->imtype;
1552         char compress= imf->compress;
1553         char quality= imf->quality;
1554
1555         int ok;
1556
1557         if(imtype== R_IMF_IMTYPE_IRIS) {
1558                 ibuf->ftype= IMAGIC;
1559         }
1560 #ifdef WITH_HDR
1561         else if (imtype==R_IMF_IMTYPE_RADHDR) {
1562                 ibuf->ftype= RADHDR;
1563         }
1564 #endif
1565         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1566                 ibuf->ftype= PNG;
1567
1568                 if(imtype==R_IMF_IMTYPE_PNG)
1569                         ibuf->ftype |= compress;
1570
1571         }
1572 #ifdef WITH_DDS
1573         else if (imtype==R_IMF_IMTYPE_DDS) {
1574                 ibuf->ftype= DDS;
1575         }
1576 #endif
1577         else if (imtype==R_IMF_IMTYPE_BMP) {
1578                 ibuf->ftype= BMP;
1579         }
1580 #ifdef WITH_TIFF
1581         else if (imtype==R_IMF_IMTYPE_TIFF) {
1582                 ibuf->ftype= TIF;
1583
1584                 if(imf->depth == R_IMF_CHAN_DEPTH_16)
1585                         ibuf->ftype |= TIF_16BIT;
1586         }
1587 #endif
1588 #ifdef WITH_OPENEXR
1589         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER) {
1590                 ibuf->ftype= OPENEXR;
1591                 if(imf->depth == R_IMF_CHAN_DEPTH_16)
1592                         ibuf->ftype |= OPENEXR_HALF;
1593                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1594                 
1595                 if(!(imf->flag & R_IMF_FLAG_ZBUF))
1596                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1597                 
1598         }
1599 #endif
1600 #ifdef WITH_CINEON
1601         else if (imtype==R_IMF_IMTYPE_CINEON) {
1602                 ibuf->ftype = CINEON;
1603         }
1604         else if (imtype==R_IMF_IMTYPE_DPX) {
1605                 ibuf->ftype = DPX;
1606         }
1607 #endif
1608         else if (imtype==R_IMF_IMTYPE_TARGA) {
1609                 ibuf->ftype= TGA;
1610         }
1611         else if(imtype==R_IMF_IMTYPE_RAWTGA) {
1612                 ibuf->ftype= RAWTGA;
1613         }
1614 #ifdef WITH_OPENJPEG
1615         else if(imtype==R_IMF_IMTYPE_JP2) {
1616                 if(quality < 10) quality= 90;
1617                 ibuf->ftype= JP2|quality;
1618                 
1619                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1620                         ibuf->ftype |= JP2_16BIT;
1621                 } else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1622                         ibuf->ftype |= JP2_12BIT;
1623                 }
1624                 
1625                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1626                         ibuf->ftype |= JP2_YCC;
1627                 }
1628
1629                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1630                         ibuf->ftype |= JP2_CINE;
1631                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1632                                 ibuf->ftype |= JP2_CINE_48FPS;
1633                 }
1634         }
1635 #endif
1636         else {
1637                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1638                 if(quality < 10) quality= 90;
1639                 ibuf->ftype= JPG|quality;
1640         }
1641         
1642         BLI_make_existing_file(name);
1643         
1644         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1645         if (ok == 0) {
1646                 perror(name);
1647         }
1648         
1649         return(ok);
1650 }
1651
1652 /* same as BKE_write_ibuf() but crappy workaround not to perminantly modify
1653  * _some_, values in the imbuf */
1654 int BKE_write_ibuf_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1655                       const short save_copy)
1656 {
1657         ImBuf ibuf_back= *ibuf;
1658         int ok;
1659
1660         /* all data is rgba anyway,
1661          * this just controls how to save for some formats */
1662         ibuf->planes= imf->planes;
1663
1664         ok= BKE_write_ibuf(ibuf, name, imf);
1665
1666         if (save_copy) {
1667                 /* note that we are not restoring _all_ settings */
1668                 ibuf->planes= ibuf_back.planes;
1669                 ibuf->ftype=  ibuf_back.ftype;
1670         }
1671
1672         return ok;
1673 }
1674
1675 int BKE_write_ibuf_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1676 {
1677         if(scene && scene->r.stamp & R_STAMP_ALL)
1678                 BKE_stamp_info(scene, camera, ibuf);
1679
1680         return BKE_write_ibuf(ibuf, name, imf);
1681 }
1682
1683
1684 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1685 {
1686         if (string==NULL) return;
1687         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1688         BLI_path_abs(string, relbase);
1689
1690         if(use_frames)
1691                 BLI_path_frame(string, frame, 4);
1692
1693         if(use_ext)
1694                 BKE_add_image_extension(string, imtype);
1695                 
1696 }
1697
1698 /* used by sequencer too */
1699 struct anim *openanim(const char *name, int flags, int streamindex)
1700 {
1701         struct anim *anim;
1702         struct ImBuf *ibuf;
1703         
1704         anim = IMB_open_anim(name, flags, streamindex);
1705         if (anim == NULL) return NULL;
1706
1707         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1708         if (ibuf == NULL) {
1709                 if(BLI_exists(name))
1710                         printf("not an anim: %s\n", name);
1711                 else
1712                         printf("anim file doesn't exist: %s\n", name);
1713                 IMB_free_anim(anim);
1714                 return NULL;
1715         }
1716         IMB_freeImBuf(ibuf);
1717         
1718         return(anim);
1719 }
1720
1721 /* ************************* New Image API *************** */
1722
1723
1724 /* Notes about Image storage 
1725 - packedfile
1726   -> written in .blend
1727 - filename
1728   -> written in .blend
1729 - movie
1730   -> comes from packedfile or filename
1731 - renderresult
1732   -> comes from packedfile or filename
1733 - listbase
1734   -> ibufs from exrhandle
1735 - flipbook array
1736   -> ibufs come from movie, temporary renderresult or sequence
1737 - ibuf
1738   -> comes from packedfile or filename or generated
1739
1740 */
1741
1742
1743 /* forces existence of 1 Image for renderout or nodes, returns Image */
1744 /* name is only for default, when making new one */
1745 Image *BKE_image_verify_viewer(int type, const char *name)
1746 {
1747         Image *ima;
1748         
1749         for(ima=G.main->image.first; ima; ima= ima->id.next)
1750                 if(ima->source==IMA_SRC_VIEWER)
1751                         if(ima->type==type)
1752                                 break;
1753         
1754         if(ima==NULL)
1755                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1756         
1757         /* happens on reload, imagewindow cannot be image user when hidden*/
1758         if(ima->id.us==0)
1759                 id_us_plus(&ima->id);
1760
1761         return ima;
1762 }
1763
1764 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1765 {
1766         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1767 }
1768
1769 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1770 {
1771         if(ima==NULL)
1772                 return;
1773         
1774         switch(signal) {
1775         case IMA_SIGNAL_FREE:
1776                 image_free_buffers(ima);
1777                 if(iuser)
1778                         iuser->ok= 1;
1779                 break;
1780         case IMA_SIGNAL_SRC_CHANGE:
1781                 if(ima->type == IMA_TYPE_UV_TEST)
1782                         if(ima->source != IMA_SRC_GENERATED)
1783                                 ima->type= IMA_TYPE_IMAGE;
1784
1785                 if(ima->source==IMA_SRC_GENERATED) {
1786                         if(ima->gen_x==0 || ima->gen_y==0) {
1787                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1788                                 if(ibuf) {
1789                                         ima->gen_x= ibuf->x;
1790                                         ima->gen_y= ibuf->y;
1791                                 }
1792                         }
1793                 }
1794
1795                 /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
1796                 if(ima->type!=IMA_TYPE_MULTILAYER)
1797                         image_free_buffers(ima);
1798
1799                 ima->ok= 1;
1800                 if(iuser)
1801                         iuser->ok= 1;
1802                 break;
1803                         
1804         case IMA_SIGNAL_RELOAD:
1805                 /* try to repack file */
1806                 if(ima->packedfile) {
1807                         PackedFile *pf;
1808                         pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
1809                         if (pf) {
1810                                 freePackedFile(ima->packedfile);
1811                                 ima->packedfile = pf;
1812                                 image_free_buffers(ima);
1813                         } else {
1814                                 printf("ERROR: Image not available. Keeping packed image\n");
1815                         }
1816                 }
1817                 else
1818                         image_free_buffers(ima);
1819                 
1820                 if(iuser)
1821                         iuser->ok= 1;
1822                 
1823                 break;
1824         case IMA_SIGNAL_USER_NEW_IMAGE:
1825                 if(iuser) {
1826                         iuser->ok= 1;
1827                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1828                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1829                                         iuser->multi_index= 0;
1830                                         iuser->layer= iuser->pass= 0;
1831                                 }
1832                         }
1833                 }
1834                 break;
1835         }
1836         
1837         /* dont use notifiers because they are not 100% sure to succseed
1838          * this also makes sure all scenes are accounted for. */
1839         {
1840                 Scene *scene;
1841                 for(scene= G.main->scene.first; scene; scene= scene->id.next) {
1842                         if(scene->nodetree) {
1843                                 nodeUpdateID(scene->nodetree, &ima->id);
1844                         }
1845                 }
1846         }
1847 }
1848
1849 /* if layer or pass changes, we need an index for the imbufs list */
1850 /* note it is called for rendered results, but it doesnt use the index! */
1851 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1852 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1853 {
1854         RenderLayer *rl;
1855         RenderPass *rpass= NULL;
1856         
1857         if(rr==NULL) 
1858                 return NULL;
1859         
1860         if(iuser) {
1861                 short index= 0, rl_index= 0, rp_index;
1862                 
1863                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1864                         rp_index= 0;
1865                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1866                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1867                                         break;
1868                         if(rpass)
1869                                 break;
1870                 }
1871                 
1872                 if(rpass)
1873                         iuser->multi_index= index;
1874                 else 
1875                         iuser->multi_index= 0;
1876         }
1877         if(rpass==NULL) {
1878                 rl= rr->layers.first;
1879                 if(rl)
1880                         rpass= rl->passes.first;
1881         }
1882         
1883         return rpass;
1884 }
1885
1886 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1887 {
1888         if(ima->rr) {
1889                 return ima->rr;
1890         }
1891         else if(ima->type==IMA_TYPE_R_RESULT) {
1892                 if(ima->render_slot == ima->last_render_slot)
1893                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1894                 else
1895                         return ima->renders[ima->render_slot];
1896         }
1897         else
1898                 return NULL;
1899 }
1900
1901 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1902 {
1903         if(ima->rr);
1904         else if(ima->type==IMA_TYPE_R_RESULT) {
1905                 if(ima->render_slot == ima->last_render_slot)
1906                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1907         }
1908 }
1909
1910 void BKE_image_backup_render(Scene *scene, Image *ima)
1911 {
1912         /* called right before rendering, ima->renders contains render
1913            result pointers for everything but the current render */
1914         Render *re= RE_GetRender(scene->id.name);
1915         int slot= ima->render_slot, last= ima->last_render_slot;
1916
1917         if(slot != last) {
1918                 if(ima->renders[slot]) {
1919                         RE_FreeRenderResult(ima->renders[slot]);
1920                         ima->renders[slot]= NULL;
1921                 }
1922
1923                 ima->renders[last]= NULL;
1924                 RE_SwapResult(re, &ima->renders[last]);
1925         }
1926
1927         ima->last_render_slot= slot;
1928 }
1929
1930 /* after imbuf load, openexr type can return with a exrhandle open */
1931 /* in that case we have to build a render-result */
1932 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1933 {
1934         
1935         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1936
1937 #ifdef WITH_OPENEXR
1938         IMB_exr_close(ibuf->userdata);
1939 #endif
1940
1941         ibuf->userdata= NULL;
1942         if(ima->rr)
1943                 ima->rr->framenr= framenr;
1944 }
1945
1946 /* common stuff to do with images after loading */
1947 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1948 {
1949         /* preview is NULL when it has never been used as an icon before */
1950         if(G.background==0 && ima->preview==NULL)
1951                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1952
1953         /* fields */
1954         if (ima->flag & IMA_FIELDS) {
1955                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1956                 else de_interlace_ng(ibuf);
1957         }
1958         /* timer */
1959         ima->lastused = clock() / CLOCKS_PER_SEC;
1960         
1961         ima->ok= IMA_OK_LOADED;
1962         
1963 }
1964
1965 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1966 {
1967         struct ImBuf *ibuf;
1968         unsigned short numlen;
1969         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1970         int flag;
1971         
1972         /* XXX temp stuff? */
1973         if(ima->lastframe != frame)
1974                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1975
1976         ima->lastframe= frame;
1977         BLI_strncpy(name, ima->name, sizeof(name));
1978         BLI_stringdec(name, head, tail, &numlen);
1979         BLI_stringenc(name, head, tail, numlen, frame);
1980
1981         BLI_path_abs(name, ID_BLEND_PATH(G.main, &ima->id));
1982         
1983         flag= IB_rect|IB_multilayer;
1984         if(ima->flag & IMA_DO_PREMUL)
1985                 flag |= IB_premul;
1986
1987         /* read ibuf */
1988         ibuf = IMB_loadiffname(name, flag);
1989
1990 #if 0
1991         if(ibuf) {
1992                 printf(AT" loaded %s\n", name);
1993         } else {
1994                 printf(AT" missed %s\n", name);
1995         }
1996 #endif
1997
1998         if (ibuf) {
1999 #ifdef WITH_OPENEXR
2000                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2001                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
2002                         image_create_multilayer(ima, ibuf, frame);      
2003                         ima->type= IMA_TYPE_MULTILAYER;
2004                         IMB_freeImBuf(ibuf);
2005                         ibuf= NULL;
2006                 }
2007                 else {
2008                         image_initialize_after_load(ima, ibuf);
2009                         image_assign_ibuf(ima, ibuf, 0, frame);
2010                 }
2011 #else
2012                 image_initialize_after_load(ima, ibuf);
2013                 image_assign_ibuf(ima, ibuf, 0, frame);
2014 #endif
2015         }
2016         else
2017                 ima->ok= 0;
2018         
2019         if(iuser)
2020                 iuser->ok= ima->ok;
2021         
2022         return ibuf;
2023 }
2024
2025 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2026 {
2027         struct ImBuf *ibuf= NULL;
2028         
2029         /* either we load from RenderResult, or we have to load a new one */
2030         
2031         /* check for new RenderResult */
2032         if(ima->rr==NULL || frame!=ima->rr->framenr) {
2033                 /* copy to survive not found multilayer image */
2034                 RenderResult *oldrr= ima->rr;
2035         
2036                 ima->rr= NULL;
2037                 ibuf = image_load_sequence_file(ima, iuser, frame);
2038                 
2039                 if(ibuf) { /* actually an error */
2040                         ima->type= IMA_TYPE_IMAGE;
2041                         printf("error, multi is normal image\n");
2042                 }
2043                 // printf("loaded new result %p\n", ima->rr);
2044                 /* free result if new one found */
2045                 if(ima->rr) {
2046                         // if(oldrr) printf("freed previous result %p\n", oldrr);
2047                         if(oldrr) RE_FreeRenderResult(oldrr);
2048                 }
2049                 else {
2050                         ima->rr= oldrr;
2051                 }
2052
2053         }
2054         if(ima->rr) {
2055                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2056                 
2057                 if(rpass) {
2058                         // printf("load from pass %s\n", rpass->name);
2059                         /* since we free  render results, we copy the rect */
2060                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2061                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
2062                         ibuf->flags |= IB_rectfloat;
2063                         ibuf->mall= IB_rectfloat;
2064                         ibuf->channels= rpass->channels;
2065                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2066                         
2067                         image_initialize_after_load(ima, ibuf);
2068                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
2069                         
2070                 }
2071                 // else printf("pass not found\n");
2072         }
2073         else
2074                 ima->ok= 0;
2075         
2076         if(iuser)
2077                 iuser->ok= ima->ok;
2078         
2079         return ibuf;
2080 }
2081
2082
2083 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2084 {
2085         struct ImBuf *ibuf= NULL;
2086         
2087         ima->lastframe= frame;
2088         
2089         if(ima->anim==NULL) {
2090                 char str[FILE_MAX];
2091                 
2092                 BLI_strncpy(str, ima->name, FILE_MAX);
2093                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2094
2095                 /* FIXME: make several stream accessible in image editor, too*/
2096                 ima->anim = openanim(str, IB_rect, 0);
2097                 
2098                 /* let's initialize this user */
2099                 if(ima->anim && iuser && iuser->frames==0)
2100                         iuser->frames= IMB_anim_get_duration(ima->anim,
2101                                                              IMB_TC_RECORD_RUN);
2102         }
2103         
2104         if(ima->anim) {
2105                 int dur = IMB_anim_get_duration(ima->anim,
2106                                                 IMB_TC_RECORD_RUN);
2107                 int fra= frame-1;
2108                 
2109                 if(fra<0) fra = 0;
2110                 if(fra>(dur-1)) fra= dur-1;
2111                 ibuf = IMB_makeSingleUser(
2112                         IMB_anim_absolute(ima->anim, fra,
2113                                           IMB_TC_RECORD_RUN,
2114                                           IMB_PROXY_NONE));
2115                 
2116                 if(ibuf) {
2117                         image_initialize_after_load(ima, ibuf);
2118                         image_assign_ibuf(ima, ibuf, 0, frame);
2119                 }
2120                 else
2121                         ima->ok= 0;
2122         }
2123         else
2124                 ima->ok= 0;
2125         
2126         if(iuser)
2127                 iuser->ok= ima->ok;
2128         
2129         return ibuf;
2130 }
2131
2132 /* warning, 'iuser' can be NULL */
2133 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2134 {
2135         struct ImBuf *ibuf;
2136         char str[FILE_MAX];
2137         int assign = 0, flag;
2138         
2139         /* always ensure clean ima */
2140         image_free_buffers(ima);
2141         
2142         /* is there a PackedFile with this image ? */
2143         if (ima->packedfile) {
2144                 flag = IB_rect|IB_multilayer;
2145                 if(ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2146                 
2147                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag, "<packed data>");
2148         } 
2149         else {
2150                 flag= IB_rect|IB_multilayer|IB_metadata;
2151                 if(ima->flag & IMA_DO_PREMUL)
2152                         flag |= IB_premul;
2153                         
2154                 /* get the right string */
2155                 BLI_strncpy(str, ima->name, sizeof(str));
2156                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2157                 
2158                 /* read ibuf */
2159                 ibuf = IMB_loadiffname(str, flag);
2160         }
2161         
2162         if (ibuf) {
2163                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2164                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
2165                         image_create_multilayer(ima, ibuf, cfra);       
2166                         ima->type= IMA_TYPE_MULTILAYER;
2167                         IMB_freeImBuf(ibuf);
2168                         ibuf= NULL;
2169                 }
2170                 else {
2171                         image_initialize_after_load(ima, ibuf);
2172                         assign= 1;
2173
2174                         /* check if the image is a font image... */
2175                         detectBitmapFont(ibuf);
2176                         
2177                         /* make packed file for autopack */
2178                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2179                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2180                 }
2181         }
2182         else
2183                 ima->ok= 0;
2184         
2185         if(assign)
2186                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2187
2188         if(iuser)
2189                 iuser->ok= ima->ok;
2190         
2191         return ibuf;
2192 }
2193
2194 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2195 {
2196         ImBuf *ibuf= NULL;
2197         
2198         if(ima->rr==NULL) {
2199                 ibuf = image_load_image_file(ima, iuser, 0);
2200                 if(ibuf) { /* actually an error */
2201                         ima->type= IMA_TYPE_IMAGE;
2202                         return ibuf;
2203                 }
2204         }
2205         if(ima->rr) {
2206                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2207
2208                 if(rpass) {
2209                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2210                         
2211                         image_initialize_after_load(ima, ibuf);
2212                         
2213                         ibuf->rect_float= rpass->rect;
2214                         ibuf->flags |= IB_rectfloat;
2215                         ibuf->channels= rpass->channels;
2216                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2217
2218                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2219                 }
2220         }
2221         
2222         if(ibuf==NULL) 
2223                 ima->ok= 0;
2224         if(iuser)
2225                 iuser->ok= ima->ok;
2226         
2227         return ibuf;
2228 }
2229
2230
2231 /* showing RGBA result itself (from compo/sequence) or
2232    like exr, using layers etc */
2233 /* always returns a single ibuf, also during render progress */
2234 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2235 {
2236         Render *re;
2237         RenderResult rres;
2238         float *rectf, *rectz;
2239         unsigned int *rect;
2240         float dither;
2241         int channels, layer, pass;
2242         ImBuf *ibuf;
2243         int from_render= (ima->render_slot == ima->last_render_slot);
2244
2245         if(!(iuser && iuser->scene))
2246                 return NULL;
2247
2248         /* if we the caller is not going to release the lock, don't give the image */
2249         if(!lock_r)
2250                 return NULL;
2251
2252         re= RE_GetRender(iuser->scene->id.name);
2253
2254         channels= 4;
2255         layer= (iuser)? iuser->layer: 0;
2256         pass= (iuser)? iuser->pass: 0;
2257
2258         if(from_render) {
2259                 RE_AcquireResultImage(re, &rres);
2260         }
2261         else if(ima->renders[ima->render_slot]) {
2262                 rres= *(ima->renders[ima->render_slot]);
2263                 rres.have_combined= rres.rectf != NULL;
2264         }
2265         else
2266                 memset(&rres, 0, sizeof(RenderResult));
2267         
2268         if(!(rres.rectx > 0 && rres.recty > 0)) {
2269                 if(from_render)
2270                         RE_ReleaseResultImage(re);
2271                 return NULL;
2272         }
2273
2274         /* release is done in BKE_image_release_ibuf using lock_r */
2275         if(from_render) {
2276                 BLI_lock_thread(LOCK_VIEWER);
2277                 *lock_r= re;
2278         }
2279
2280         /* this gives active layer, composite or seqence result */
2281         rect= (unsigned int *)rres.rect32;
2282         rectf= rres.rectf;
2283         rectz= rres.rectz;
2284         dither= iuser->scene->r.dither_intensity;
2285
2286         /* combined layer gets added as first layer */
2287         if(rres.have_combined && layer==0);
2288         else if(rres.layers.first) {
2289                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
2290                 if(rl) {
2291                         RenderPass *rpass;
2292
2293                         /* there's no combined pass, is in renderlayer itself */
2294                         if(pass==0) {
2295                                 rectf= rl->rectf;
2296                         }
2297                         else {
2298                                 rpass= BLI_findlink(&rl->passes, pass-1);
2299                                 if(rpass) {
2300                                         channels= rpass->channels;
2301                                         rectf= rpass->rect;
2302                                         dither= 0.0f; /* don't dither passes */
2303                                 }
2304                         }
2305
2306                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
2307                                 if(rpass->passtype == SCE_PASS_Z)
2308                                         rectz= rpass->rect;
2309                 }
2310         }
2311
2312         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2313
2314         /* make ibuf if needed, and initialize it */
2315         if(ibuf==NULL) {
2316                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2317                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2318         }
2319
2320         ibuf->x= rres.rectx;
2321         ibuf->y= rres.recty;
2322         
2323         /* free rect buffer if float buffer changes, so it can be recreated with
2324            the updated result, and also in case we got byte buffer from sequencer,
2325            so we don't keep reference to freed buffer */
2326         if(ibuf->rect_float!=rectf || rect || !rectf)
2327                 imb_freerectImBuf(ibuf);
2328
2329         if(rect)
2330                 ibuf->rect= rect;
2331         
2332         if(rectf) {
2333                 ibuf->rect_float= rectf;
2334                 ibuf->flags |= IB_rectfloat;
2335                 ibuf->channels= channels;
2336         }
2337         else {
2338                 ibuf->rect_float= NULL;
2339                 ibuf->flags &= ~IB_rectfloat;
2340         }
2341
2342         if(rectz) {
2343                 ibuf->zbuf_float= rectz;
2344                 ibuf->flags |= IB_zbuffloat;
2345         }
2346         else {
2347                 ibuf->zbuf_float= NULL;
2348                 ibuf->flags &= ~IB_zbuffloat;
2349         }
2350
2351         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2352         ibuf->profile= (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2353         ibuf->dither= dither;
2354
2355         if(iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2356                 ibuf->flags |= IB_cm_predivide;
2357                 ima->flag |= IMA_CM_PREDIVIDE;
2358         }
2359         else {
2360                 ibuf->flags &= ~IB_cm_predivide;
2361                 ima->flag &= ~IMA_CM_PREDIVIDE;
2362         }
2363
2364         ima->ok= IMA_OK_LOADED;
2365
2366         return ibuf;
2367 }
2368
2369 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2370 {
2371         ImBuf *ibuf = NULL;
2372         int frame = 0, index = 0;
2373
2374         /* see if we already have an appropriate ibuf, with image source and type */
2375         if(ima->source==IMA_SRC_MOVIE) {
2376                 frame= iuser?iuser->framenr:ima->lastframe;
2377                 ibuf= image_get_ibuf(ima, 0, frame);
2378                 /* XXX temp stuff? */
2379                 if(ima->lastframe != frame)
2380                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2381                 ima->lastframe = frame;
2382         }
2383         else if(ima->source==IMA_SRC_SEQUENCE) {
2384                 if(ima->type==IMA_TYPE_IMAGE) {
2385                         frame= iuser?iuser->framenr:ima->lastframe;
2386                         ibuf= image_get_ibuf(ima, 0, frame);
2387                         
2388                         /* XXX temp stuff? */
2389                         if(ima->lastframe != frame) {
2390                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2391                         }
2392                         ima->lastframe = frame;
2393                 }       
2394                 else if(ima->type==IMA_TYPE_MULTILAYER) {
2395                         frame= iuser?iuser->framenr:ima->lastframe;
2396                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2397                         ibuf= image_get_ibuf(ima, index, frame);
2398                 }
2399         }
2400         else if(ima->source==IMA_SRC_FILE) {
2401                 if(ima->type==IMA_TYPE_IMAGE)
2402                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2403                 else if(ima->type==IMA_TYPE_MULTILAYER)
2404                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2405         }
2406         else if(ima->source == IMA_SRC_GENERATED) {
2407                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2408         }
2409         else if(ima->source == IMA_SRC_VIEWER) {
2410                 /* always verify entirely, not that this shouldn't happen
2411                  * as part of texture sampling in rendering anyway, so not
2412                  * a big bottleneck */
2413         }
2414
2415         *frame_r = frame;
2416         *index_r = index;
2417
2418         return ibuf;
2419 }
2420
2421 /* Checks optional ImageUser and verifies/creates ImBuf. */
2422 /* use this one if you want to get a render result in progress,
2423  * if not, use BKE_image_get_ibuf which doesn't require a release */
2424 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2425 {
2426         ImBuf *ibuf= NULL;
2427         float color[] = {0, 0, 0, 1};
2428         int frame= 0, index= 0;
2429
2430         /* This function is intended to be thread-safe. It postpones the mutex lock
2431          * until it needs to load the image, if the image is already there it
2432          * should just get the pointer and return. The reason is that a lot of mutex
2433          * locks appears to be very slow on certain multicore macs, causing a render
2434          * with image textures to actually slow down as more threads are used.
2435          *
2436          * Note that all the image loading functions should also make sure they do
2437          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2438          * That means, the last two steps must be, 1) add the ibuf to the list and
2439          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2440         
2441         if(lock_r)
2442                 *lock_r= NULL;
2443
2444         /* quick reject tests */
2445         if(ima==NULL) 
2446                 return NULL;
2447         if(iuser) {
2448                 if(iuser->ok==0)
2449                         return NULL;
2450         }
2451         else if(ima->ok==0)
2452                 return NULL;
2453         
2454         /* try to get the ibuf without locking */
2455         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2456
2457         if(ibuf == NULL) {
2458                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2459                  * load the image */
2460                 BLI_lock_thread(LOCK_IMAGE);
2461
2462                 /* need to check ok flag and loading ibuf again, because the situation
2463                  * might have changed in the meantime */
2464                 if(iuser) {
2465                         if(iuser->ok==0) {
2466                                 BLI_unlock_thread(LOCK_IMAGE);
2467                                 return NULL;
2468                         }
2469                 }
2470                 else if(ima->ok==0) {
2471                         BLI_unlock_thread(LOCK_IMAGE);
2472                         return NULL;
2473                 }
2474
2475                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2476
2477                 if(ibuf == NULL) {
2478                         /* we are sure we have to load the ibuf, using source and type */
2479                         if(ima->source==IMA_SRC_MOVIE) {
2480                                 /* source is from single file, use flipbook to store ibuf */
2481                                 ibuf= image_load_movie_file(ima, iuser, frame);
2482                         }
2483                         else if(ima->source==IMA_SRC_SEQUENCE) {
2484                                 if(ima->type==IMA_TYPE_IMAGE) {
2485                                         /* regular files, ibufs in flipbook, allows saving */
2486                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2487                                 }
2488                                 /* no else; on load the ima type can change */
2489                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2490                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2491                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2492                                 }
2493                         }
2494                         else if(ima->source==IMA_SRC_FILE) {
2495                                 
2496                                 if(ima->type==IMA_TYPE_IMAGE)
2497                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2498                                 /* no else; on load the ima type can change */
2499                                 if(ima->type==IMA_TYPE_MULTILAYER)
2500                                         /* keeps render result, stores ibufs in listbase, allows saving */
2501                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2502                                         
2503                         }
2504                         else if(ima->source == IMA_SRC_GENERATED) {
2505                                 /* generated is: ibuf is allocated dynamically */
2506                                 /* UV testgrid or black or solid etc */
2507                                 if(ima->gen_x==0) ima->gen_x= 1024;
2508                                 if(ima->gen_y==0) ima->gen_y= 1024;
2509                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2510                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2511                                 ima->ok= IMA_OK_LOADED;
2512                         }
2513                         else if(ima->source == IMA_SRC_VIEWER) {
2514                                 if(ima->type==IMA_TYPE_R_RESULT) {
2515                                         /* always verify entirely, and potentially
2516                                            returns pointer to release later */
2517                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2518                                 }
2519                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2520                                         /* requires lock/unlock, otherwise don't return image */
2521                                         if(lock_r) {
2522                                                 /* unlock in BKE_image_release_ibuf */
2523                                                 BLI_lock_thread(LOCK_VIEWER);
2524                                                 *lock_r= ima;
2525
2526                                                 /* XXX anim play for viewer nodes not yet supported */
2527                                                 frame= 0; // XXX iuser?iuser->framenr:0;
2528                                                 ibuf= image_get_ibuf(ima, 0, frame);
2529
2530                                                 if(!ibuf) {
2531                                                         /* Composite Viewer, all handled in compositor */
2532                                                         /* fake ibuf, will be filled in compositor */
2533                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect);
2534                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2535                                                 }
2536                                         }
2537                                 }
2538                         }
2539                 }
2540
2541                 BLI_unlock_thread(LOCK_IMAGE);
2542         }
2543
2544         tag_image_time(ima);
2545
2546         return ibuf;
2547 }
2548
2549 void BKE_image_release_ibuf(Image *ima, void *lock)
2550 {
2551         /* for getting image during threaded render / compositing, need to release */
2552         if(lock == ima) {
2553                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2554         }
2555         else if(lock) {
2556                 RE_ReleaseResultImage(lock); /* render result */
2557                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2558         }
2559 }
2560
2561 /* warning, this can allocate generated images */
2562 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2563 {
2564         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2565         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2566 }
2567
2568 int BKE_image_user_get_frame(const ImageUser *iuser, int cfra, int fieldnr)
2569 {
2570         const int len= (iuser->fie_ima*iuser->frames)/2;
2571
2572         if(len==0) {
2573                 return 0;
2574         }
2575         else {
2576                 int framenr;
2577                 cfra= cfra - iuser->sfra+1;
2578
2579                 /* cyclic */
2580                 if(iuser->cycl) {
2581                         cfra= ( (cfra) % len );
2582                         if(cfra < 0) cfra+= len;
2583                         if(cfra==0) cfra= len;
2584                 }
2585
2586                 if(cfra<0) cfra= 0;
2587                 else if(cfra>len) cfra= len;
2588
2589                 /* convert current frame to current field */
2590                 cfra= 2*(cfra);
2591                 if(fieldnr) cfra++;
2592
2593                 /* transform to images space */
2594                 framenr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2595                 if(framenr>iuser->frames) framenr= iuser->frames;
2596                 framenr+= iuser->offset;
2597
2598                 if(iuser->cycl) {
2599                         framenr= ( (framenr) % len );
2600                         while(framenr < 0) framenr+= len;
2601                         if(framenr==0) framenr= len;
2602                 }
2603
2604                 return framenr;
2605         }
2606 }
2607
2608 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2609 {
2610         const int framenr= BKE_image_user_get_frame(iuser, cfra, fieldnr);
2611
2612         /* allows image users to handle redraws */
2613         if(iuser->flag & IMA_ANIM_ALWAYS)
2614                 if(framenr!=iuser->framenr)
2615                         iuser->flag |= IMA_ANIM_REFRESHED;
2616
2617         iuser->framenr= framenr;
2618         if(iuser->ok==0) iuser->ok= 1;
2619 }
2620
2621 int BKE_image_has_alpha(struct Image *image)
2622 {
2623         ImBuf *ibuf;
2624         void *lock;
2625         int planes;
2626         
2627         ibuf= BKE_image_acquire_ibuf(image, NULL, &lock);
2628         planes = (ibuf?ibuf->planes:0);
2629         BKE_image_release_ibuf(image, lock);
2630
2631         if (planes == 32)
2632                 return 1;
2633         else
2634                 return 0;
2635 }
2636