screenshot operator now adds file extension in the file selector and has its own...
[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= BLI_open(str, O_BINARY|O_RDONLY, 0);
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 (BLI_path_cmp(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); */ /* don't 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                         /* If it's in GL memory, deallocate and set time tag to current time
716                          * This gives textures a "second chance" to be used before dying. */
717                         if (ima->bindcode || ima->repbind) {
718                                 GPU_free_image(ima);
719                                 ima->lastused = ctime;
720                         }
721                         /* Otherwise, just kill the buffers */
722                         else if (ima->ibufs.first) {
723                                 image_free_buffers(ima);
724                         }
725                 }
726                 ima = ima->id.next;
727         }
728 }
729
730 static uintptr_t image_mem_size(Image *ima)
731 {
732         ImBuf *ibuf, *ibufm;
733         int level;
734         uintptr_t size = 0;
735
736         size= 0;
737         
738         /* viewers have memory depending on other rules, has no valid rect pointer */
739         if (ima->source==IMA_SRC_VIEWER)
740                 return 0;
741         
742         for (ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
743                 if (ibuf->rect) size += MEM_allocN_len(ibuf->rect);
744                 else if (ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
745
746                 for (level=0; level<IB_MIPMAP_LEVELS; level++) {
747                         ibufm= ibuf->mipmap[level];
748                         if (ibufm) {
749                                 if (ibufm->rect) size += MEM_allocN_len(ibufm->rect);
750                                 else if (ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
751                         }
752                 }
753         }
754
755         return size;
756 }
757
758 void BKE_image_print_memlist(void)
759 {
760         Image *ima;
761         uintptr_t size, totsize= 0;
762
763         for (ima= G.main->image.first; ima; ima= ima->id.next)
764                 totsize += image_mem_size(ima);
765
766         printf("\ntotal image memory len: %.3f MB\n", (double)totsize/(double)(1024*1024));
767
768         for (ima= G.main->image.first; ima; ima= ima->id.next) {
769                 size= image_mem_size(ima);
770
771                 if (size)
772                         printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
773         }
774 }
775
776 void BKE_image_free_all_textures(void)
777 {
778         Tex *tex;
779         Image *ima;
780         /* unsigned int totsize= 0; */
781         
782         for (ima= G.main->image.first; ima; ima= ima->id.next)
783                 ima->id.flag &= ~LIB_DOIT;
784         
785         for (tex= G.main->tex.first; tex; tex= tex->id.next)
786                 if (tex->ima)
787                         tex->ima->id.flag |= LIB_DOIT;
788         
789         for (ima= G.main->image.first; ima; ima= ima->id.next) {
790                 if (ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
791                         ImBuf *ibuf;
792                         
793                         for (ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
794                                 /* escape when image is painted on */
795                                 if (ibuf->userflags & IB_BITMAPDIRTY)
796                                         break;
797                                 
798 #if 0
799                                 if (ibuf->mipmap[0]) 
800                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
801                                 else
802                                         totsize+= ibuf->x*ibuf->y*4;
803 #endif
804                         }
805                         if (ibuf==NULL)
806                                 image_free_buffers(ima);
807                 }
808         }
809         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
810 }
811
812 /* except_frame is weak, only works for seqs without offset... */
813 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
814 {
815         ImBuf *ibuf, *nbuf;
816
817         for (ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
818                 nbuf= ibuf->next;
819                 if (ibuf->userflags & IB_BITMAPDIRTY)
820                         continue;
821                 if (ibuf->index==IMA_NO_INDEX)
822                         continue;
823                 if (except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
824                         BLI_remlink(&ima->ibufs, ibuf);
825                         
826                         if (ibuf->userdata) {
827                                 MEM_freeN(ibuf->userdata);
828                                 ibuf->userdata = NULL;
829                         }
830                         IMB_freeImBuf(ibuf);
831                 }                                       
832         }
833 }
834
835 void BKE_image_all_free_anim_ibufs(int cfra)
836 {
837         Image *ima;
838         
839         for (ima= G.main->image.first; ima; ima= ima->id.next)
840                 if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
841                         BKE_image_free_anim_ibufs(ima, cfra);
842 }
843
844
845 /* *********** READ AND WRITE ************** */
846
847 int BKE_imtype_to_ftype(const char imtype)
848 {
849         if (imtype==R_IMF_IMTYPE_TARGA)
850                 return TGA;
851         else if (imtype==R_IMF_IMTYPE_RAWTGA)
852                 return RAWTGA;
853         else if (imtype== R_IMF_IMTYPE_IRIS) 
854                 return IMAGIC;
855 #ifdef WITH_HDR
856         else if (imtype==R_IMF_IMTYPE_RADHDR)
857                 return RADHDR;
858 #endif
859         else if (imtype==R_IMF_IMTYPE_PNG)
860                 return PNG;
861 #ifdef WITH_DDS
862         else if (imtype==R_IMF_IMTYPE_DDS)
863                 return DDS;
864 #endif
865         else if (imtype==R_IMF_IMTYPE_BMP)
866                 return BMP;
867 #ifdef WITH_TIFF
868         else if (imtype==R_IMF_IMTYPE_TIFF)
869                 return TIF;
870 #endif
871         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER)
872                 return OPENEXR;
873 #ifdef WITH_CINEON
874         else if (imtype==R_IMF_IMTYPE_CINEON)
875                 return CINEON;
876         else if (imtype==R_IMF_IMTYPE_DPX)
877                 return DPX;
878 #endif
879 #ifdef WITH_OPENJPEG
880         else if (imtype==R_IMF_IMTYPE_JP2)
881                 return JP2;
882 #endif
883         else
884                 return JPG|90;
885 }
886
887 char BKE_ftype_to_imtype(const int ftype)
888 {
889         if (ftype==0)
890                 return R_IMF_IMTYPE_TARGA;
891         else if (ftype == IMAGIC) 
892                 return R_IMF_IMTYPE_IRIS;
893 #ifdef WITH_HDR
894         else if (ftype & RADHDR)
895                 return R_IMF_IMTYPE_RADHDR;
896 #endif
897         else if (ftype & PNG)
898                 return R_IMF_IMTYPE_PNG;
899 #ifdef WITH_DDS
900         else if (ftype & DDS)
901                 return R_IMF_IMTYPE_DDS;
902 #endif
903         else if (ftype & BMP)
904                 return R_IMF_IMTYPE_BMP;
905 #ifdef WITH_TIFF
906         else if (ftype & TIF)
907                 return R_IMF_IMTYPE_TIFF;
908 #endif
909         else if (ftype & OPENEXR)
910                 return R_IMF_IMTYPE_OPENEXR;
911 #ifdef WITH_CINEON
912         else if (ftype & CINEON)
913                 return R_IMF_IMTYPE_CINEON;
914         else if (ftype & DPX)
915                 return R_IMF_IMTYPE_DPX;
916 #endif
917         else if (ftype & TGA)
918                 return R_IMF_IMTYPE_TARGA;
919         else if (ftype & RAWTGA)
920                 return R_IMF_IMTYPE_RAWTGA;
921 #ifdef WITH_OPENJPEG
922         else if (ftype & JP2)
923                 return R_IMF_IMTYPE_JP2;
924 #endif
925         else
926                 return R_IMF_IMTYPE_JPEG90;
927 }
928
929
930 int BKE_imtype_is_movie(const char imtype)
931 {
932         switch(imtype) {
933         case R_IMF_IMTYPE_AVIRAW:
934         case R_IMF_IMTYPE_AVIJPEG:
935         case R_IMF_IMTYPE_AVICODEC:
936         case R_IMF_IMTYPE_QUICKTIME:
937         case R_IMF_IMTYPE_FFMPEG:
938         case R_IMF_IMTYPE_H264:
939         case R_IMF_IMTYPE_THEORA:
940         case R_IMF_IMTYPE_XVID:
941         case R_IMF_IMTYPE_FRAMESERVER:
942                         return 1;
943         }
944         return 0;
945 }
946
947 int BKE_imtype_supports_zbuf(const char imtype)
948 {
949         switch(imtype) {
950         case R_IMF_IMTYPE_IRIZ:
951         case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
952                         return 1;
953         }
954         return 0;
955 }
956
957 int BKE_imtype_supports_compress(const char imtype)
958 {
959         switch(imtype) {
960         case R_IMF_IMTYPE_PNG:
961                         return 1;
962         }
963         return 0;
964 }
965
966 int BKE_imtype_supports_quality(const char imtype)
967 {
968         switch(imtype) {
969         case R_IMF_IMTYPE_JPEG90:
970         case R_IMF_IMTYPE_JP2:
971         case R_IMF_IMTYPE_AVIJPEG:
972                         return 1;
973         }
974         return 0;
975 }
976
977 char BKE_imtype_valid_channels(const char imtype)
978 {
979         char chan_flag= IMA_CHAN_FLAG_RGB; /* assume all support rgb */
980
981         /* alpha */
982         switch(imtype) {
983         case R_IMF_IMTYPE_TARGA:
984         case R_IMF_IMTYPE_IRIS:
985         case R_IMF_IMTYPE_PNG:
986         /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
987         case R_IMF_IMTYPE_RADHDR:
988         case R_IMF_IMTYPE_TIFF:
989         case R_IMF_IMTYPE_OPENEXR:
990         case R_IMF_IMTYPE_MULTILAYER:
991         case R_IMF_IMTYPE_DDS:
992         case R_IMF_IMTYPE_JP2:
993         case R_IMF_IMTYPE_QUICKTIME:
994                         chan_flag |= IMA_CHAN_FLAG_ALPHA;
995         }
996
997         /* bw */
998         switch(imtype) {
999         case R_IMF_IMTYPE_PNG:
1000         case R_IMF_IMTYPE_JPEG90:
1001         case R_IMF_IMTYPE_TARGA:
1002         case R_IMF_IMTYPE_RAWTGA:
1003         case R_IMF_IMTYPE_TIFF:
1004         case R_IMF_IMTYPE_IRIS:
1005                         chan_flag |= IMA_CHAN_FLAG_BW;
1006         }
1007
1008         return chan_flag;
1009 }
1010
1011 char BKE_imtype_valid_depths(const char imtype)
1012 {
1013         switch (imtype) {
1014         case R_IMF_IMTYPE_RADHDR:
1015                 return R_IMF_CHAN_DEPTH_32;
1016         case R_IMF_IMTYPE_TIFF:
1017                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1018         case R_IMF_IMTYPE_OPENEXR:
1019                 return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1020         case R_IMF_IMTYPE_MULTILAYER:
1021                 return R_IMF_CHAN_DEPTH_32;
1022         /* eeh, cineone does some strange 10bits per channel */
1023         case R_IMF_IMTYPE_DPX:
1024         case R_IMF_IMTYPE_CINEON:
1025                 return R_IMF_CHAN_DEPTH_12;
1026         case R_IMF_IMTYPE_JP2:
1027                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1028         /* most formats are 8bit only */
1029         default:
1030                 return R_IMF_CHAN_DEPTH_8;
1031         }
1032 }
1033
1034
1035 /* string is from command line --render-format arg, keep in sync with
1036  * creator.c help info */
1037 char BKE_imtype_from_arg(const char *imtype_arg)
1038 {
1039         if      (!strcmp(imtype_arg,"TGA")) return R_IMF_IMTYPE_TARGA;
1040         else if (!strcmp(imtype_arg,"IRIS")) return R_IMF_IMTYPE_IRIS;
1041 #ifdef WITH_DDS
1042         else if (!strcmp(imtype_arg,"DDS")) return R_IMF_IMTYPE_DDS;
1043 #endif
1044         else if (!strcmp(imtype_arg,"JPEG")) return R_IMF_IMTYPE_JPEG90;
1045         else if (!strcmp(imtype_arg,"IRIZ")) return R_IMF_IMTYPE_IRIZ;
1046         else if (!strcmp(imtype_arg,"RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
1047         else if (!strcmp(imtype_arg,"AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
1048         else if (!strcmp(imtype_arg,"AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
1049         else if (!strcmp(imtype_arg,"PNG")) return R_IMF_IMTYPE_PNG;
1050         else if (!strcmp(imtype_arg,"AVICODEC")) return R_IMF_IMTYPE_AVICODEC;
1051         else if (!strcmp(imtype_arg,"QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
1052         else if (!strcmp(imtype_arg,"BMP")) return R_IMF_IMTYPE_BMP;
1053 #ifdef WITH_HDR
1054         else if (!strcmp(imtype_arg,"HDR")) return R_IMF_IMTYPE_RADHDR;
1055 #endif
1056 #ifdef WITH_TIFF
1057         else if (!strcmp(imtype_arg,"TIFF")) return R_IMF_IMTYPE_TIFF;
1058 #endif
1059 #ifdef WITH_OPENEXR
1060         else if (!strcmp(imtype_arg,"EXR")) return R_IMF_IMTYPE_OPENEXR;
1061         else if (!strcmp(imtype_arg,"MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1062 #endif
1063         else if (!strcmp(imtype_arg,"MPEG")) return R_IMF_IMTYPE_FFMPEG;
1064         else if (!strcmp(imtype_arg,"FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
1065 #ifdef WITH_CINEON
1066         else if (!strcmp(imtype_arg,"CINEON")) return R_IMF_IMTYPE_CINEON;
1067         else if (!strcmp(imtype_arg,"DPX")) return R_IMF_IMTYPE_DPX;
1068 #endif
1069 #ifdef WITH_OPENJPEG
1070         else if (!strcmp(imtype_arg,"JP2")) return R_IMF_IMTYPE_JP2;
1071 #endif
1072         else return R_IMF_IMTYPE_INVALID;
1073 }
1074
1075 int BKE_add_image_extension(char *string, const char imtype)
1076 {
1077         const char *extension= NULL;
1078         
1079         if (imtype== R_IMF_IMTYPE_IRIS) {
1080                 if (!BLI_testextensie(string, ".rgb"))
1081                         extension= ".rgb";
1082         }
1083         else if (imtype==R_IMF_IMTYPE_IRIZ) {
1084                 if (!BLI_testextensie(string, ".rgb"))
1085                         extension= ".rgb";
1086         }
1087 #ifdef WITH_HDR
1088         else if (imtype==R_IMF_IMTYPE_RADHDR) {
1089                 if (!BLI_testextensie(string, ".hdr"))
1090                         extension= ".hdr";
1091         }
1092 #endif
1093         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1094                 if (!BLI_testextensie(string, ".png"))
1095                         extension= ".png";
1096         }
1097 #ifdef WITH_DDS
1098         else if (imtype==R_IMF_IMTYPE_DDS) {
1099                 if (!BLI_testextensie(string, ".dds"))
1100                         extension= ".dds";
1101         }
1102 #endif
1103         else if (imtype==R_IMF_IMTYPE_RAWTGA) {
1104                 if (!BLI_testextensie(string, ".tga"))
1105                         extension= ".tga";
1106         }
1107         else if (imtype==R_IMF_IMTYPE_BMP) {
1108                 if (!BLI_testextensie(string, ".bmp"))
1109                         extension= ".bmp";
1110         }
1111 #ifdef WITH_TIFF
1112         else if (imtype==R_IMF_IMTYPE_TIFF) {
1113                 if (!BLI_testextensie(string, ".tif") && 
1114                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
1115         }
1116 #endif
1117 #ifdef WITH_OPENEXR
1118         else if ( ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1119                 if (!BLI_testextensie(string, ".exr"))
1120                         extension= ".exr";
1121         }
1122 #endif
1123 #ifdef WITH_CINEON
1124         else if (imtype==R_IMF_IMTYPE_CINEON) {
1125                 if (!BLI_testextensie(string, ".cin"))
1126                         extension= ".cin";
1127         }
1128         else if (imtype==R_IMF_IMTYPE_DPX) {
1129                 if (!BLI_testextensie(string, ".dpx"))
1130                         extension= ".dpx";
1131         }
1132 #endif
1133         else if (imtype==R_IMF_IMTYPE_TARGA) {
1134                 if (!BLI_testextensie(string, ".tga"))
1135                         extension= ".tga";
1136         }
1137 #ifdef WITH_OPENJPEG
1138         else if (imtype==R_IMF_IMTYPE_JP2) {
1139                 if (!BLI_testextensie(string, ".jp2"))
1140                         extension= ".jp2";
1141         }
1142 #endif
1143         else { //   R_IMF_IMTYPE_AVICODEC, R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1144                 if (!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1145                         extension= ".jpg";
1146         }
1147
1148         if (extension) {
1149                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1150                 /* remove any other known image extension */
1151                 if (BLI_testextensie_array(string, imb_ext_image) ||
1152                     (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt)))
1153                 {
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 void BKE_imformat_defaults(ImageFormatData *im_format)
1167 {
1168         memset(im_format, 0, sizeof(*im_format));
1169         im_format->planes = R_IMF_PLANES_RGB;
1170         im_format->imtype = R_IMF_IMTYPE_PNG;
1171         im_format->quality = 90;
1172         im_format->compress = 90;
1173 }
1174
1175 /* could allow access externally - 512 is for long names, 64 is for id names */
1176 typedef struct StampData {
1177         char    file[512];
1178         char    note[512];
1179         char    date[512];
1180         char    marker[512];
1181         char    time[512];
1182         char    frame[512];
1183         char    camera[64];
1184         char    cameralens[64];
1185         char    scene[64];
1186         char    strip[64];
1187         char    rendertime[64];
1188 } StampData;
1189
1190 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1191 {
1192         char text[256];
1193         struct tm *tl;
1194         time_t t;
1195
1196         if (scene->r.stamp & R_STAMP_FILENAME) {
1197                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s":"%s", G.relbase_valid ? G.main->name:"<untitled>");
1198         }
1199         else {
1200                 stamp_data->file[0] = '\0';
1201         }
1202         
1203         if (scene->r.stamp & R_STAMP_NOTE) {
1204                 /* Never do prefix for Note */
1205                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1206         }
1207         else {
1208                 stamp_data->note[0] = '\0';
1209         }
1210         
1211         if (scene->r.stamp & R_STAMP_DATE) {
1212                 t = time(NULL);
1213                 tl = localtime(&t);
1214                 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);
1215                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s":"%s", text);
1216         }
1217         else {
1218                 stamp_data->date[0] = '\0';
1219         }
1220         
1221         if (scene->r.stamp & R_STAMP_MARKER) {
1222                 char *name = scene_find_last_marker_name(scene, CFRA);
1223
1224                 if (name)       BLI_strncpy(text, name, sizeof(text));
1225                 else            BLI_strncpy(text, "<none>", sizeof(text));
1226
1227                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s":"%s", text);
1228         }
1229         else {
1230                 stamp_data->marker[0] = '\0';
1231         }
1232         
1233         if (scene->r.stamp & R_STAMP_TIME) {
1234                 int f = (int)(scene->r.cfra % scene->r.frs_sec);
1235                 int s = (int)(scene->r.cfra / scene->r.frs_sec);
1236                 int h= 0;
1237                 int m= 0;
1238
1239                 if (s) {
1240                         m = (int)(s / 60);
1241                         s %= 60;
1242
1243                         if (m) {
1244                                 h = (int)(m / 60);
1245                                 m %= 60;
1246                         }
1247                 }
1248
1249                 if (scene->r.frs_sec < 100)
1250                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%02d", h, m, s, f);
1251                 else
1252                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%03d", h, m, s, f);
1253
1254                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s":"%s", text);
1255         }
1256         else {
1257                 stamp_data->time[0] = '\0';
1258         }
1259         
1260         if (scene->r.stamp & R_STAMP_FRAME) {
1261                 char fmtstr[32];
1262                 int digits= 1;
1263                 
1264                 if (scene->r.efra>9)
1265                         digits= 1 + (int) log10(scene->r.efra);
1266
1267                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di":"%%0%di", digits);
1268                 BLI_snprintf (stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1269         }
1270         else {
1271                 stamp_data->frame[0] = '\0';
1272         }
1273
1274         if (scene->r.stamp & R_STAMP_CAMERA) {
1275                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s":"%s", camera ? camera->id.name+2 : "<none>");
1276         }
1277         else {
1278                 stamp_data->camera[0] = '\0';
1279         }
1280
1281         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1282                 if (camera && camera->type == OB_CAMERA) {
1283                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1284                 }
1285                 else            BLI_strncpy(text, "<none>", sizeof(text));
1286
1287                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s":"%s", text);
1288         }
1289         else {
1290                 stamp_data->cameralens[0] = '\0';
1291         }
1292
1293         if (scene->r.stamp & R_STAMP_SCENE) {
1294                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s":"%s", scene->id.name+2);
1295         }
1296         else {
1297                 stamp_data->scene[0] = '\0';
1298         }
1299         
1300         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1301                 Sequence *seq= seq_foreground_frame_get(scene, scene->r.cfra);
1302         
1303                 if (seq)        BLI_strncpy(text, seq->name+2, sizeof(text));
1304                 else            BLI_strncpy(text, "<none>", sizeof(text));
1305
1306                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s":"%s", text);
1307         }
1308         else {
1309                 stamp_data->strip[0] = '\0';
1310         }
1311
1312         {
1313                 Render *re= RE_GetRender(scene->id.name);
1314                 RenderStats *stats= re ? RE_GetStats(re):NULL;
1315
1316                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1317                         BLI_timestr(stats->lastframetime, text);
1318
1319                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s":"%s", text);
1320                 }
1321                 else {
1322                         stamp_data->rendertime[0] = '\0';
1323                 }
1324         }
1325 }
1326
1327 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1328 {
1329         struct StampData stamp_data;
1330         float w, h, pad;
1331         int x, y, y_ofs;
1332         float h_fixed;
1333         const int mono= blf_mono_font_render; // XXX
1334
1335 #define BUFF_MARGIN_X 2
1336 #define BUFF_MARGIN_Y 1
1337
1338         if (!rect && !rectf)
1339                 return;
1340         
1341         stampdata(scene, camera, &stamp_data, 1);
1342
1343         /* TODO, do_versions */
1344         if (scene->r.stamp_font_id < 8)
1345                 scene->r.stamp_font_id= 12;
1346
1347         /* set before return */
1348         BLF_size(mono, scene->r.stamp_font_id, 72);
1349         
1350         BLF_buffer(mono, rectf, rect, width, height, channels);
1351         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1352         pad= BLF_width_max(mono);
1353
1354         /* use 'h_fixed' rather than 'h', aligns better */
1355         h_fixed= BLF_height_max(mono);
1356         y_ofs = -BLF_descender(mono);
1357
1358         x= 0;
1359         y= height;
1360
1361         if (stamp_data.file[0]) {
1362                 /* Top left corner */
1363                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1364                 y -= h;
1365
1366                 /* also a little of space to the background. */
1367                 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);
1368
1369                 /* and draw the text. */
1370                 BLF_position(mono, x, y + y_ofs, 0.0);
1371                 BLF_draw_buffer(mono, stamp_data.file);
1372
1373                 /* the extra pixel for background. */
1374                 y -= BUFF_MARGIN_Y * 2;
1375         }
1376
1377         /* Top left corner, below File */
1378         if (stamp_data.note[0]) {
1379                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1380                 y -= h;
1381
1382                 /* and space for background. */
1383                 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);
1384
1385                 BLF_position(mono, x, y + y_ofs, 0.0);
1386                 BLF_draw_buffer(mono, stamp_data.note);
1387
1388                 /* the extra pixel for background. */
1389                 y -= BUFF_MARGIN_Y * 2;
1390         }
1391         
1392         /* Top left corner, below File (or Note) */
1393         if (stamp_data.date[0]) {
1394                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1395                 y -= h;
1396
1397                 /* and space for background. */
1398                 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);
1399
1400                 BLF_position(mono, x, y + y_ofs, 0.0);
1401                 BLF_draw_buffer(mono, stamp_data.date);
1402
1403                 /* the extra pixel for background. */
1404                 y -= BUFF_MARGIN_Y * 2;
1405         }
1406
1407         /* Top left corner, below File, Date or Note */
1408         if (stamp_data.rendertime[0]) {
1409                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1410                 y -= h;
1411
1412                 /* and space for background. */
1413                 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);
1414
1415                 BLF_position(mono, x, y + y_ofs, 0.0);
1416                 BLF_draw_buffer(mono, stamp_data.rendertime);
1417         }
1418
1419         x= 0;
1420         y= 0;
1421
1422         /* Bottom left corner, leaving space for timing */
1423         if (stamp_data.marker[0]) {
1424                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1425
1426                 /* extra space for background. */
1427                 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);
1428
1429                 /* and pad the text. */
1430                 BLF_position(mono, x, y + y_ofs, 0.0);
1431                 BLF_draw_buffer(mono, stamp_data.marker);
1432
1433                 /* space width. */
1434                 x += w + pad;
1435         }
1436         
1437         /* Left bottom corner */
1438         if (stamp_data.time[0]) {
1439                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h= h_fixed;
1440
1441                 /* extra space for background */
1442                 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);
1443
1444                 /* and pad the text. */
1445                 BLF_position(mono, x, y + y_ofs, 0.0);
1446                 BLF_draw_buffer(mono, stamp_data.time);
1447
1448                 /* space width. */
1449                 x += w + pad;
1450         }
1451         
1452         if (stamp_data.frame[0]) {
1453                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h= h_fixed;
1454
1455                 /* extra space for background. */
1456                 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);
1457
1458                 /* and pad the text. */
1459                 BLF_position(mono, x, y + y_ofs, 0.0);
1460                 BLF_draw_buffer(mono, stamp_data.frame);
1461
1462                 /* space width. */
1463                 x += w + pad;
1464         }
1465
1466         if (stamp_data.camera[0]) {
1467                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1468
1469                 /* extra space for background. */
1470                 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);
1471                 BLF_position(mono, x, y + y_ofs, 0.0);
1472                 BLF_draw_buffer(mono, stamp_data.camera);
1473
1474                 /* space width. */
1475                 x += w + pad;
1476         }
1477
1478         if (stamp_data.cameralens[0]) {
1479                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h= h_fixed;
1480
1481                 /* extra space for background. */
1482                 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);
1483                 BLF_position(mono, x, y + y_ofs, 0.0);
1484                 BLF_draw_buffer(mono, stamp_data.cameralens);
1485         }
1486         
1487         if (stamp_data.scene[0]) {
1488                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1489
1490                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1491                 x= width - w - 2;
1492
1493                 /* extra space for background. */
1494                 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);
1495
1496                 /* and pad the text. */
1497                 BLF_position(mono, x, y+y_ofs, 0.0);
1498                 BLF_draw_buffer(mono, stamp_data.scene);
1499         }
1500         
1501         if (stamp_data.strip[0]) {
1502                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h= h_fixed;
1503
1504                 /* Top right corner, with an extra space because blenfont is too strict! */
1505                 x= width - w - pad;
1506                 y= height - h;
1507
1508                 /* extra space for background. */
1509                 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);
1510
1511                 BLF_position(mono, x, y + y_ofs, 0.0);
1512                 BLF_draw_buffer(mono, stamp_data.strip);
1513         }
1514
1515         /* cleanup the buffer. */
1516         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1517
1518 #undef BUFF_MARGIN_X
1519 #undef BUFF_MARGIN_Y
1520 }
1521
1522 void BKE_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1523 {
1524         struct StampData stamp_data;
1525
1526         if (!ibuf)      return;
1527         
1528         /* fill all the data values, no prefix */
1529         stampdata(scene, camera, &stamp_data, 0);
1530         
1531         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1532         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1533         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1534         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1535         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1536         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1537         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1538         if (stamp_data.cameralens[0]) IMB_metadata_change_field (ibuf, "Lens",  stamp_data.cameralens);
1539         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1540         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1541         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1542 }
1543
1544 int BKE_alphatest_ibuf(ImBuf *ibuf)
1545 {
1546         int tot;
1547         if (ibuf->rect_float) {
1548                 float *buf= ibuf->rect_float;
1549                 for (tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1550                         if (buf[3] < 1.0f) {
1551                                 return TRUE;
1552                         }
1553                 }
1554         }
1555         else if (ibuf->rect) {
1556                 unsigned char *buf= (unsigned char *)ibuf->rect;
1557                 for (tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1558                         if (buf[3] != 255) {
1559                                 return TRUE;
1560                         }
1561                 }
1562         }
1563
1564         return FALSE;
1565 }
1566
1567 /* note: imf->planes is ignored here, its assumed the image channels
1568  * are already set */
1569 int BKE_write_ibuf(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1570 {
1571         char imtype= imf->imtype;
1572         char compress= imf->compress;
1573         char quality= imf->quality;
1574
1575         int ok;
1576
1577         if (imtype== R_IMF_IMTYPE_IRIS) {
1578                 ibuf->ftype= IMAGIC;
1579         }
1580 #ifdef WITH_HDR
1581         else if (imtype==R_IMF_IMTYPE_RADHDR) {
1582                 ibuf->ftype= RADHDR;
1583         }
1584 #endif
1585         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1586                 ibuf->ftype= PNG;
1587
1588                 if (imtype==R_IMF_IMTYPE_PNG)
1589                         ibuf->ftype |= compress;
1590
1591         }
1592 #ifdef WITH_DDS
1593         else if (imtype==R_IMF_IMTYPE_DDS) {
1594                 ibuf->ftype= DDS;
1595         }
1596 #endif
1597         else if (imtype==R_IMF_IMTYPE_BMP) {
1598                 ibuf->ftype= BMP;
1599         }
1600 #ifdef WITH_TIFF
1601         else if (imtype==R_IMF_IMTYPE_TIFF) {
1602                 ibuf->ftype= TIF;
1603
1604                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1605                         ibuf->ftype |= TIF_16BIT;
1606         }
1607 #endif
1608 #ifdef WITH_OPENEXR
1609         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER) {
1610                 ibuf->ftype= OPENEXR;
1611                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1612                         ibuf->ftype |= OPENEXR_HALF;
1613                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1614                 
1615                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1616                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1617                 
1618         }
1619 #endif
1620 #ifdef WITH_CINEON
1621         else if (imtype==R_IMF_IMTYPE_CINEON) {
1622                 ibuf->ftype = CINEON;
1623         }
1624         else if (imtype==R_IMF_IMTYPE_DPX) {
1625                 ibuf->ftype = DPX;
1626         }
1627 #endif
1628         else if (imtype==R_IMF_IMTYPE_TARGA) {
1629                 ibuf->ftype= TGA;
1630         }
1631         else if (imtype==R_IMF_IMTYPE_RAWTGA) {
1632                 ibuf->ftype= RAWTGA;
1633         }
1634 #ifdef WITH_OPENJPEG
1635         else if (imtype==R_IMF_IMTYPE_JP2) {
1636                 if (quality < 10) quality= 90;
1637                 ibuf->ftype= JP2|quality;
1638                 
1639                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1640                         ibuf->ftype |= JP2_16BIT;
1641                 }
1642                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1643                         ibuf->ftype |= JP2_12BIT;
1644                 }
1645                 
1646                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1647                         ibuf->ftype |= JP2_YCC;
1648                 }
1649
1650                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1651                         ibuf->ftype |= JP2_CINE;
1652                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1653                                 ibuf->ftype |= JP2_CINE_48FPS;
1654                 }
1655         }
1656 #endif
1657         else {
1658                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1659                 if (quality < 10) quality= 90;
1660                 ibuf->ftype= JPG|quality;
1661         }
1662         
1663         BLI_make_existing_file(name);
1664         
1665         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1666         if (ok == 0) {
1667                 perror(name);
1668         }
1669         
1670         return(ok);
1671 }
1672
1673 /* same as BKE_write_ibuf() but crappy workaround not to perminantly modify
1674  * _some_, values in the imbuf */
1675 int BKE_write_ibuf_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1676                       const short save_copy)
1677 {
1678         ImBuf ibuf_back= *ibuf;
1679         int ok;
1680
1681         /* all data is rgba anyway,
1682          * this just controls how to save for some formats */
1683         ibuf->planes= imf->planes;
1684
1685         ok= BKE_write_ibuf(ibuf, name, imf);
1686
1687         if (save_copy) {
1688                 /* note that we are not restoring _all_ settings */
1689                 ibuf->planes= ibuf_back.planes;
1690                 ibuf->ftype=  ibuf_back.ftype;
1691         }
1692
1693         return ok;
1694 }
1695
1696 int BKE_write_ibuf_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1697 {
1698         if (scene && scene->r.stamp & R_STAMP_ALL)
1699                 BKE_stamp_info(scene, camera, ibuf);
1700
1701         return BKE_write_ibuf(ibuf, name, imf);
1702 }
1703
1704
1705 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1706 {
1707         if (string==NULL) return;
1708         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1709         BLI_path_abs(string, relbase);
1710
1711         if (use_frames)
1712                 BLI_path_frame(string, frame, 4);
1713
1714         if (use_ext)
1715                 BKE_add_image_extension(string, imtype);
1716                 
1717 }
1718
1719 /* used by sequencer too */
1720 struct anim *openanim(const char *name, int flags, int streamindex)
1721 {
1722         struct anim *anim;
1723         struct ImBuf *ibuf;
1724         
1725         anim = IMB_open_anim(name, flags, streamindex);
1726         if (anim == NULL) return NULL;
1727
1728         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1729         if (ibuf == NULL) {
1730                 if (BLI_exists(name))
1731                         printf("not an anim: %s\n", name);
1732                 else
1733                         printf("anim file doesn't exist: %s\n", name);
1734                 IMB_free_anim(anim);
1735                 return NULL;
1736         }
1737         IMB_freeImBuf(ibuf);
1738         
1739         return(anim);
1740 }
1741
1742 /* ************************* New Image API *************** */
1743
1744
1745 /* Notes about Image storage 
1746  * - packedfile
1747  *   -> written in .blend
1748  * - filename
1749  *   -> written in .blend
1750  * - movie
1751  *   -> comes from packedfile or filename
1752  * - renderresult
1753  *   -> comes from packedfile or filename
1754  * - listbase
1755  *   -> ibufs from exrhandle
1756  * - flipbook array
1757  *   -> ibufs come from movie, temporary renderresult or sequence
1758  * - ibuf
1759  *   -> comes from packedfile or filename or generated
1760  */
1761
1762
1763 /* forces existence of 1 Image for renderout or nodes, returns Image */
1764 /* name is only for default, when making new one */
1765 Image *BKE_image_verify_viewer(int type, const char *name)
1766 {
1767         Image *ima;
1768         
1769         for (ima=G.main->image.first; ima; ima= ima->id.next)
1770                 if (ima->source==IMA_SRC_VIEWER)
1771                         if (ima->type==type)
1772                                 break;
1773         
1774         if (ima==NULL)
1775                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1776         
1777         /* happens on reload, imagewindow cannot be image user when hidden*/
1778         if (ima->id.us==0)
1779                 id_us_plus(&ima->id);
1780
1781         return ima;
1782 }
1783
1784 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1785 {
1786         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1787 }
1788
1789 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1790 {
1791         if (ima==NULL)
1792                 return;
1793         
1794         switch(signal) {
1795         case IMA_SIGNAL_FREE:
1796                 image_free_buffers(ima);
1797                 if (iuser)
1798                         iuser->ok= 1;
1799                 break;
1800         case IMA_SIGNAL_SRC_CHANGE:
1801                 if (ima->type == IMA_TYPE_UV_TEST)
1802                         if (ima->source != IMA_SRC_GENERATED)
1803                                 ima->type= IMA_TYPE_IMAGE;
1804
1805                 if (ima->source==IMA_SRC_GENERATED) {
1806                         if (ima->gen_x==0 || ima->gen_y==0) {
1807                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1808                                 if (ibuf) {
1809                                         ima->gen_x= ibuf->x;
1810                                         ima->gen_y= ibuf->y;
1811                                 }
1812                         }
1813                 }
1814
1815                 /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
1816                 if (ima->type!=IMA_TYPE_MULTILAYER)
1817                         image_free_buffers(ima);
1818
1819                 ima->ok= 1;
1820                 if (iuser)
1821                         iuser->ok= 1;
1822                 break;
1823                         
1824         case IMA_SIGNAL_RELOAD:
1825                 /* try to repack file */
1826                 if (ima->packedfile) {
1827                         PackedFile *pf;
1828                         pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
1829                         if (pf) {
1830                                 freePackedFile(ima->packedfile);
1831                                 ima->packedfile = pf;
1832                                 image_free_buffers(ima);
1833                         }
1834                         else {
1835                                 printf("ERROR: Image not available. Keeping packed image\n");
1836                         }
1837                 }
1838                 else
1839                         image_free_buffers(ima);
1840                 
1841                 if (iuser)
1842                         iuser->ok= 1;
1843                 
1844                 break;
1845         case IMA_SIGNAL_USER_NEW_IMAGE:
1846                 if (iuser) {
1847                         iuser->ok= 1;
1848                         if (ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1849                                 if (ima->type==IMA_TYPE_MULTILAYER) {
1850                                         iuser->multi_index= 0;
1851                                         iuser->layer= iuser->pass= 0;
1852                                 }
1853                         }
1854                 }
1855                 break;
1856         }
1857         
1858         /* don't use notifiers because they are not 100% sure to succeeded
1859          * this also makes sure all scenes are accounted for. */
1860         {
1861                 Scene *scene;
1862                 for (scene= G.main->scene.first; scene; scene= scene->id.next) {
1863                         if (scene->nodetree) {
1864                                 nodeUpdateID(scene->nodetree, &ima->id);
1865                         }
1866                 }
1867         }
1868 }
1869
1870 /* if layer or pass changes, we need an index for the imbufs list */
1871 /* note it is called for rendered results, but it doesnt use the index! */
1872 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1873 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1874 {
1875         RenderLayer *rl;
1876         RenderPass *rpass= NULL;
1877         
1878         if (rr==NULL) 
1879                 return NULL;
1880         
1881         if (iuser) {
1882                 short index= 0, rl_index= 0, rp_index;
1883                 
1884                 for (rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1885                         rp_index= 0;
1886                         for (rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1887                                 if (iuser->layer==rl_index && iuser->pass==rp_index)
1888                                         break;
1889                         if (rpass)
1890                                 break;
1891                 }
1892                 
1893                 if (rpass)
1894                         iuser->multi_index= index;
1895                 else 
1896                         iuser->multi_index= 0;
1897         }
1898         if (rpass==NULL) {
1899                 rl= rr->layers.first;
1900                 if (rl)
1901                         rpass= rl->passes.first;
1902         }
1903         
1904         return rpass;
1905 }
1906
1907 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1908 {
1909         if (ima->rr) {
1910                 return ima->rr;
1911         }
1912         else if (ima->type==IMA_TYPE_R_RESULT) {
1913                 if (ima->render_slot == ima->last_render_slot)
1914                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1915                 else
1916                         return ima->renders[ima->render_slot];
1917         }
1918         else
1919                 return NULL;
1920 }
1921
1922 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1923 {
1924         if (ima->rr);
1925         else if (ima->type==IMA_TYPE_R_RESULT) {
1926                 if (ima->render_slot == ima->last_render_slot)
1927                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1928         }
1929 }
1930
1931 void BKE_image_backup_render(Scene *scene, Image *ima)
1932 {
1933         /* called right before rendering, ima->renders contains render
1934          * result pointers for everything but the current render */
1935         Render *re= RE_GetRender(scene->id.name);
1936         int slot= ima->render_slot, last= ima->last_render_slot;
1937
1938         if (slot != last) {
1939                 if (ima->renders[slot]) {
1940                         RE_FreeRenderResult(ima->renders[slot]);
1941                         ima->renders[slot]= NULL;
1942                 }
1943
1944                 ima->renders[last]= NULL;
1945                 RE_SwapResult(re, &ima->renders[last]);
1946         }
1947
1948         ima->last_render_slot= slot;
1949 }
1950
1951 /* after imbuf load, openexr type can return with a exrhandle open */
1952 /* in that case we have to build a render-result */
1953 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1954 {
1955         
1956         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1957
1958 #ifdef WITH_OPENEXR
1959         IMB_exr_close(ibuf->userdata);
1960 #endif
1961
1962         ibuf->userdata= NULL;
1963         if (ima->rr)
1964                 ima->rr->framenr= framenr;
1965 }
1966
1967 /* common stuff to do with images after loading */
1968 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1969 {
1970         /* preview is NULL when it has never been used as an icon before */
1971         if (G.background==0 && ima->preview==NULL)
1972                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1973
1974         /* fields */
1975         if (ima->flag & IMA_FIELDS) {
1976                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1977                 else de_interlace_ng(ibuf);
1978         }
1979         /* timer */
1980         ima->lastused = clock() / CLOCKS_PER_SEC;
1981         
1982         ima->ok= IMA_OK_LOADED;
1983         
1984 }
1985
1986 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1987 {
1988         struct ImBuf *ibuf;
1989         unsigned short numlen;
1990         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1991         int flag;
1992         
1993         /* XXX temp stuff? */
1994         if (ima->lastframe != frame)
1995                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1996
1997         ima->lastframe= frame;
1998         BLI_strncpy(name, ima->name, sizeof(name));
1999         BLI_stringdec(name, head, tail, &numlen);
2000         BLI_stringenc(name, head, tail, numlen, frame);
2001
2002         BLI_path_abs(name, ID_BLEND_PATH(G.main, &ima->id));
2003         
2004         flag= IB_rect|IB_multilayer;
2005         if (ima->flag & IMA_DO_PREMUL)
2006                 flag |= IB_premul;
2007
2008         /* read ibuf */
2009         ibuf = IMB_loadiffname(name, flag);
2010
2011 #if 0
2012         if (ibuf) {
2013                 printf(AT" loaded %s\n", name);
2014         }
2015         else {
2016                 printf(AT" missed %s\n", name);
2017         }
2018 #endif
2019
2020         if (ibuf) {
2021 #ifdef WITH_OPENEXR
2022                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2023                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
2024                         image_create_multilayer(ima, ibuf, frame);      
2025                         ima->type= IMA_TYPE_MULTILAYER;
2026                         IMB_freeImBuf(ibuf);
2027                         ibuf= NULL;
2028                 }
2029                 else {
2030                         image_initialize_after_load(ima, ibuf);
2031                         image_assign_ibuf(ima, ibuf, 0, frame);
2032                 }
2033 #else
2034                 image_initialize_after_load(ima, ibuf);
2035                 image_assign_ibuf(ima, ibuf, 0, frame);
2036 #endif
2037         }
2038         else
2039                 ima->ok= 0;
2040         
2041         if (iuser)
2042                 iuser->ok= ima->ok;
2043         
2044         return ibuf;
2045 }
2046
2047 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2048 {
2049         struct ImBuf *ibuf= NULL;
2050         
2051         /* either we load from RenderResult, or we have to load a new one */
2052         
2053         /* check for new RenderResult */
2054         if (ima->rr==NULL || frame!=ima->rr->framenr) {
2055                 /* copy to survive not found multilayer image */
2056                 RenderResult *oldrr= ima->rr;
2057         
2058                 ima->rr= NULL;
2059                 ibuf = image_load_sequence_file(ima, iuser, frame);
2060                 
2061                 if (ibuf) { /* actually an error */
2062                         ima->type= IMA_TYPE_IMAGE;
2063                         printf("error, multi is normal image\n");
2064                 }
2065                 // printf("loaded new result %p\n", ima->rr);
2066                 /* free result if new one found */
2067                 if (ima->rr) {
2068                         // if (oldrr) printf("freed previous result %p\n", oldrr);
2069                         if (oldrr) RE_FreeRenderResult(oldrr);
2070                 }
2071                 else {
2072                         ima->rr= oldrr;
2073                 }
2074
2075         }
2076         if (ima->rr) {
2077                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2078                 
2079                 if (rpass) {
2080                         // printf("load from pass %s\n", rpass->name);
2081                         /* since we free  render results, we copy the rect */
2082                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2083                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
2084                         ibuf->flags |= IB_rectfloat;
2085                         ibuf->mall= IB_rectfloat;
2086                         ibuf->channels= rpass->channels;
2087                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2088                         
2089                         image_initialize_after_load(ima, ibuf);
2090                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
2091                         
2092                 }
2093                 // else printf("pass not found\n");
2094         }
2095         else
2096                 ima->ok= 0;
2097         
2098         if (iuser)
2099                 iuser->ok= ima->ok;
2100         
2101         return ibuf;
2102 }
2103
2104
2105 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2106 {
2107         struct ImBuf *ibuf= NULL;
2108         
2109         ima->lastframe= frame;
2110         
2111         if (ima->anim==NULL) {
2112                 char str[FILE_MAX];
2113                 
2114                 BLI_strncpy(str, ima->name, FILE_MAX);
2115                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2116
2117                 /* FIXME: make several stream accessible in image editor, too*/
2118                 ima->anim = openanim(str, IB_rect, 0);
2119                 
2120                 /* let's initialize this user */
2121                 if (ima->anim && iuser && iuser->frames==0)
2122                         iuser->frames= IMB_anim_get_duration(ima->anim,
2123                                                              IMB_TC_RECORD_RUN);
2124         }
2125         
2126         if (ima->anim) {
2127                 int dur = IMB_anim_get_duration(ima->anim,
2128                                                 IMB_TC_RECORD_RUN);
2129                 int fra= frame-1;
2130                 
2131                 if (fra<0) fra = 0;
2132                 if (fra>(dur-1)) fra= dur-1;
2133                 ibuf = IMB_makeSingleUser(
2134                         IMB_anim_absolute(ima->anim, fra,
2135                                           IMB_TC_RECORD_RUN,
2136                                           IMB_PROXY_NONE));
2137                 
2138                 if (ibuf) {
2139                         image_initialize_after_load(ima, ibuf);
2140                         image_assign_ibuf(ima, ibuf, 0, frame);
2141                 }
2142                 else
2143                         ima->ok= 0;
2144         }
2145         else
2146                 ima->ok= 0;
2147         
2148         if (iuser)
2149                 iuser->ok= ima->ok;
2150         
2151         return ibuf;
2152 }
2153
2154 /* warning, 'iuser' can be NULL */
2155 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2156 {
2157         struct ImBuf *ibuf;
2158         char str[FILE_MAX];
2159         int assign = 0, flag;
2160         
2161         /* always ensure clean ima */
2162         image_free_buffers(ima);
2163         
2164         /* is there a PackedFile with this image ? */
2165         if (ima->packedfile) {
2166                 flag = IB_rect|IB_multilayer;
2167                 if (ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2168                 
2169                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag, "<packed data>");
2170         } 
2171         else {
2172                 flag= IB_rect|IB_multilayer|IB_metadata;
2173                 if (ima->flag & IMA_DO_PREMUL)
2174                         flag |= IB_premul;
2175                         
2176                 /* get the right string */
2177                 BLI_strncpy(str, ima->name, sizeof(str));
2178                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2179                 
2180                 /* read ibuf */
2181                 ibuf = IMB_loadiffname(str, flag);
2182         }
2183         
2184         if (ibuf) {
2185                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2186                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
2187                         image_create_multilayer(ima, ibuf, cfra);       
2188                         ima->type= IMA_TYPE_MULTILAYER;
2189                         IMB_freeImBuf(ibuf);
2190                         ibuf= NULL;
2191                 }
2192                 else {
2193                         image_initialize_after_load(ima, ibuf);
2194                         assign= 1;
2195
2196                         /* check if the image is a font image... */
2197                         detectBitmapFont(ibuf);
2198                         
2199                         /* make packed file for autopack */
2200                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2201                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2202                 }
2203         }
2204         else
2205                 ima->ok= 0;
2206         
2207         if (assign)
2208                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2209
2210         if (iuser)
2211                 iuser->ok= ima->ok;
2212         
2213         return ibuf;
2214 }
2215
2216 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2217 {
2218         ImBuf *ibuf= NULL;
2219         
2220         if (ima->rr==NULL) {
2221                 ibuf = image_load_image_file(ima, iuser, 0);
2222                 if (ibuf) { /* actually an error */
2223                         ima->type= IMA_TYPE_IMAGE;
2224                         return ibuf;
2225                 }
2226         }
2227         if (ima->rr) {
2228                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2229
2230                 if (rpass) {
2231                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2232                         
2233                         image_initialize_after_load(ima, ibuf);
2234                         
2235                         ibuf->rect_float= rpass->rect;
2236                         ibuf->flags |= IB_rectfloat;
2237                         ibuf->channels= rpass->channels;
2238                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2239
2240                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2241                 }
2242         }
2243         
2244         if (ibuf==NULL) 
2245                 ima->ok= 0;
2246         if (iuser)
2247                 iuser->ok= ima->ok;
2248         
2249         return ibuf;
2250 }
2251
2252
2253 /* showing RGBA result itself (from compo/sequence) or
2254  * like exr, using layers etc */
2255 /* always returns a single ibuf, also during render progress */
2256 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2257 {
2258         Render *re;
2259         RenderResult rres;
2260         float *rectf, *rectz;
2261         unsigned int *rect;
2262         float dither;
2263         int channels, layer, pass;
2264         ImBuf *ibuf;
2265         int from_render= (ima->render_slot == ima->last_render_slot);
2266
2267         if (!(iuser && iuser->scene))
2268                 return NULL;
2269
2270         /* if we the caller is not going to release the lock, don't give the image */
2271         if (!lock_r)
2272                 return NULL;
2273
2274         re= RE_GetRender(iuser->scene->id.name);
2275
2276         channels= 4;
2277         layer= (iuser)? iuser->layer: 0;
2278         pass= (iuser)? iuser->pass: 0;
2279
2280         if (from_render) {
2281                 RE_AcquireResultImage(re, &rres);
2282         }
2283         else if (ima->renders[ima->render_slot]) {
2284                 rres= *(ima->renders[ima->render_slot]);
2285                 rres.have_combined= rres.rectf != NULL;
2286         }
2287         else
2288                 memset(&rres, 0, sizeof(RenderResult));
2289         
2290         if (!(rres.rectx > 0 && rres.recty > 0)) {
2291                 if (from_render)
2292                         RE_ReleaseResultImage(re);
2293                 return NULL;
2294         }
2295
2296         /* release is done in BKE_image_release_ibuf using lock_r */
2297         if (from_render) {
2298                 BLI_lock_thread(LOCK_VIEWER);
2299                 *lock_r= re;
2300         }
2301
2302         /* this gives active layer, composite or seqence result */
2303         rect= (unsigned int *)rres.rect32;
2304         rectf= rres.rectf;
2305         rectz= rres.rectz;
2306         dither= iuser->scene->r.dither_intensity;
2307
2308         /* combined layer gets added as first layer */
2309         if (rres.have_combined && layer==0);
2310         else if (rres.layers.first) {
2311                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
2312                 if (rl) {
2313                         RenderPass *rpass;
2314
2315                         /* there's no combined pass, is in renderlayer itself */
2316                         if (pass==0) {
2317                                 rectf= rl->rectf;
2318                         }
2319                         else {
2320                                 rpass= BLI_findlink(&rl->passes, pass-1);
2321                                 if (rpass) {
2322                                         channels= rpass->channels;
2323                                         rectf= rpass->rect;
2324                                         dither= 0.0f; /* don't dither passes */
2325                                 }
2326                         }
2327
2328                         for (rpass= rl->passes.first; rpass; rpass= rpass->next)
2329                                 if (rpass->passtype == SCE_PASS_Z)
2330                                         rectz= rpass->rect;
2331                 }
2332         }
2333
2334         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2335
2336         /* make ibuf if needed, and initialize it */
2337         if (ibuf==NULL) {
2338                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2339                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2340         }
2341
2342         ibuf->x= rres.rectx;
2343         ibuf->y= rres.recty;
2344         
2345         /* free rect buffer if float buffer changes, so it can be recreated with
2346          * the updated result, and also in case we got byte buffer from sequencer,
2347          * so we don't keep reference to freed buffer */
2348         if (ibuf->rect_float!=rectf || rect || !rectf)
2349                 imb_freerectImBuf(ibuf);
2350
2351         if (rect)
2352                 ibuf->rect= rect;
2353         
2354         if (rectf) {
2355                 ibuf->rect_float= rectf;
2356                 ibuf->flags |= IB_rectfloat;
2357                 ibuf->channels= channels;
2358         }
2359         else {
2360                 ibuf->rect_float= NULL;
2361                 ibuf->flags &= ~IB_rectfloat;
2362         }
2363
2364         if (rectz) {
2365                 ibuf->zbuf_float= rectz;
2366                 ibuf->flags |= IB_zbuffloat;
2367         }
2368         else {
2369                 ibuf->zbuf_float= NULL;
2370                 ibuf->flags &= ~IB_zbuffloat;
2371         }
2372
2373         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2374         ibuf->profile= (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2375         ibuf->dither= dither;
2376
2377         if (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2378                 ibuf->flags |= IB_cm_predivide;
2379                 ima->flag |= IMA_CM_PREDIVIDE;
2380         }
2381         else {
2382                 ibuf->flags &= ~IB_cm_predivide;
2383                 ima->flag &= ~IMA_CM_PREDIVIDE;
2384         }
2385
2386         ima->ok= IMA_OK_LOADED;
2387
2388         return ibuf;
2389 }
2390
2391 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2392 {
2393         ImBuf *ibuf = NULL;
2394         int frame = 0, index = 0;
2395
2396         /* see if we already have an appropriate ibuf, with image source and type */
2397         if (ima->source==IMA_SRC_MOVIE) {
2398                 frame= iuser?iuser->framenr:ima->lastframe;
2399                 ibuf= image_get_ibuf(ima, 0, frame);
2400                 /* XXX temp stuff? */
2401                 if (ima->lastframe != frame)
2402                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2403                 ima->lastframe = frame;
2404         }
2405         else if (ima->source==IMA_SRC_SEQUENCE) {
2406                 if (ima->type==IMA_TYPE_IMAGE) {
2407                         frame= iuser?iuser->framenr:ima->lastframe;
2408                         ibuf= image_get_ibuf(ima, 0, frame);
2409                         
2410                         /* XXX temp stuff? */
2411                         if (ima->lastframe != frame) {
2412                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2413                         }
2414                         ima->lastframe = frame;
2415                 }       
2416                 else if (ima->type==IMA_TYPE_MULTILAYER) {
2417                         frame= iuser?iuser->framenr:ima->lastframe;
2418                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2419                         ibuf= image_get_ibuf(ima, index, frame);
2420                 }
2421         }
2422         else if (ima->source==IMA_SRC_FILE) {
2423                 if (ima->type==IMA_TYPE_IMAGE)
2424                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2425                 else if (ima->type==IMA_TYPE_MULTILAYER)
2426                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2427         }
2428         else if (ima->source == IMA_SRC_GENERATED) {
2429                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2430         }
2431         else if (ima->source == IMA_SRC_VIEWER) {
2432                 /* always verify entirely, not that this shouldn't happen
2433                  * as part of texture sampling in rendering anyway, so not
2434                  * a big bottleneck */
2435         }
2436
2437         *frame_r = frame;
2438         *index_r = index;
2439
2440         return ibuf;
2441 }
2442
2443 /* Checks optional ImageUser and verifies/creates ImBuf. */
2444 /* use this one if you want to get a render result in progress,
2445  * if not, use BKE_image_get_ibuf which doesn't require a release */
2446 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2447 {
2448         ImBuf *ibuf= NULL;
2449         float color[] = {0, 0, 0, 1};
2450         int frame= 0, index= 0;
2451
2452         /* This function is intended to be thread-safe. It postpones the mutex lock
2453          * until it needs to load the image, if the image is already there it
2454          * should just get the pointer and return. The reason is that a lot of mutex
2455          * locks appears to be very slow on certain multicore macs, causing a render
2456          * with image textures to actually slow down as more threads are used.
2457          *
2458          * Note that all the image loading functions should also make sure they do
2459          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2460          * That means, the last two steps must be, 1) add the ibuf to the list and
2461          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2462         
2463         if (lock_r)
2464                 *lock_r= NULL;
2465
2466         /* quick reject tests */
2467         if (ima==NULL) 
2468                 return NULL;
2469         if (iuser) {
2470                 if (iuser->ok==0)
2471                         return NULL;
2472         }
2473         else if (ima->ok==0)
2474                 return NULL;
2475         
2476         /* try to get the ibuf without locking */
2477         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2478
2479         if (ibuf == NULL) {
2480                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2481                  * load the image */
2482                 BLI_lock_thread(LOCK_IMAGE);
2483
2484                 /* need to check ok flag and loading ibuf again, because the situation
2485                  * might have changed in the meantime */
2486                 if (iuser) {
2487                         if (iuser->ok==0) {
2488                                 BLI_unlock_thread(LOCK_IMAGE);
2489                                 return NULL;
2490                         }
2491                 }
2492                 else if (ima->ok==0) {
2493                         BLI_unlock_thread(LOCK_IMAGE);
2494                         return NULL;
2495                 }
2496
2497                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2498
2499                 if (ibuf == NULL) {
2500                         /* we are sure we have to load the ibuf, using source and type */
2501                         if (ima->source==IMA_SRC_MOVIE) {
2502                                 /* source is from single file, use flipbook to store ibuf */
2503                                 ibuf= image_load_movie_file(ima, iuser, frame);
2504                         }
2505                         else if (ima->source==IMA_SRC_SEQUENCE) {
2506                                 if (ima->type==IMA_TYPE_IMAGE) {
2507                                         /* regular files, ibufs in flipbook, allows saving */
2508                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2509                                 }
2510                                 /* no else; on load the ima type can change */
2511                                 if (ima->type==IMA_TYPE_MULTILAYER) {
2512                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2513                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2514                                 }
2515                         }
2516                         else if (ima->source==IMA_SRC_FILE) {
2517                                 
2518                                 if (ima->type==IMA_TYPE_IMAGE)
2519                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2520                                 /* no else; on load the ima type can change */
2521                                 if (ima->type==IMA_TYPE_MULTILAYER)
2522                                         /* keeps render result, stores ibufs in listbase, allows saving */
2523                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2524                                         
2525                         }
2526                         else if (ima->source == IMA_SRC_GENERATED) {
2527                                 /* generated is: ibuf is allocated dynamically */
2528                                 /* UV testgrid or black or solid etc */
2529                                 if (ima->gen_x==0) ima->gen_x= 1024;
2530                                 if (ima->gen_y==0) ima->gen_y= 1024;
2531                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2532                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2533                                 ima->ok= IMA_OK_LOADED;
2534                         }
2535                         else if (ima->source == IMA_SRC_VIEWER) {
2536                                 if (ima->type==IMA_TYPE_R_RESULT) {
2537                                         /* always verify entirely, and potentially
2538                                          * returns pointer to release later */
2539                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2540                                 }
2541                                 else if (ima->type==IMA_TYPE_COMPOSITE) {
2542                                         /* requires lock/unlock, otherwise don't return image */
2543                                         if (lock_r) {
2544                                                 /* unlock in BKE_image_release_ibuf */
2545                                                 BLI_lock_thread(LOCK_VIEWER);
2546                                                 *lock_r= ima;
2547
2548                                                 /* XXX anim play for viewer nodes not yet supported */
2549                                                 frame= 0; // XXX iuser?iuser->framenr:0;
2550                                                 ibuf= image_get_ibuf(ima, 0, frame);
2551
2552                                                 if (!ibuf) {
2553                                                         /* Composite Viewer, all handled in compositor */
2554                                                         /* fake ibuf, will be filled in compositor */
2555                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect);
2556                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2557                                                 }
2558                                         }
2559                                 }
2560                         }
2561                 }
2562
2563                 BLI_unlock_thread(LOCK_IMAGE);
2564         }
2565
2566         tag_image_time(ima);
2567
2568         return ibuf;
2569 }
2570
2571 void BKE_image_release_ibuf(Image *ima, void *lock)
2572 {
2573         /* for getting image during threaded render / compositing, need to release */
2574         if (lock == ima) {
2575                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2576         }
2577         else if (lock) {
2578                 RE_ReleaseResultImage(lock); /* render result */
2579                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2580         }
2581 }
2582
2583 /* warning, this can allocate generated images */
2584 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2585 {
2586         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2587         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2588 }
2589
2590 int BKE_image_user_get_frame(const ImageUser *iuser, int cfra, int fieldnr)
2591 {
2592         const int len= (iuser->fie_ima*iuser->frames)/2;
2593
2594         if (len==0) {
2595                 return 0;
2596         }
2597         else {
2598                 int framenr;
2599                 cfra= cfra - iuser->sfra+1;
2600
2601                 /* cyclic */
2602                 if (iuser->cycl) {
2603                         cfra= ( (cfra) % len );
2604                         if (cfra < 0) cfra+= len;
2605                         if (cfra==0) cfra= len;
2606                 }
2607
2608                 if (cfra<0) cfra= 0;
2609                 else if (cfra>len) cfra= len;
2610
2611                 /* convert current frame to current field */
2612                 cfra= 2*(cfra);
2613                 if (fieldnr) cfra++;
2614
2615                 /* transform to images space */
2616                 framenr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2617                 if (framenr>iuser->frames) framenr= iuser->frames;
2618                 framenr+= iuser->offset;
2619
2620                 if (iuser->cycl) {
2621                         framenr= ( (framenr) % len );
2622                         while (framenr < 0) framenr+= len;
2623                         if (framenr==0) framenr= len;
2624                 }
2625
2626                 return framenr;
2627         }
2628 }
2629
2630 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2631 {
2632         const int framenr= BKE_image_user_get_frame(iuser, cfra, fieldnr);
2633
2634         /* allows image users to handle redraws */
2635         if (iuser->flag & IMA_ANIM_ALWAYS)
2636                 if (framenr!=iuser->framenr)
2637                         iuser->flag |= IMA_ANIM_REFRESHED;
2638
2639         iuser->framenr= framenr;
2640         if (iuser->ok==0) iuser->ok= 1;
2641 }
2642
2643 int BKE_image_has_alpha(struct Image *image)
2644 {
2645         ImBuf *ibuf;
2646         void *lock;
2647         int planes;
2648         
2649         ibuf= BKE_image_acquire_ibuf(image, NULL, &lock);
2650         planes = (ibuf?ibuf->planes:0);
2651         BKE_image_release_ibuf(image, lock);
2652
2653         if (planes == 32)
2654                 return 1;
2655         else
2656                 return 0;
2657 }
2658