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