1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19 
20 /** \file
21  * \ingroup bke
22  */
23 
24 #include <fcntl.h>
25 #include <math.h>
26 #include <stdio.h>
27 #include <string.h>
28 #ifndef WIN32
29 #  include <unistd.h>
30 #else
31 #  include <io.h>
32 #endif
33 
34 #include <time.h>
35 
36 #include "CLG_log.h"
37 
38 #include "MEM_guardedalloc.h"
39 
40 #include "IMB_colormanagement.h"
41 #include "IMB_imbuf.h"
42 #include "IMB_imbuf_types.h"
43 #include "IMB_metadata.h"
44 #include "IMB_moviecache.h"
45 
46 #ifdef WITH_OPENEXR
47 #  include "intern/openexr/openexr_multi.h"
48 #endif
49 
50 /* Allow using deprecated functionality for .blend file I/O. */
51 #define DNA_DEPRECATED_ALLOW
52 
53 #include "DNA_brush_types.h"
54 #include "DNA_camera_types.h"
55 #include "DNA_defaults.h"
56 #include "DNA_light_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_meshdata_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_packedFile_types.h"
61 #include "DNA_scene_types.h"
62 #include "DNA_sequence_types.h"
63 #include "DNA_simulation_types.h"
64 #include "DNA_world_types.h"
65 
66 #include "BLI_blenlib.h"
67 #include "BLI_math_vector.h"
68 #include "BLI_mempool.h"
69 #include "BLI_system.h"
70 #include "BLI_threads.h"
71 #include "BLI_timecode.h" /* For stamp time-code format. */
72 #include "BLI_utildefines.h"
73 
74 #include "BLT_translation.h"
75 
76 #include "BKE_colortools.h"
77 #include "BKE_global.h"
78 #include "BKE_icons.h"
79 #include "BKE_idtype.h"
80 #include "BKE_image.h"
81 #include "BKE_lib_id.h"
82 #include "BKE_main.h"
83 #include "BKE_node.h"
84 #include "BKE_packedFile.h"
85 #include "BKE_report.h"
86 #include "BKE_scene.h"
87 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
88 #include "BKE_workspace.h"
89 
90 #include "BLF_api.h"
91 
92 #include "PIL_time.h"
93 
94 #include "RE_pipeline.h"
95 
96 #include "GPU_texture.h"
97 
98 #include "BLI_sys_types.h" /* for intptr_t support */
99 
100 #include "DEG_depsgraph.h"
101 #include "DEG_depsgraph_query.h"
102 
103 #include "BLO_read_write.h"
104 
105 /* for image user iteration */
106 #include "DNA_node_types.h"
107 #include "DNA_screen_types.h"
108 #include "DNA_space_types.h"
109 #include "DNA_view3d_types.h"
110 
111 static CLG_LogRef LOG = {"bke.image"};
112 static ThreadMutex *image_mutex;
113 
114 static void image_init(Image *ima, short source, short type);
115 static void image_free_packedfiles(Image *ima);
116 static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src);
117 
image_init_data(ID * id)118 static void image_init_data(ID *id)
119 {
120   Image *image = (Image *)id;
121 
122   if (image != NULL) {
123     image_init(image, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
124   }
125 }
126 
image_copy_data(Main * UNUSED (bmain),ID * id_dst,const ID * id_src,const int flag)127 static void image_copy_data(Main *UNUSED(bmain), ID *id_dst, const ID *id_src, const int flag)
128 {
129   Image *image_dst = (Image *)id_dst;
130   const Image *image_src = (const Image *)id_src;
131 
132   BKE_color_managed_colorspace_settings_copy(&image_dst->colorspace_settings,
133                                              &image_src->colorspace_settings);
134 
135   copy_image_packedfiles(&image_dst->packedfiles, &image_src->packedfiles);
136 
137   image_dst->stereo3d_format = MEM_dupallocN(image_src->stereo3d_format);
138   BLI_duplicatelist(&image_dst->views, &image_src->views);
139 
140   /* Cleanup stuff that cannot be copied. */
141   image_dst->cache = NULL;
142   image_dst->rr = NULL;
143 
144   BLI_duplicatelist(&image_dst->renderslots, &image_src->renderslots);
145   LISTBASE_FOREACH (RenderSlot *, slot, &image_dst->renderslots) {
146     slot->render = NULL;
147   }
148 
149   BLI_listbase_clear(&image_dst->anims);
150 
151   BLI_duplicatelist(&image_dst->tiles, &image_src->tiles);
152 
153   for (int eye = 0; eye < 2; eye++) {
154     for (int i = 0; i < TEXTARGET_COUNT; i++) {
155       image_dst->gputexture[i][eye] = NULL;
156     }
157   }
158 
159   if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
160     BKE_previewimg_id_copy(&image_dst->id, &image_src->id);
161   }
162   else {
163     image_dst->preview = NULL;
164   }
165 }
166 
image_free_data(ID * id)167 static void image_free_data(ID *id)
168 {
169   Image *image = (Image *)id;
170 
171   /* Also frees animdata. */
172   BKE_image_free_buffers(image);
173 
174   image_free_packedfiles(image);
175 
176   LISTBASE_FOREACH (RenderSlot *, slot, &image->renderslots) {
177     if (slot->render) {
178       RE_FreeRenderResult(slot->render);
179       slot->render = NULL;
180     }
181   }
182   BLI_freelistN(&image->renderslots);
183 
184   BKE_image_free_views(image);
185   MEM_SAFE_FREE(image->stereo3d_format);
186 
187   BKE_icon_id_delete(&image->id);
188   BKE_previewimg_free(&image->preview);
189 
190   BLI_freelistN(&image->tiles);
191 }
192 
image_foreach_cache(ID * id,IDTypeForeachCacheFunctionCallback function_callback,void * user_data)193 static void image_foreach_cache(ID *id,
194                                 IDTypeForeachCacheFunctionCallback function_callback,
195                                 void *user_data)
196 {
197   Image *image = (Image *)id;
198   IDCacheKey key = {
199       .id_session_uuid = id->session_uuid,
200       .offset_in_ID = offsetof(Image, cache),
201       .cache_v = image->cache,
202   };
203   function_callback(id, &key, (void **)&image->cache, 0, user_data);
204 
205   for (int eye = 0; eye < 2; eye++) {
206     for (int a = 0; a < TEXTARGET_COUNT; a++) {
207       key.offset_in_ID = offsetof(Image, gputexture[a][eye]);
208       key.cache_v = image->gputexture[a][eye];
209       function_callback(id, &key, (void **)&image->gputexture[a][eye], 0, user_data);
210     }
211   }
212 
213   key.offset_in_ID = offsetof(Image, rr);
214   key.cache_v = image->rr;
215   function_callback(id, &key, (void **)&image->rr, 0, user_data);
216 
217   LISTBASE_FOREACH (RenderSlot *, slot, &image->renderslots) {
218     key.offset_in_ID = (size_t)BLI_ghashutil_strhash_p(slot->name);
219     key.cache_v = slot->render;
220     function_callback(id, &key, (void **)&slot->render, 0, user_data);
221   }
222 }
223 
image_blend_write(BlendWriter * writer,ID * id,const void * id_address)224 static void image_blend_write(BlendWriter *writer, ID *id, const void *id_address)
225 {
226   Image *ima = (Image *)id;
227   if (ima->id.us > 0 || BLO_write_is_undo(writer)) {
228     ImagePackedFile *imapf;
229 
230     /* Some trickery to keep forward compatibility of packed images. */
231     BLI_assert(ima->packedfile == NULL);
232     if (ima->packedfiles.first != NULL) {
233       imapf = ima->packedfiles.first;
234       ima->packedfile = imapf->packedfile;
235     }
236 
237     /* write LibData */
238     BLO_write_id_struct(writer, Image, id_address, &ima->id);
239     BKE_id_blend_write(writer, &ima->id);
240 
241     for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
242       BLO_write_struct(writer, ImagePackedFile, imapf);
243       BKE_packedfile_blend_write(writer, imapf->packedfile);
244     }
245 
246     BKE_previewimg_blend_write(writer, ima->preview);
247 
248     LISTBASE_FOREACH (ImageView *, iv, &ima->views) {
249       BLO_write_struct(writer, ImageView, iv);
250     }
251     BLO_write_struct(writer, Stereo3dFormat, ima->stereo3d_format);
252 
253     BLO_write_struct_list(writer, ImageTile, &ima->tiles);
254 
255     ima->packedfile = NULL;
256 
257     BLO_write_struct_list(writer, RenderSlot, &ima->renderslots);
258   }
259 }
260 
image_blend_read_data(BlendDataReader * reader,ID * id)261 static void image_blend_read_data(BlendDataReader *reader, ID *id)
262 {
263   Image *ima = (Image *)id;
264   BLO_read_list(reader, &ima->tiles);
265 
266   BLO_read_list(reader, &(ima->renderslots));
267   if (!BLO_read_data_is_undo(reader)) {
268     /* We reset this last render slot index only when actually reading a file, not for undo. */
269     ima->last_render_slot = ima->render_slot;
270   }
271 
272   BLO_read_list(reader, &(ima->views));
273   BLO_read_list(reader, &(ima->packedfiles));
274 
275   if (ima->packedfiles.first) {
276     LISTBASE_FOREACH (ImagePackedFile *, imapf, &ima->packedfiles) {
277       BKE_packedfile_blend_read(reader, &imapf->packedfile);
278     }
279     ima->packedfile = NULL;
280   }
281   else {
282     BKE_packedfile_blend_read(reader, &ima->packedfile);
283   }
284 
285   BLI_listbase_clear(&ima->anims);
286   BLO_read_data_address(reader, &ima->preview);
287   BKE_previewimg_blend_read(reader, ima->preview);
288   BLO_read_data_address(reader, &ima->stereo3d_format);
289   LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
290     tile->ok = IMA_OK;
291   }
292 }
293 
image_blend_read_lib(BlendLibReader * UNUSED (reader),ID * id)294 static void image_blend_read_lib(BlendLibReader *UNUSED(reader), ID *id)
295 {
296   Image *ima = (Image *)id;
297   /* Images have some kind of 'main' cache, when NULL we should also clear all others. */
298   /* Needs to be done *after* cache pointers are restored (call to
299    * `foreach_cache`/`blo_cache_storage_entry_restore_in_new`), easier for now to do it in
300    * lib_link... */
301   if (ima->cache == NULL) {
302     BKE_image_free_buffers(ima);
303   }
304 }
305 
306 IDTypeInfo IDType_ID_IM = {
307     .id_code = ID_IM,
308     .id_filter = FILTER_ID_IM,
309     .main_listbase_index = INDEX_ID_IM,
310     .struct_size = sizeof(Image),
311     .name = "Image",
312     .name_plural = "images",
313     .translation_context = BLT_I18NCONTEXT_ID_IMAGE,
314     .flags = IDTYPE_FLAGS_NO_ANIMDATA,
315 
316     .init_data = image_init_data,
317     .copy_data = image_copy_data,
318     .free_data = image_free_data,
319     .make_local = NULL,
320     .foreach_id = NULL,
321     .foreach_cache = image_foreach_cache,
322 
323     .blend_write = image_blend_write,
324     .blend_read_data = image_blend_read_data,
325     .blend_read_lib = image_blend_read_lib,
326     .blend_read_expand = NULL,
327 };
328 
329 /* prototypes */
330 static int image_num_files(struct Image *ima);
331 static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock);
332 static void image_update_views_format(Image *ima, ImageUser *iuser);
333 static void image_add_view(Image *ima, const char *viewname, const char *filepath);
334 
335 /* max int, to indicate we don't store sequences in ibuf */
336 #define IMA_NO_INDEX 0x7FEFEFEF
337 
338 /* quick lookup: supports 1 million entries, thousand passes */
339 #define IMA_MAKE_INDEX(entry, index) (((entry) << 10) + (index))
340 #define IMA_INDEX_ENTRY(index) ((index) >> 10)
341 #if 0
342 #  define IMA_INDEX_PASS(index) (index & ~1023)
343 #endif
344 
345 /* ******** IMAGE CACHE ************* */
346 
347 typedef struct ImageCacheKey {
348   int index;
349 } ImageCacheKey;
350 
imagecache_hashhash(const void * key_v)351 static unsigned int imagecache_hashhash(const void *key_v)
352 {
353   const ImageCacheKey *key = key_v;
354   return key->index;
355 }
356 
imagecache_hashcmp(const void * a_v,const void * b_v)357 static bool imagecache_hashcmp(const void *a_v, const void *b_v)
358 {
359   const ImageCacheKey *a = a_v;
360   const ImageCacheKey *b = b_v;
361 
362   return (a->index != b->index);
363 }
364 
imagecache_keydata(void * userkey,int * framenr,int * proxy,int * render_flags)365 static void imagecache_keydata(void *userkey, int *framenr, int *proxy, int *render_flags)
366 {
367   ImageCacheKey *key = userkey;
368 
369   *framenr = IMA_INDEX_ENTRY(key->index);
370   *proxy = IMB_PROXY_NONE;
371   *render_flags = 0;
372 }
373 
imagecache_put(Image * image,int index,ImBuf * ibuf)374 static void imagecache_put(Image *image, int index, ImBuf *ibuf)
375 {
376   ImageCacheKey key;
377 
378   if (image->cache == NULL) {
379     // char cache_name[64];
380     // SNPRINTF(cache_name, "Image Datablock %s", image->id.name);
381 
382     image->cache = IMB_moviecache_create(
383         "Image Datablock Cache", sizeof(ImageCacheKey), imagecache_hashhash, imagecache_hashcmp);
384     IMB_moviecache_set_getdata_callback(image->cache, imagecache_keydata);
385   }
386 
387   key.index = index;
388 
389   IMB_moviecache_put(image->cache, &key, ibuf);
390 }
391 
imagecache_remove(Image * image,int index)392 static void imagecache_remove(Image *image, int index)
393 {
394   if (image->cache == NULL) {
395     return;
396   }
397 
398   ImageCacheKey key;
399   key.index = index;
400   IMB_moviecache_remove(image->cache, &key);
401 }
402 
imagecache_get(Image * image,int index)403 static struct ImBuf *imagecache_get(Image *image, int index)
404 {
405   if (image->cache) {
406     ImageCacheKey key;
407     key.index = index;
408     return IMB_moviecache_get(image->cache, &key);
409   }
410 
411   return NULL;
412 }
413 
BKE_images_init(void)414 void BKE_images_init(void)
415 {
416   image_mutex = BLI_mutex_alloc();
417 }
418 
BKE_images_exit(void)419 void BKE_images_exit(void)
420 {
421   BLI_mutex_free(image_mutex);
422 }
423 
424 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
425 
image_free_cached_frames(Image * image)426 static void image_free_cached_frames(Image *image)
427 {
428   if (image->cache) {
429     IMB_moviecache_free(image->cache);
430     image->cache = NULL;
431   }
432 }
433 
image_free_packedfiles(Image * ima)434 static void image_free_packedfiles(Image *ima)
435 {
436   while (ima->packedfiles.last) {
437     ImagePackedFile *imapf = ima->packedfiles.last;
438     if (imapf->packedfile) {
439       BKE_packedfile_free(imapf->packedfile);
440     }
441     BLI_remlink(&ima->packedfiles, imapf);
442     MEM_freeN(imapf);
443   }
444 }
445 
BKE_image_free_packedfiles(Image * ima)446 void BKE_image_free_packedfiles(Image *ima)
447 {
448   image_free_packedfiles(ima);
449 }
450 
BKE_image_free_views(Image * image)451 void BKE_image_free_views(Image *image)
452 {
453   BLI_freelistN(&image->views);
454 }
455 
image_free_anims(Image * ima)456 static void image_free_anims(Image *ima)
457 {
458   while (ima->anims.last) {
459     ImageAnim *ia = ima->anims.last;
460     if (ia->anim) {
461       IMB_free_anim(ia->anim);
462       ia->anim = NULL;
463     }
464     BLI_remlink(&ima->anims, ia);
465     MEM_freeN(ia);
466   }
467 }
468 
469 /**
470  * Simply free the image data from memory,
471  * on display the image can load again (except for render buffers).
472  */
BKE_image_free_buffers_ex(Image * ima,bool do_lock)473 void BKE_image_free_buffers_ex(Image *ima, bool do_lock)
474 {
475   if (do_lock) {
476     BLI_mutex_lock(image_mutex);
477   }
478   image_free_cached_frames(ima);
479 
480   image_free_anims(ima);
481 
482   if (ima->rr) {
483     RE_FreeRenderResult(ima->rr);
484     ima->rr = NULL;
485   }
486 
487   BKE_image_free_gputextures(ima);
488 
489   LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
490     tile->ok = IMA_OK;
491   }
492 
493   if (do_lock) {
494     BLI_mutex_unlock(image_mutex);
495   }
496 }
497 
BKE_image_free_buffers(Image * ima)498 void BKE_image_free_buffers(Image *ima)
499 {
500   BKE_image_free_buffers_ex(ima, false);
501 }
502 
503 /** Free (or release) any data used by this image (does not free the image itself). */
BKE_image_free(Image * ima)504 void BKE_image_free(Image *ima)
505 {
506   image_free_data(&ima->id);
507 }
508 
509 /* only image block itself */
image_init(Image * ima,short source,short type)510 static void image_init(Image *ima, short source, short type)
511 {
512   BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(ima, id));
513 
514   MEMCPY_STRUCT_AFTER(ima, DNA_struct_default_get(Image), id);
515 
516   ima->source = source;
517   ima->type = type;
518 
519   if (source == IMA_SRC_VIEWER) {
520     ima->flag |= IMA_VIEW_AS_RENDER;
521   }
522 
523   ImageTile *tile = MEM_callocN(sizeof(ImageTile), "Image Tiles");
524   tile->ok = IMA_OK;
525   tile->tile_number = 1001;
526   BLI_addtail(&ima->tiles, tile);
527 
528   if (type == IMA_TYPE_R_RESULT) {
529     for (int i = 0; i < 8; i++) {
530       BKE_image_add_renderslot(ima, NULL);
531     }
532   }
533 
534   BKE_color_managed_colorspace_settings_init(&ima->colorspace_settings);
535   ima->stereo3d_format = MEM_callocN(sizeof(Stereo3dFormat), "Image Stereo Format");
536 }
537 
image_alloc(Main * bmain,const char * name,short source,short type)538 static Image *image_alloc(Main *bmain, const char *name, short source, short type)
539 {
540   Image *ima;
541 
542   ima = BKE_libblock_alloc(bmain, ID_IM, name, 0);
543   if (ima) {
544     image_init(ima, source, type);
545   }
546 
547   return ima;
548 }
549 
550 /* Get the ibuf from an image cache by its index and entry.
551  * Local use here only.
552  *
553  * Returns referenced image buffer if it exists, callee is to
554  * call IMB_freeImBuf to de-reference the image buffer after
555  * it's done handling it.
556  */
image_get_cached_ibuf_for_index_entry(Image * ima,int index,int entry)557 static ImBuf *image_get_cached_ibuf_for_index_entry(Image *ima, int index, int entry)
558 {
559   if (index != IMA_NO_INDEX) {
560     index = IMA_MAKE_INDEX(entry, index);
561   }
562 
563   return imagecache_get(ima, index);
564 }
565 
566 /* no ima->ibuf anymore, but listbase */
image_assign_ibuf(Image * ima,ImBuf * ibuf,int index,int entry)567 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int entry)
568 {
569   if (ibuf) {
570     if (index != IMA_NO_INDEX) {
571       index = IMA_MAKE_INDEX(entry, index);
572     }
573 
574     imagecache_put(ima, index, ibuf);
575   }
576 }
577 
image_remove_ibuf(Image * ima,int index,int entry)578 static void image_remove_ibuf(Image *ima, int index, int entry)
579 {
580   if (index != IMA_NO_INDEX) {
581     index = IMA_MAKE_INDEX(entry, index);
582   }
583   imagecache_remove(ima, index);
584 }
585 
copy_image_packedfiles(ListBase * lb_dst,const ListBase * lb_src)586 static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src)
587 {
588   const ImagePackedFile *imapf_src;
589 
590   BLI_listbase_clear(lb_dst);
591   for (imapf_src = lb_src->first; imapf_src; imapf_src = imapf_src->next) {
592     ImagePackedFile *imapf_dst = MEM_mallocN(sizeof(ImagePackedFile), "Image Packed Files (copy)");
593     STRNCPY(imapf_dst->filepath, imapf_src->filepath);
594 
595     if (imapf_src->packedfile) {
596       imapf_dst->packedfile = BKE_packedfile_duplicate(imapf_src->packedfile);
597     }
598 
599     BLI_addtail(lb_dst, imapf_dst);
600   }
601 }
602 
BKE_image_merge(Main * bmain,Image * dest,Image * source)603 void BKE_image_merge(Main *bmain, Image *dest, Image *source)
604 {
605   /* sanity check */
606   if (dest && source && dest != source) {
607     BLI_mutex_lock(image_mutex);
608     if (source->cache != NULL) {
609       struct MovieCacheIter *iter;
610       iter = IMB_moviecacheIter_new(source->cache);
611       while (!IMB_moviecacheIter_done(iter)) {
612         ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
613         ImageCacheKey *key = IMB_moviecacheIter_getUserKey(iter);
614         imagecache_put(dest, key->index, ibuf);
615         IMB_moviecacheIter_step(iter);
616       }
617       IMB_moviecacheIter_free(iter);
618     }
619     BLI_mutex_unlock(image_mutex);
620 
621     BKE_id_free(bmain, source);
622   }
623 }
624 
625 /* note, we could be clever and scale all imbuf's but since some are mipmaps its not so simple */
BKE_image_scale(Image * image,int width,int height)626 bool BKE_image_scale(Image *image, int width, int height)
627 {
628   ImBuf *ibuf;
629   void *lock;
630 
631   ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
632 
633   if (ibuf) {
634     IMB_scaleImBuf(ibuf, width, height);
635     BKE_image_mark_dirty(image, ibuf);
636   }
637 
638   BKE_image_release_ibuf(image, ibuf, lock);
639 
640   return (ibuf != NULL);
641 }
642 
BKE_image_has_opengl_texture(Image * ima)643 bool BKE_image_has_opengl_texture(Image *ima)
644 {
645   for (int eye = 0; eye < 2; eye++) {
646     for (int i = 0; i < TEXTARGET_COUNT; i++) {
647       if (ima->gputexture[i][eye] != NULL) {
648         return true;
649       }
650     }
651   }
652   return false;
653 }
654 
BKE_image_get_tile(Image * ima,int tile_number)655 ImageTile *BKE_image_get_tile(Image *ima, int tile_number)
656 {
657   if (ima == NULL) {
658     return NULL;
659   }
660 
661   /* Verify valid tile range. */
662   if ((tile_number != 0) && (tile_number < 1001 || tile_number > IMA_UDIM_MAX)) {
663     return NULL;
664   }
665 
666   /* Tile number 0 is a special case and refers to the first tile, typically
667    * coming from non-UDIM-aware code. */
668   if (tile_number == 0 || tile_number == 1001) {
669     return ima->tiles.first;
670   }
671 
672   if (ima->source != IMA_SRC_TILED) {
673     return NULL;
674   }
675 
676   LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
677     if (tile->tile_number == tile_number) {
678       return tile;
679     }
680   }
681 
682   return NULL;
683 }
684 
BKE_image_get_tile_from_iuser(Image * ima,const ImageUser * iuser)685 ImageTile *BKE_image_get_tile_from_iuser(Image *ima, const ImageUser *iuser)
686 {
687   return BKE_image_get_tile(ima, (iuser && iuser->tile) ? iuser->tile : 1001);
688 }
689 
BKE_image_get_tile_from_pos(struct Image * ima,const float uv[2],float r_uv[2],float r_ofs[2])690 int BKE_image_get_tile_from_pos(struct Image *ima,
691                                 const float uv[2],
692                                 float r_uv[2],
693                                 float r_ofs[2])
694 {
695   float local_ofs[2];
696   if (r_ofs == NULL) {
697     r_ofs = local_ofs;
698   }
699 
700   copy_v2_v2(r_uv, uv);
701   zero_v2(r_ofs);
702 
703   if ((ima->source != IMA_SRC_TILED) || uv[0] < 0.0f || uv[1] < 0.0f || uv[0] >= 10.0f) {
704     return 0;
705   }
706 
707   int ix = (int)uv[0];
708   int iy = (int)uv[1];
709   int tile_number = 1001 + 10 * iy + ix;
710 
711   if (BKE_image_get_tile(ima, tile_number) == NULL) {
712     return 0;
713   }
714   r_ofs[0] = ix;
715   r_ofs[1] = iy;
716   sub_v2_v2(r_uv, r_ofs);
717 
718   return tile_number;
719 }
720 
image_init_color_management(Image * ima)721 static void image_init_color_management(Image *ima)
722 {
723   ImBuf *ibuf;
724   char name[FILE_MAX];
725 
726   BKE_image_user_file_path(NULL, ima, name);
727 
728   /* will set input color space to image format default's */
729   ibuf = IMB_loadiffname(name, IB_test | IB_alphamode_detect, ima->colorspace_settings.name);
730 
731   if (ibuf) {
732     if (ibuf->flags & IB_alphamode_premul) {
733       ima->alpha_mode = IMA_ALPHA_PREMUL;
734     }
735     else if (ibuf->flags & IB_alphamode_channel_packed) {
736       ima->alpha_mode = IMA_ALPHA_CHANNEL_PACKED;
737     }
738     else if (ibuf->flags & IB_alphamode_ignore) {
739       ima->alpha_mode = IMA_ALPHA_IGNORE;
740     }
741     else {
742       ima->alpha_mode = IMA_ALPHA_STRAIGHT;
743     }
744 
745     IMB_freeImBuf(ibuf);
746   }
747 }
748 
BKE_image_alpha_mode_from_extension_ex(const char * filepath)749 char BKE_image_alpha_mode_from_extension_ex(const char *filepath)
750 {
751   if (BLI_path_extension_check_n(filepath, ".exr", ".cin", ".dpx", ".hdr", NULL)) {
752     return IMA_ALPHA_PREMUL;
753   }
754 
755   return IMA_ALPHA_STRAIGHT;
756 }
757 
BKE_image_alpha_mode_from_extension(Image * image)758 void BKE_image_alpha_mode_from_extension(Image *image)
759 {
760   image->alpha_mode = BKE_image_alpha_mode_from_extension_ex(image->filepath);
761 }
762 
BKE_image_load(Main * bmain,const char * filepath)763 Image *BKE_image_load(Main *bmain, const char *filepath)
764 {
765   Image *ima;
766   int file;
767   char str[FILE_MAX];
768 
769   STRNCPY(str, filepath);
770   BLI_path_abs(str, BKE_main_blendfile_path(bmain));
771 
772   /* exists? */
773   file = BLI_open(str, O_BINARY | O_RDONLY, 0);
774   if (file == -1) {
775     return NULL;
776   }
777   close(file);
778 
779   ima = image_alloc(bmain, BLI_path_basename(filepath), IMA_SRC_FILE, IMA_TYPE_IMAGE);
780   STRNCPY(ima->filepath, filepath);
781 
782   if (BLI_path_extension_check_array(filepath, imb_ext_movie)) {
783     ima->source = IMA_SRC_MOVIE;
784   }
785 
786   image_init_color_management(ima);
787 
788   return ima;
789 }
790 
791 /* checks if image was already loaded, then returns same image */
792 /* otherwise creates new. */
793 /* does not load ibuf itself */
794 /* pass on optional frame for #name images */
BKE_image_load_exists_ex(Main * bmain,const char * filepath,bool * r_exists)795 Image *BKE_image_load_exists_ex(Main *bmain, const char *filepath, bool *r_exists)
796 {
797   Image *ima;
798   char str[FILE_MAX], strtest[FILE_MAX];
799 
800   STRNCPY(str, filepath);
801   BLI_path_abs(str, bmain->name);
802 
803   /* first search an identical filepath */
804   for (ima = bmain->images.first; ima; ima = ima->id.next) {
805     if (ima->source != IMA_SRC_VIEWER && ima->source != IMA_SRC_GENERATED) {
806       STRNCPY(strtest, ima->filepath);
807       BLI_path_abs(strtest, ID_BLEND_PATH(bmain, &ima->id));
808 
809       if (BLI_path_cmp(strtest, str) == 0) {
810         if ((BKE_image_has_anim(ima) == false) || (ima->id.us == 0)) {
811           id_us_plus(&ima->id); /* officially should not, it doesn't link here! */
812           LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
813             if (tile->ok == 0) {
814               tile->ok = IMA_OK;
815             }
816           }
817           if (r_exists) {
818             *r_exists = true;
819           }
820           return ima;
821         }
822       }
823     }
824   }
825 
826   if (r_exists) {
827     *r_exists = false;
828   }
829   return BKE_image_load(bmain, filepath);
830 }
831 
BKE_image_load_exists(Main * bmain,const char * filepath)832 Image *BKE_image_load_exists(Main *bmain, const char *filepath)
833 {
834   return BKE_image_load_exists_ex(bmain, filepath, NULL);
835 }
836 
add_ibuf_size(unsigned int width,unsigned int height,const char * name,int depth,int floatbuf,short gen_type,const float color[4],ColorManagedColorspaceSettings * colorspace_settings)837 static ImBuf *add_ibuf_size(unsigned int width,
838                             unsigned int height,
839                             const char *name,
840                             int depth,
841                             int floatbuf,
842                             short gen_type,
843                             const float color[4],
844                             ColorManagedColorspaceSettings *colorspace_settings)
845 {
846   ImBuf *ibuf;
847   unsigned char *rect = NULL;
848   float *rect_float = NULL;
849   float fill_color[4];
850 
851   if (floatbuf) {
852     ibuf = IMB_allocImBuf(width, height, depth, IB_rectfloat);
853 
854     if (colorspace_settings->name[0] == '\0') {
855       const char *colorspace = IMB_colormanagement_role_colorspace_name_get(
856           COLOR_ROLE_DEFAULT_FLOAT);
857 
858       STRNCPY(colorspace_settings->name, colorspace);
859     }
860 
861     if (ibuf != NULL) {
862       rect_float = ibuf->rect_float;
863       IMB_colormanagement_check_is_data(ibuf, colorspace_settings->name);
864     }
865 
866     if (IMB_colormanagement_space_name_is_data(colorspace_settings->name)) {
867       copy_v4_v4(fill_color, color);
868     }
869     else {
870       /* The input color here should ideally be linear already, but for now
871        * we just convert and postpone breaking the API for later. */
872       srgb_to_linearrgb_v4(fill_color, color);
873     }
874   }
875   else {
876     ibuf = IMB_allocImBuf(width, height, depth, IB_rect);
877 
878     if (colorspace_settings->name[0] == '\0') {
879       const char *colorspace = IMB_colormanagement_role_colorspace_name_get(
880           COLOR_ROLE_DEFAULT_BYTE);
881 
882       STRNCPY(colorspace_settings->name, colorspace);
883     }
884 
885     if (ibuf != NULL) {
886       rect = (unsigned char *)ibuf->rect;
887       IMB_colormanagement_assign_rect_colorspace(ibuf, colorspace_settings->name);
888     }
889 
890     copy_v4_v4(fill_color, color);
891   }
892 
893   if (!ibuf) {
894     return NULL;
895   }
896 
897   STRNCPY(ibuf->name, name);
898 
899   switch (gen_type) {
900     case IMA_GENTYPE_GRID:
901       BKE_image_buf_fill_checker(rect, rect_float, width, height);
902       break;
903     case IMA_GENTYPE_GRID_COLOR:
904       BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
905       break;
906     default:
907       BKE_image_buf_fill_color(rect, rect_float, width, height, fill_color);
908       break;
909   }
910 
911   return ibuf;
912 }
913 
914 /* adds new image block, creates ImBuf and initializes color */
BKE_image_add_generated(Main * bmain,unsigned int width,unsigned int height,const char * name,int depth,int floatbuf,short gen_type,const float color[4],const bool stereo3d,const bool is_data,const bool tiled)915 Image *BKE_image_add_generated(Main *bmain,
916                                unsigned int width,
917                                unsigned int height,
918                                const char *name,
919                                int depth,
920                                int floatbuf,
921                                short gen_type,
922                                const float color[4],
923                                const bool stereo3d,
924                                const bool is_data,
925                                const bool tiled)
926 {
927   /* on save, type is changed to FILE in editsima.c */
928   Image *ima;
929   if (tiled) {
930     ima = image_alloc(bmain, name, IMA_SRC_TILED, IMA_TYPE_IMAGE);
931   }
932   else {
933     ima = image_alloc(bmain, name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
934   }
935   if (ima == NULL) {
936     return NULL;
937   }
938 
939   int view_id;
940   const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
941 
942   /* STRNCPY(ima->filepath, name); */ /* don't do this, this writes in ain invalid filepath! */
943   ima->gen_x = width;
944   ima->gen_y = height;
945   ima->gen_type = gen_type;
946   ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
947   ima->gen_depth = depth;
948   copy_v4_v4(ima->gen_color, color);
949 
950   if (is_data) {
951     STRNCPY(ima->colorspace_settings.name,
952             IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DATA));
953   }
954 
955   for (view_id = 0; view_id < 2; view_id++) {
956     ImBuf *ibuf;
957     ibuf = add_ibuf_size(
958         width, height, ima->filepath, depth, floatbuf, gen_type, color, &ima->colorspace_settings);
959     int index = tiled ? 0 : IMA_NO_INDEX;
960     int entry = tiled ? 1001 : 0;
961     image_assign_ibuf(ima, ibuf, stereo3d ? view_id : index, entry);
962 
963     /* image_assign_ibuf puts buffer to the cache, which increments user counter. */
964     IMB_freeImBuf(ibuf);
965     if (!stereo3d) {
966       break;
967     }
968 
969     image_add_view(ima, names[view_id], "");
970   }
971 
972   ImageTile *tile = BKE_image_get_tile(ima, 0);
973   tile->ok = IMA_OK_LOADED;
974 
975   return ima;
976 }
977 
978 /* Create an image image from ibuf. The refcount of ibuf is increased,
979  * caller should take care to drop its reference by calling
980  * IMB_freeImBuf if needed. */
BKE_image_add_from_imbuf(Main * bmain,ImBuf * ibuf,const char * name)981 Image *BKE_image_add_from_imbuf(Main *bmain, ImBuf *ibuf, const char *name)
982 {
983   /* on save, type is changed to FILE in editsima.c */
984   Image *ima;
985 
986   if (name == NULL) {
987     name = BLI_path_basename(ibuf->name);
988   }
989 
990   ima = image_alloc(bmain, name, IMA_SRC_FILE, IMA_TYPE_IMAGE);
991 
992   if (ima) {
993     STRNCPY(ima->filepath, ibuf->name);
994     image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
995     ImageTile *tile = BKE_image_get_tile(ima, 0);
996     tile->ok = IMA_OK_LOADED;
997   }
998 
999   return ima;
1000 }
1001 
1002 /* Pack image buffer to memory as PNG or EXR. */
image_memorypack_imbuf(Image * ima,ImBuf * ibuf,const char * filepath)1003 static bool image_memorypack_imbuf(Image *ima, ImBuf *ibuf, const char *filepath)
1004 {
1005   ibuf->ftype = (ibuf->rect_float) ? IMB_FTYPE_OPENEXR : IMB_FTYPE_PNG;
1006 
1007   IMB_saveiff(ibuf, filepath, IB_rect | IB_mem);
1008 
1009   if (ibuf->encodedbuffer == NULL) {
1010     CLOG_STR_ERROR(&LOG, "memory save for pack error");
1011     IMB_freeImBuf(ibuf);
1012     image_free_packedfiles(ima);
1013     return false;
1014   }
1015 
1016   ImagePackedFile *imapf;
1017   PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
1018 
1019   pf->data = ibuf->encodedbuffer;
1020   pf->size = ibuf->encodedsize;
1021 
1022   imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile");
1023   STRNCPY(imapf->filepath, filepath);
1024   imapf->packedfile = pf;
1025   BLI_addtail(&ima->packedfiles, imapf);
1026 
1027   ibuf->encodedbuffer = NULL;
1028   ibuf->encodedsize = 0;
1029   ibuf->userflags &= ~IB_BITMAPDIRTY;
1030 
1031   return true;
1032 }
1033 
1034 /* Pack image to memory. */
BKE_image_memorypack(Image * ima)1035 bool BKE_image_memorypack(Image *ima)
1036 {
1037   bool ok = true;
1038 
1039   image_free_packedfiles(ima);
1040 
1041   if (BKE_image_is_multiview(ima)) {
1042     /* Store each view as a separate packed files with R_IMF_VIEWS_INDIVIDUAL. */
1043     ImageView *iv;
1044     int i;
1045 
1046     for (i = 0, iv = ima->views.first; iv; iv = iv->next, i++) {
1047       ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, i, 0);
1048 
1049       if (!ibuf) {
1050         ok = false;
1051         break;
1052       }
1053 
1054       /* if the image was a R_IMF_VIEWS_STEREO_3D we force _L, _R suffices */
1055       if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
1056         const char *suffix[2] = {STEREO_LEFT_SUFFIX, STEREO_RIGHT_SUFFIX};
1057         BLI_path_suffix(iv->filepath, FILE_MAX, suffix[i], "");
1058       }
1059 
1060       ok = ok && image_memorypack_imbuf(ima, ibuf, iv->filepath);
1061       IMB_freeImBuf(ibuf);
1062     }
1063 
1064     ima->views_format = R_IMF_VIEWS_INDIVIDUAL;
1065   }
1066   else {
1067     ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, IMA_NO_INDEX, 0);
1068 
1069     if (ibuf) {
1070       ok = ok && image_memorypack_imbuf(ima, ibuf, ibuf->name);
1071       IMB_freeImBuf(ibuf);
1072     }
1073     else {
1074       ok = false;
1075     }
1076   }
1077 
1078   if (ok && ima->source == IMA_SRC_GENERATED) {
1079     ima->source = IMA_SRC_FILE;
1080     ima->type = IMA_TYPE_IMAGE;
1081   }
1082 
1083   return ok;
1084 }
1085 
BKE_image_packfiles(ReportList * reports,Image * ima,const char * basepath)1086 void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath)
1087 {
1088   const int totfiles = image_num_files(ima);
1089 
1090   if (totfiles == 1) {
1091     ImagePackedFile *imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image packed file");
1092     BLI_addtail(&ima->packedfiles, imapf);
1093     imapf->packedfile = BKE_packedfile_new(reports, ima->filepath, basepath);
1094     if (imapf->packedfile) {
1095       STRNCPY(imapf->filepath, ima->filepath);
1096     }
1097     else {
1098       BLI_freelinkN(&ima->packedfiles, imapf);
1099     }
1100   }
1101   else {
1102     ImageView *iv;
1103     for (iv = ima->views.first; iv; iv = iv->next) {
1104       ImagePackedFile *imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image packed file");
1105       BLI_addtail(&ima->packedfiles, imapf);
1106 
1107       imapf->packedfile = BKE_packedfile_new(reports, iv->filepath, basepath);
1108       if (imapf->packedfile) {
1109         STRNCPY(imapf->filepath, iv->filepath);
1110       }
1111       else {
1112         BLI_freelinkN(&ima->packedfiles, imapf);
1113       }
1114     }
1115   }
1116 }
1117 
BKE_image_packfiles_from_mem(ReportList * reports,Image * ima,char * data,const size_t data_len)1118 void BKE_image_packfiles_from_mem(ReportList *reports,
1119                                   Image *ima,
1120                                   char *data,
1121                                   const size_t data_len)
1122 {
1123   const int totfiles = image_num_files(ima);
1124 
1125   if (totfiles != 1) {
1126     BKE_report(reports, RPT_ERROR, "Cannot pack multiview images from raw data currently...");
1127   }
1128   else {
1129     ImagePackedFile *imapf = MEM_mallocN(sizeof(ImagePackedFile), __func__);
1130     BLI_addtail(&ima->packedfiles, imapf);
1131     imapf->packedfile = BKE_packedfile_new_from_memory(data, data_len);
1132     STRNCPY(imapf->filepath, ima->filepath);
1133   }
1134 }
1135 
BKE_image_tag_time(Image * ima)1136 void BKE_image_tag_time(Image *ima)
1137 {
1138   ima->lastused = PIL_check_seconds_timer_i();
1139 }
1140 
image_mem_size(Image * image)1141 static uintptr_t image_mem_size(Image *image)
1142 {
1143   uintptr_t size = 0;
1144 
1145   /* viewers have memory depending on other rules, has no valid rect pointer */
1146   if (image->source == IMA_SRC_VIEWER) {
1147     return 0;
1148   }
1149 
1150   BLI_mutex_lock(image_mutex);
1151   if (image->cache != NULL) {
1152     struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);
1153 
1154     while (!IMB_moviecacheIter_done(iter)) {
1155       ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
1156       ImBuf *ibufm;
1157       int level;
1158 
1159       if (ibuf->rect) {
1160         size += MEM_allocN_len(ibuf->rect);
1161       }
1162       if (ibuf->rect_float) {
1163         size += MEM_allocN_len(ibuf->rect_float);
1164       }
1165 
1166       for (level = 0; level < IMB_MIPMAP_LEVELS; level++) {
1167         ibufm = ibuf->mipmap[level];
1168         if (ibufm) {
1169           if (ibufm->rect) {
1170             size += MEM_allocN_len(ibufm->rect);
1171           }
1172           if (ibufm->rect_float) {
1173             size += MEM_allocN_len(ibufm->rect_float);
1174           }
1175         }
1176       }
1177 
1178       IMB_moviecacheIter_step(iter);
1179     }
1180     IMB_moviecacheIter_free(iter);
1181   }
1182   BLI_mutex_unlock(image_mutex);
1183 
1184   return size;
1185 }
1186 
BKE_image_print_memlist(Main * bmain)1187 void BKE_image_print_memlist(Main *bmain)
1188 {
1189   Image *ima;
1190   uintptr_t size, totsize = 0;
1191 
1192   for (ima = bmain->images.first; ima; ima = ima->id.next) {
1193     totsize += image_mem_size(ima);
1194   }
1195 
1196   printf("\ntotal image memory len: %.3f MB\n", (double)totsize / (double)(1024 * 1024));
1197 
1198   for (ima = bmain->images.first; ima; ima = ima->id.next) {
1199     size = image_mem_size(ima);
1200 
1201     if (size) {
1202       printf("%s len: %.3f MB\n", ima->id.name + 2, (double)size / (double)(1024 * 1024));
1203     }
1204   }
1205 }
1206 
imagecache_check_dirty(ImBuf * ibuf,void * UNUSED (userkey),void * UNUSED (userdata))1207 static bool imagecache_check_dirty(ImBuf *ibuf, void *UNUSED(userkey), void *UNUSED(userdata))
1208 {
1209   return (ibuf->userflags & IB_BITMAPDIRTY) == 0;
1210 }
1211 
BKE_image_free_all_textures(Main * bmain)1212 void BKE_image_free_all_textures(Main *bmain)
1213 {
1214 #undef CHECK_FREED_SIZE
1215 
1216   Tex *tex;
1217   Image *ima;
1218 #ifdef CHECK_FREED_SIZE
1219   uintptr_t tot_freed_size = 0;
1220 #endif
1221 
1222   for (ima = bmain->images.first; ima; ima = ima->id.next) {
1223     ima->id.tag &= ~LIB_TAG_DOIT;
1224   }
1225 
1226   for (tex = bmain->textures.first; tex; tex = tex->id.next) {
1227     if (tex->ima) {
1228       tex->ima->id.tag |= LIB_TAG_DOIT;
1229     }
1230   }
1231 
1232   for (ima = bmain->images.first; ima; ima = ima->id.next) {
1233     if (ima->cache && (ima->id.tag & LIB_TAG_DOIT)) {
1234 #ifdef CHECK_FREED_SIZE
1235       uintptr_t old_size = image_mem_size(ima);
1236 #endif
1237 
1238       IMB_moviecache_cleanup(ima->cache, imagecache_check_dirty, NULL);
1239 
1240 #ifdef CHECK_FREED_SIZE
1241       tot_freed_size += old_size - image_mem_size(ima);
1242 #endif
1243     }
1244   }
1245 #ifdef CHECK_FREED_SIZE
1246   printf("%s: freed total %lu MB\n", __func__, tot_freed_size / (1024 * 1024));
1247 #endif
1248 }
1249 
imagecache_check_free_anim(ImBuf * ibuf,void * UNUSED (userkey),void * userdata)1250 static bool imagecache_check_free_anim(ImBuf *ibuf, void *UNUSED(userkey), void *userdata)
1251 {
1252   int except_frame = *(int *)userdata;
1253   return (ibuf->userflags & IB_BITMAPDIRTY) == 0 && (ibuf->index != IMA_NO_INDEX) &&
1254          (except_frame != IMA_INDEX_ENTRY(ibuf->index));
1255 }
1256 
1257 /* except_frame is weak, only works for seqs without offset... */
BKE_image_free_anim_ibufs(Image * ima,int except_frame)1258 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
1259 {
1260   BLI_mutex_lock(image_mutex);
1261   if (ima->cache != NULL) {
1262     IMB_moviecache_cleanup(ima->cache, imagecache_check_free_anim, &except_frame);
1263   }
1264   BLI_mutex_unlock(image_mutex);
1265 }
1266 
BKE_image_all_free_anim_ibufs(Main * bmain,int cfra)1267 void BKE_image_all_free_anim_ibufs(Main *bmain, int cfra)
1268 {
1269   Image *ima;
1270 
1271   for (ima = bmain->images.first; ima; ima = ima->id.next) {
1272     if (BKE_image_is_animated(ima)) {
1273       BKE_image_free_anim_ibufs(ima, cfra);
1274     }
1275   }
1276 }
1277 
1278 /* *********** READ AND WRITE ************** */
1279 
BKE_image_imtype_to_ftype(const char imtype,ImbFormatOptions * r_options)1280 int BKE_image_imtype_to_ftype(const char imtype, ImbFormatOptions *r_options)
1281 {
1282   memset(r_options, 0, sizeof(*r_options));
1283 
1284   if (imtype == R_IMF_IMTYPE_TARGA) {
1285     return IMB_FTYPE_TGA;
1286   }
1287   if (imtype == R_IMF_IMTYPE_RAWTGA) {
1288     r_options->flag = RAWTGA;
1289     return IMB_FTYPE_TGA;
1290   }
1291   if (imtype == R_IMF_IMTYPE_IRIS) {
1292     return IMB_FTYPE_IMAGIC;
1293   }
1294 #ifdef WITH_HDR
1295   if (imtype == R_IMF_IMTYPE_RADHDR) {
1296     return IMB_FTYPE_RADHDR;
1297   }
1298 #endif
1299   if (imtype == R_IMF_IMTYPE_PNG) {
1300     r_options->quality = 15;
1301     return IMB_FTYPE_PNG;
1302   }
1303 #ifdef WITH_DDS
1304   if (imtype == R_IMF_IMTYPE_DDS) {
1305     return IMB_FTYPE_DDS;
1306   }
1307 #endif
1308   if (imtype == R_IMF_IMTYPE_BMP) {
1309     return IMB_FTYPE_BMP;
1310   }
1311 #ifdef WITH_TIFF
1312   if (imtype == R_IMF_IMTYPE_TIFF) {
1313     return IMB_FTYPE_TIF;
1314   }
1315 #endif
1316   if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1317     return IMB_FTYPE_OPENEXR;
1318   }
1319 #ifdef WITH_CINEON
1320   if (imtype == R_IMF_IMTYPE_CINEON) {
1321     return IMB_FTYPE_CINEON;
1322   }
1323   if (imtype == R_IMF_IMTYPE_DPX) {
1324     return IMB_FTYPE_DPX;
1325   }
1326 #endif
1327 #ifdef WITH_OPENJPEG
1328   if (imtype == R_IMF_IMTYPE_JP2) {
1329     r_options->flag |= JP2_JP2;
1330     r_options->quality = 90;
1331     return IMB_FTYPE_JP2;
1332   }
1333 #endif
1334 
1335   r_options->quality = 90;
1336   return IMB_FTYPE_JPG;
1337 }
1338 
BKE_image_ftype_to_imtype(const int ftype,const ImbFormatOptions * options)1339 char BKE_image_ftype_to_imtype(const int ftype, const ImbFormatOptions *options)
1340 {
1341   if (ftype == 0) {
1342     return R_IMF_IMTYPE_TARGA;
1343   }
1344   if (ftype == IMB_FTYPE_IMAGIC) {
1345     return R_IMF_IMTYPE_IRIS;
1346   }
1347 #ifdef WITH_HDR
1348   if (ftype == IMB_FTYPE_RADHDR) {
1349     return R_IMF_IMTYPE_RADHDR;
1350   }
1351 #endif
1352   if (ftype == IMB_FTYPE_PNG) {
1353     return R_IMF_IMTYPE_PNG;
1354   }
1355 #ifdef WITH_DDS
1356   if (ftype == IMB_FTYPE_DDS) {
1357     return R_IMF_IMTYPE_DDS;
1358   }
1359 #endif
1360   if (ftype == IMB_FTYPE_BMP) {
1361     return R_IMF_IMTYPE_BMP;
1362   }
1363 #ifdef WITH_TIFF
1364   if (ftype == IMB_FTYPE_TIF) {
1365     return R_IMF_IMTYPE_TIFF;
1366   }
1367 #endif
1368   if (ftype == IMB_FTYPE_OPENEXR) {
1369     return R_IMF_IMTYPE_OPENEXR;
1370   }
1371 #ifdef WITH_CINEON
1372   if (ftype == IMB_FTYPE_CINEON) {
1373     return R_IMF_IMTYPE_CINEON;
1374   }
1375   if (ftype == IMB_FTYPE_DPX) {
1376     return R_IMF_IMTYPE_DPX;
1377   }
1378 #endif
1379   if (ftype == IMB_FTYPE_TGA) {
1380     if (options && (options->flag & RAWTGA)) {
1381       return R_IMF_IMTYPE_RAWTGA;
1382     }
1383 
1384     return R_IMF_IMTYPE_TARGA;
1385   }
1386 #ifdef WITH_OPENJPEG
1387   if (ftype == IMB_FTYPE_JP2) {
1388     return R_IMF_IMTYPE_JP2;
1389   }
1390 #endif
1391 
1392   return R_IMF_IMTYPE_JPEG90;
1393 }
1394 
BKE_imtype_is_movie(const char imtype)1395 bool BKE_imtype_is_movie(const char imtype)
1396 {
1397   switch (imtype) {
1398     case R_IMF_IMTYPE_AVIRAW:
1399     case R_IMF_IMTYPE_AVIJPEG:
1400     case R_IMF_IMTYPE_FFMPEG:
1401     case R_IMF_IMTYPE_H264:
1402     case R_IMF_IMTYPE_THEORA:
1403     case R_IMF_IMTYPE_XVID:
1404       return true;
1405   }
1406   return false;
1407 }
1408 
BKE_imtype_supports_zbuf(const char imtype)1409 bool BKE_imtype_supports_zbuf(const char imtype)
1410 {
1411   switch (imtype) {
1412     case R_IMF_IMTYPE_IRIZ:
1413     case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
1414       return true;
1415   }
1416   return false;
1417 }
1418 
BKE_imtype_supports_compress(const char imtype)1419 bool BKE_imtype_supports_compress(const char imtype)
1420 {
1421   switch (imtype) {
1422     case R_IMF_IMTYPE_PNG:
1423       return true;
1424   }
1425   return false;
1426 }
1427 
BKE_imtype_supports_quality(const char imtype)1428 bool BKE_imtype_supports_quality(const char imtype)
1429 {
1430   switch (imtype) {
1431     case R_IMF_IMTYPE_JPEG90:
1432     case R_IMF_IMTYPE_JP2:
1433     case R_IMF_IMTYPE_AVIJPEG:
1434       return true;
1435   }
1436   return false;
1437 }
1438 
BKE_imtype_requires_linear_float(const char imtype)1439 bool BKE_imtype_requires_linear_float(const char imtype)
1440 {
1441   switch (imtype) {
1442     case R_IMF_IMTYPE_CINEON:
1443     case R_IMF_IMTYPE_DPX:
1444     case R_IMF_IMTYPE_RADHDR:
1445     case R_IMF_IMTYPE_OPENEXR:
1446     case R_IMF_IMTYPE_MULTILAYER:
1447       return true;
1448   }
1449   return false;
1450 }
1451 
BKE_imtype_valid_channels(const char imtype,bool write_file)1452 char BKE_imtype_valid_channels(const char imtype, bool write_file)
1453 {
1454   char chan_flag = IMA_CHAN_FLAG_RGB; /* assume all support rgb */
1455 
1456   /* alpha */
1457   switch (imtype) {
1458     case R_IMF_IMTYPE_BMP:
1459       if (write_file) {
1460         break;
1461       }
1462       ATTR_FALLTHROUGH;
1463     case R_IMF_IMTYPE_TARGA:
1464     case R_IMF_IMTYPE_RAWTGA:
1465     case R_IMF_IMTYPE_IRIS:
1466     case R_IMF_IMTYPE_PNG:
1467     case R_IMF_IMTYPE_TIFF:
1468     case R_IMF_IMTYPE_OPENEXR:
1469     case R_IMF_IMTYPE_MULTILAYER:
1470     case R_IMF_IMTYPE_DDS:
1471     case R_IMF_IMTYPE_JP2:
1472     case R_IMF_IMTYPE_DPX:
1473       chan_flag |= IMA_CHAN_FLAG_ALPHA;
1474       break;
1475   }
1476 
1477   /* bw */
1478   switch (imtype) {
1479     case R_IMF_IMTYPE_BMP:
1480     case R_IMF_IMTYPE_PNG:
1481     case R_IMF_IMTYPE_JPEG90:
1482     case R_IMF_IMTYPE_TARGA:
1483     case R_IMF_IMTYPE_RAWTGA:
1484     case R_IMF_IMTYPE_TIFF:
1485     case R_IMF_IMTYPE_IRIS:
1486       chan_flag |= IMA_CHAN_FLAG_BW;
1487       break;
1488   }
1489 
1490   return chan_flag;
1491 }
1492 
BKE_imtype_valid_depths(const char imtype)1493 char BKE_imtype_valid_depths(const char imtype)
1494 {
1495   switch (imtype) {
1496     case R_IMF_IMTYPE_RADHDR:
1497       return R_IMF_CHAN_DEPTH_32;
1498     case R_IMF_IMTYPE_TIFF:
1499       return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1500     case R_IMF_IMTYPE_OPENEXR:
1501       return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1502     case R_IMF_IMTYPE_MULTILAYER:
1503       return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1504     /* eeh, cineon does some strange 10bits per channel */
1505     case R_IMF_IMTYPE_DPX:
1506       return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_10 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1507     case R_IMF_IMTYPE_CINEON:
1508       return R_IMF_CHAN_DEPTH_10;
1509     case R_IMF_IMTYPE_JP2:
1510       return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1511     case R_IMF_IMTYPE_PNG:
1512       return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1513     /* most formats are 8bit only */
1514     default:
1515       return R_IMF_CHAN_DEPTH_8;
1516   }
1517 }
1518 
1519 /* string is from command line --render-format arg, keep in sync with
1520  * creator_args.c help info */
BKE_imtype_from_arg(const char * imtype_arg)1521 char BKE_imtype_from_arg(const char *imtype_arg)
1522 {
1523   if (STREQ(imtype_arg, "TGA")) {
1524     return R_IMF_IMTYPE_TARGA;
1525   }
1526   if (STREQ(imtype_arg, "IRIS")) {
1527     return R_IMF_IMTYPE_IRIS;
1528   }
1529 #ifdef WITH_DDS
1530   if (STREQ(imtype_arg, "DDS")) {
1531     return R_IMF_IMTYPE_DDS;
1532   }
1533 #endif
1534   if (STREQ(imtype_arg, "JPEG")) {
1535     return R_IMF_IMTYPE_JPEG90;
1536   }
1537   if (STREQ(imtype_arg, "IRIZ")) {
1538     return R_IMF_IMTYPE_IRIZ;
1539   }
1540   if (STREQ(imtype_arg, "RAWTGA")) {
1541     return R_IMF_IMTYPE_RAWTGA;
1542   }
1543   if (STREQ(imtype_arg, "AVIRAW")) {
1544     return R_IMF_IMTYPE_AVIRAW;
1545   }
1546   if (STREQ(imtype_arg, "AVIJPEG")) {
1547     return R_IMF_IMTYPE_AVIJPEG;
1548   }
1549   if (STREQ(imtype_arg, "PNG")) {
1550     return R_IMF_IMTYPE_PNG;
1551   }
1552   if (STREQ(imtype_arg, "BMP")) {
1553     return R_IMF_IMTYPE_BMP;
1554   }
1555 #ifdef WITH_HDR
1556   if (STREQ(imtype_arg, "HDR")) {
1557     return R_IMF_IMTYPE_RADHDR;
1558   }
1559 #endif
1560 #ifdef WITH_TIFF
1561   if (STREQ(imtype_arg, "TIFF")) {
1562     return R_IMF_IMTYPE_TIFF;
1563   }
1564 #endif
1565 #ifdef WITH_OPENEXR
1566   if (STREQ(imtype_arg, "OPEN_EXR")) {
1567     return R_IMF_IMTYPE_OPENEXR;
1568   }
1569   if (STREQ(imtype_arg, "OPEN_EXR_MULTILAYER")) {
1570     return R_IMF_IMTYPE_MULTILAYER;
1571   }
1572   if (STREQ(imtype_arg, "EXR")) {
1573     return R_IMF_IMTYPE_OPENEXR;
1574   }
1575   if (STREQ(imtype_arg, "MULTILAYER")) {
1576     return R_IMF_IMTYPE_MULTILAYER;
1577   }
1578 #endif
1579   if (STREQ(imtype_arg, "FFMPEG")) {
1580     return R_IMF_IMTYPE_FFMPEG;
1581   }
1582 #ifdef WITH_CINEON
1583   if (STREQ(imtype_arg, "CINEON")) {
1584     return R_IMF_IMTYPE_CINEON;
1585   }
1586   if (STREQ(imtype_arg, "DPX")) {
1587     return R_IMF_IMTYPE_DPX;
1588   }
1589 #endif
1590 #ifdef WITH_OPENJPEG
1591   if (STREQ(imtype_arg, "JP2")) {
1592     return R_IMF_IMTYPE_JP2;
1593   }
1594 #endif
1595 
1596   return R_IMF_IMTYPE_INVALID;
1597 }
1598 
do_add_image_extension(char * string,const char imtype,const ImageFormatData * im_format)1599 static bool do_add_image_extension(char *string,
1600                                    const char imtype,
1601                                    const ImageFormatData *im_format)
1602 {
1603   const char *extension = NULL;
1604   const char *extension_test;
1605   (void)im_format; /* may be unused, depends on build options */
1606 
1607   if (imtype == R_IMF_IMTYPE_IRIS) {
1608     if (!BLI_path_extension_check(string, extension_test = ".rgb")) {
1609       extension = extension_test;
1610     }
1611   }
1612   else if (imtype == R_IMF_IMTYPE_IRIZ) {
1613     if (!BLI_path_extension_check(string, extension_test = ".rgb")) {
1614       extension = extension_test;
1615     }
1616   }
1617 #ifdef WITH_HDR
1618   else if (imtype == R_IMF_IMTYPE_RADHDR) {
1619     if (!BLI_path_extension_check(string, extension_test = ".hdr")) {
1620       extension = extension_test;
1621     }
1622   }
1623 #endif
1624   else if (ELEM(imtype,
1625                 R_IMF_IMTYPE_PNG,
1626                 R_IMF_IMTYPE_FFMPEG,
1627                 R_IMF_IMTYPE_H264,
1628                 R_IMF_IMTYPE_THEORA,
1629                 R_IMF_IMTYPE_XVID)) {
1630     if (!BLI_path_extension_check(string, extension_test = ".png")) {
1631       extension = extension_test;
1632     }
1633   }
1634 #ifdef WITH_DDS
1635   else if (imtype == R_IMF_IMTYPE_DDS) {
1636     if (!BLI_path_extension_check(string, extension_test = ".dds")) {
1637       extension = extension_test;
1638     }
1639   }
1640 #endif
1641   else if (ELEM(imtype, R_IMF_IMTYPE_TARGA, R_IMF_IMTYPE_RAWTGA)) {
1642     if (!BLI_path_extension_check(string, extension_test = ".tga")) {
1643       extension = extension_test;
1644     }
1645   }
1646   else if (imtype == R_IMF_IMTYPE_BMP) {
1647     if (!BLI_path_extension_check(string, extension_test = ".bmp")) {
1648       extension = extension_test;
1649     }
1650   }
1651 #ifdef WITH_TIFF
1652   else if (imtype == R_IMF_IMTYPE_TIFF) {
1653     if (!BLI_path_extension_check_n(string, extension_test = ".tif", ".tiff", NULL)) {
1654       extension = extension_test;
1655     }
1656   }
1657 #endif
1658 #ifdef WITH_OPENIMAGEIO
1659   else if (imtype == R_IMF_IMTYPE_PSD) {
1660     if (!BLI_path_extension_check(string, extension_test = ".psd")) {
1661       extension = extension_test;
1662     }
1663   }
1664 #endif
1665 #ifdef WITH_OPENEXR
1666   else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1667     if (!BLI_path_extension_check(string, extension_test = ".exr")) {
1668       extension = extension_test;
1669     }
1670   }
1671 #endif
1672 #ifdef WITH_CINEON
1673   else if (imtype == R_IMF_IMTYPE_CINEON) {
1674     if (!BLI_path_extension_check(string, extension_test = ".cin")) {
1675       extension = extension_test;
1676     }
1677   }
1678   else if (imtype == R_IMF_IMTYPE_DPX) {
1679     if (!BLI_path_extension_check(string, extension_test = ".dpx")) {
1680       extension = extension_test;
1681     }
1682   }
1683 #endif
1684 #ifdef WITH_OPENJPEG
1685   else if (imtype == R_IMF_IMTYPE_JP2) {
1686     if (im_format) {
1687       if (im_format->jp2_codec == R_IMF_JP2_CODEC_JP2) {
1688         if (!BLI_path_extension_check(string, extension_test = ".jp2")) {
1689           extension = extension_test;
1690         }
1691       }
1692       else if (im_format->jp2_codec == R_IMF_JP2_CODEC_J2K) {
1693         if (!BLI_path_extension_check(string, extension_test = ".j2c")) {
1694           extension = extension_test;
1695         }
1696       }
1697       else {
1698         BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
1699       }
1700     }
1701     else {
1702       if (!BLI_path_extension_check(string, extension_test = ".jp2")) {
1703         extension = extension_test;
1704       }
1705     }
1706   }
1707 #endif
1708   else {  //   R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90 etc
1709     if (!(BLI_path_extension_check_n(string, extension_test = ".jpg", ".jpeg", NULL))) {
1710       extension = extension_test;
1711     }
1712   }
1713 
1714   if (extension) {
1715     /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1716     /* remove any other known image extension */
1717     if (BLI_path_extension_check_array(string, imb_ext_image)) {
1718       return BLI_path_extension_replace(string, FILE_MAX, extension);
1719     }
1720 
1721     return BLI_path_extension_ensure(string, FILE_MAX, extension);
1722   }
1723 
1724   return false;
1725 }
1726 
BKE_image_path_ensure_ext_from_imformat(char * string,const ImageFormatData * im_format)1727 int BKE_image_path_ensure_ext_from_imformat(char *string, const ImageFormatData *im_format)
1728 {
1729   return do_add_image_extension(string, im_format->imtype, im_format);
1730 }
1731 
BKE_image_path_ensure_ext_from_imtype(char * string,const char imtype)1732 int BKE_image_path_ensure_ext_from_imtype(char *string, const char imtype)
1733 {
1734   return do_add_image_extension(string, imtype, NULL);
1735 }
1736 
BKE_imformat_defaults(ImageFormatData * im_format)1737 void BKE_imformat_defaults(ImageFormatData *im_format)
1738 {
1739   memset(im_format, 0, sizeof(*im_format));
1740   im_format->planes = R_IMF_PLANES_RGBA;
1741   im_format->imtype = R_IMF_IMTYPE_PNG;
1742   im_format->depth = R_IMF_CHAN_DEPTH_8;
1743   im_format->quality = 90;
1744   im_format->compress = 15;
1745 
1746   BKE_color_managed_display_settings_init(&im_format->display_settings);
1747   BKE_color_managed_view_settings_init_default(&im_format->view_settings,
1748                                                &im_format->display_settings);
1749 }
1750 
BKE_imbuf_to_image_format(struct ImageFormatData * im_format,const ImBuf * imbuf)1751 void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
1752 {
1753   int ftype = imbuf->ftype;
1754   int custom_flags = imbuf->foptions.flag;
1755   char quality = imbuf->foptions.quality;
1756 
1757   BKE_imformat_defaults(im_format);
1758 
1759   /* file type */
1760 
1761   if (ftype == IMB_FTYPE_IMAGIC) {
1762     im_format->imtype = R_IMF_IMTYPE_IRIS;
1763   }
1764 #ifdef WITH_HDR
1765   else if (ftype == IMB_FTYPE_RADHDR) {
1766     im_format->imtype = R_IMF_IMTYPE_RADHDR;
1767   }
1768 #endif
1769   else if (ftype == IMB_FTYPE_PNG) {
1770     im_format->imtype = R_IMF_IMTYPE_PNG;
1771 
1772     if (custom_flags & PNG_16BIT) {
1773       im_format->depth = R_IMF_CHAN_DEPTH_16;
1774     }
1775 
1776     im_format->compress = quality;
1777   }
1778 
1779 #ifdef WITH_DDS
1780   else if (ftype == IMB_FTYPE_DDS) {
1781     im_format->imtype = R_IMF_IMTYPE_DDS;
1782   }
1783 #endif
1784   else if (ftype == IMB_FTYPE_BMP) {
1785     im_format->imtype = R_IMF_IMTYPE_BMP;
1786   }
1787 #ifdef WITH_TIFF
1788   else if (ftype == IMB_FTYPE_TIF) {
1789     im_format->imtype = R_IMF_IMTYPE_TIFF;
1790     if (custom_flags & TIF_16BIT) {
1791       im_format->depth = R_IMF_CHAN_DEPTH_16;
1792     }
1793     if (custom_flags & TIF_COMPRESS_NONE) {
1794       im_format->tiff_codec = R_IMF_TIFF_CODEC_NONE;
1795     }
1796     if (custom_flags & TIF_COMPRESS_DEFLATE) {
1797       im_format->tiff_codec = R_IMF_TIFF_CODEC_DEFLATE;
1798     }
1799     if (custom_flags & TIF_COMPRESS_LZW) {
1800       im_format->tiff_codec = R_IMF_TIFF_CODEC_LZW;
1801     }
1802     if (custom_flags & TIF_COMPRESS_PACKBITS) {
1803       im_format->tiff_codec = R_IMF_TIFF_CODEC_PACKBITS;
1804     }
1805   }
1806 #endif
1807 
1808 #ifdef WITH_OPENEXR
1809   else if (ftype == IMB_FTYPE_OPENEXR) {
1810     im_format->imtype = R_IMF_IMTYPE_OPENEXR;
1811     if (custom_flags & OPENEXR_HALF) {
1812       im_format->depth = R_IMF_CHAN_DEPTH_16;
1813     }
1814     if (custom_flags & OPENEXR_COMPRESS) {
1815       im_format->exr_codec = R_IMF_EXR_CODEC_ZIP; /* Can't determine compression */
1816     }
1817     if (imbuf->zbuf_float) {
1818       im_format->flag |= R_IMF_FLAG_ZBUF;
1819     }
1820   }
1821 #endif
1822 
1823 #ifdef WITH_CINEON
1824   else if (ftype == IMB_FTYPE_CINEON) {
1825     im_format->imtype = R_IMF_IMTYPE_CINEON;
1826   }
1827   else if (ftype == IMB_FTYPE_DPX) {
1828     im_format->imtype = R_IMF_IMTYPE_DPX;
1829   }
1830 #endif
1831   else if (ftype == IMB_FTYPE_TGA) {
1832     if (custom_flags & RAWTGA) {
1833       im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1834     }
1835     else {
1836       im_format->imtype = R_IMF_IMTYPE_TARGA;
1837     }
1838   }
1839 #ifdef WITH_OPENJPEG
1840   else if (ftype == IMB_FTYPE_JP2) {
1841     im_format->imtype = R_IMF_IMTYPE_JP2;
1842     im_format->quality = quality;
1843 
1844     if (custom_flags & JP2_16BIT) {
1845       im_format->depth = R_IMF_CHAN_DEPTH_16;
1846     }
1847     else if (custom_flags & JP2_12BIT) {
1848       im_format->depth = R_IMF_CHAN_DEPTH_12;
1849     }
1850 
1851     if (custom_flags & JP2_YCC) {
1852       im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1853     }
1854 
1855     if (custom_flags & JP2_CINE) {
1856       im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1857       if (custom_flags & JP2_CINE_48FPS) {
1858         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1859       }
1860     }
1861 
1862     if (custom_flags & JP2_JP2) {
1863       im_format->jp2_codec = R_IMF_JP2_CODEC_JP2;
1864     }
1865     else if (custom_flags & JP2_J2K) {
1866       im_format->jp2_codec = R_IMF_JP2_CODEC_J2K;
1867     }
1868     else {
1869       BLI_assert(!"Unsupported jp2 codec was specified in file type");
1870     }
1871   }
1872 #endif
1873 
1874   else {
1875     im_format->imtype = R_IMF_IMTYPE_JPEG90;
1876     im_format->quality = quality;
1877   }
1878 
1879   /* planes */
1880   im_format->planes = imbuf->planes;
1881 }
1882 
1883 #define STAMP_NAME_SIZE ((MAX_ID_NAME - 2) + 16)
1884 /* could allow access externally - 512 is for long names,
1885  * STAMP_NAME_SIZE is for id names, allowing them some room for description */
1886 typedef struct StampDataCustomField {
1887   struct StampDataCustomField *next, *prev;
1888   /* TODO(sergey): Think of better size here, maybe dynamically allocated even. */
1889   char key[512];
1890   char *value;
1891   /* TODO(sergey): Support non-string values. */
1892 } StampDataCustomField;
1893 
1894 typedef struct StampData {
1895   char file[512];
1896   char note[512];
1897   char date[512];
1898   char marker[512];
1899   char time[512];
1900   char frame[512];
1901   char frame_range[512];
1902   char camera[STAMP_NAME_SIZE];
1903   char cameralens[STAMP_NAME_SIZE];
1904   char scene[STAMP_NAME_SIZE];
1905   char strip[STAMP_NAME_SIZE];
1906   char rendertime[STAMP_NAME_SIZE];
1907   char memory[STAMP_NAME_SIZE];
1908   char hostname[512];
1909 
1910   /* Custom fields are used to put extra meta information header from render
1911    * engine to the result image.
1912    *
1913    * NOTE: This fields are not stamped onto the image. At least for now.
1914    */
1915   ListBase custom_fields;
1916 } StampData;
1917 #undef STAMP_NAME_SIZE
1918 
1919 /**
1920  * \param do_prefix: Include a label like "File ", "Date ", etc. in the stamp data strings.
1921  * \param use_dynamic: Also include data that can change on a per-frame basis.
1922  */
stampdata(const Scene * scene,Object * camera,StampData * stamp_data,int do_prefix,bool use_dynamic)1923 static void stampdata(
1924     const Scene *scene, Object *camera, StampData *stamp_data, int do_prefix, bool use_dynamic)
1925 {
1926   char text[256];
1927   struct tm *tl;
1928   time_t t;
1929 
1930   if (scene->r.stamp & R_STAMP_FILENAME) {
1931     SNPRINTF(stamp_data->file,
1932              do_prefix ? "File %s" : "%s",
1933              G.relbase_valid ? BKE_main_blendfile_path_from_global() : "<untitled>");
1934   }
1935   else {
1936     stamp_data->file[0] = '\0';
1937   }
1938 
1939   if (scene->r.stamp & R_STAMP_NOTE) {
1940     /* Never do prefix for Note */
1941     SNPRINTF(stamp_data->note, "%s", scene->r.stamp_udata);
1942   }
1943   else {
1944     stamp_data->note[0] = '\0';
1945   }
1946 
1947   if (scene->r.stamp & R_STAMP_DATE) {
1948     t = time(NULL);
1949     tl = localtime(&t);
1950     SNPRINTF(text,
1951              "%04d/%02d/%02d %02d:%02d:%02d",
1952              tl->tm_year + 1900,
1953              tl->tm_mon + 1,
1954              tl->tm_mday,
1955              tl->tm_hour,
1956              tl->tm_min,
1957              tl->tm_sec);
1958     SNPRINTF(stamp_data->date, do_prefix ? "Date %s" : "%s", text);
1959   }
1960   else {
1961     stamp_data->date[0] = '\0';
1962   }
1963 
1964   if (use_dynamic && scene->r.stamp & R_STAMP_MARKER) {
1965     const char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1966 
1967     if (name) {
1968       STRNCPY(text, name);
1969     }
1970     else {
1971       STRNCPY(text, "<none>");
1972     }
1973 
1974     SNPRINTF(stamp_data->marker, do_prefix ? "Marker %s" : "%s", text);
1975   }
1976   else {
1977     stamp_data->marker[0] = '\0';
1978   }
1979 
1980   if (use_dynamic && scene->r.stamp & R_STAMP_TIME) {
1981     const short timecode_style = USER_TIMECODE_SMPTE_FULL;
1982     BLI_timecode_string_from_time(
1983         text, sizeof(text), 0, FRA2TIME(scene->r.cfra), FPS, timecode_style);
1984     SNPRINTF(stamp_data->time, do_prefix ? "Timecode %s" : "%s", text);
1985   }
1986   else {
1987     stamp_data->time[0] = '\0';
1988   }
1989 
1990   if (use_dynamic && scene->r.stamp & R_STAMP_FRAME) {
1991     char fmtstr[32];
1992     int digits = 1;
1993 
1994     if (scene->r.efra > 9) {
1995       digits = integer_digits_i(scene->r.efra);
1996     }
1997 
1998     SNPRINTF(fmtstr, do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1999     SNPRINTF(stamp_data->frame, fmtstr, scene->r.cfra);
2000   }
2001   else {
2002     stamp_data->frame[0] = '\0';
2003   }
2004 
2005   if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
2006     SNPRINTF(stamp_data->frame_range,
2007              do_prefix ? "Frame Range %d:%d" : "%d:%d",
2008              scene->r.sfra,
2009              scene->r.efra);
2010   }
2011   else {
2012     stamp_data->frame_range[0] = '\0';
2013   }
2014 
2015   if (use_dynamic && scene->r.stamp & R_STAMP_CAMERA) {
2016     SNPRINTF(stamp_data->camera,
2017              do_prefix ? "Camera %s" : "%s",
2018              camera ? camera->id.name + 2 : "<none>");
2019   }
2020   else {
2021     stamp_data->camera[0] = '\0';
2022   }
2023 
2024   if (use_dynamic && scene->r.stamp & R_STAMP_CAMERALENS) {
2025     if (camera && camera->type == OB_CAMERA) {
2026       SNPRINTF(text, "%.2f", ((Camera *)camera->data)->lens);
2027     }
2028     else {
2029       STRNCPY(text, "<none>");
2030     }
2031 
2032     SNPRINTF(stamp_data->cameralens, do_prefix ? "Lens %s" : "%s", text);
2033   }
2034   else {
2035     stamp_data->cameralens[0] = '\0';
2036   }
2037 
2038   if (scene->r.stamp & R_STAMP_SCENE) {
2039     SNPRINTF(stamp_data->scene, do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
2040   }
2041   else {
2042     stamp_data->scene[0] = '\0';
2043   }
2044 
2045   if (use_dynamic && scene->r.stamp & R_STAMP_SEQSTRIP) {
2046     const Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
2047 
2048     if (seq) {
2049       STRNCPY(text, seq->name + 2);
2050     }
2051     else {
2052       STRNCPY(text, "<none>");
2053     }
2054 
2055     SNPRINTF(stamp_data->strip, do_prefix ? "Strip %s" : "%s", text);
2056   }
2057   else {
2058     stamp_data->strip[0] = '\0';
2059   }
2060 
2061   {
2062     Render *re = RE_GetSceneRender(scene);
2063     RenderStats *stats = re ? RE_GetStats(re) : NULL;
2064 
2065     if (use_dynamic && stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
2066       BLI_timecode_string_from_time_simple(text, sizeof(text), stats->lastframetime);
2067 
2068       SNPRINTF(stamp_data->rendertime, do_prefix ? "RenderTime %s" : "%s", text);
2069     }
2070     else {
2071       stamp_data->rendertime[0] = '\0';
2072     }
2073 
2074     if (use_dynamic && stats && (scene->r.stamp & R_STAMP_MEMORY)) {
2075       SNPRINTF(stamp_data->memory, do_prefix ? "Peak Memory %.2fM" : "%.2fM", stats->mem_peak);
2076     }
2077     else {
2078       stamp_data->memory[0] = '\0';
2079     }
2080   }
2081   if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
2082     SNPRINTF(stamp_data->frame_range,
2083              do_prefix ? "Frame Range %d:%d" : "%d:%d",
2084              scene->r.sfra,
2085              scene->r.efra);
2086   }
2087   else {
2088     stamp_data->frame_range[0] = '\0';
2089   }
2090 
2091   if (scene->r.stamp & R_STAMP_HOSTNAME) {
2092     char hostname[500]; /* sizeof(stamp_data->hostname) minus some bytes for a label. */
2093     BLI_hostname_get(hostname, sizeof(hostname));
2094     SNPRINTF(stamp_data->hostname, do_prefix ? "Hostname %s" : "%s", hostname);
2095   }
2096   else {
2097     stamp_data->hostname[0] = '\0';
2098   }
2099 }
2100 
stampdata_from_template(StampData * stamp_data,const Scene * scene,const StampData * stamp_data_template,bool do_prefix)2101 static void stampdata_from_template(StampData *stamp_data,
2102                                     const Scene *scene,
2103                                     const StampData *stamp_data_template,
2104                                     bool do_prefix)
2105 {
2106   if (scene->r.stamp & R_STAMP_FILENAME) {
2107     SNPRINTF(stamp_data->file, do_prefix ? "File %s" : "%s", stamp_data_template->file);
2108   }
2109   else {
2110     stamp_data->file[0] = '\0';
2111   }
2112   if (scene->r.stamp & R_STAMP_NOTE) {
2113     SNPRINTF(stamp_data->note, "%s", stamp_data_template->note);
2114   }
2115   else {
2116     stamp_data->note[0] = '\0';
2117   }
2118   if (scene->r.stamp & R_STAMP_DATE) {
2119     SNPRINTF(stamp_data->date, do_prefix ? "Date %s" : "%s", stamp_data_template->date);
2120   }
2121   else {
2122     stamp_data->date[0] = '\0';
2123   }
2124   if (scene->r.stamp & R_STAMP_MARKER) {
2125     SNPRINTF(stamp_data->marker, do_prefix ? "Marker %s" : "%s", stamp_data_template->marker);
2126   }
2127   else {
2128     stamp_data->marker[0] = '\0';
2129   }
2130   if (scene->r.stamp & R_STAMP_TIME) {
2131     SNPRINTF(stamp_data->time, do_prefix ? "Timecode %s" : "%s", stamp_data_template->time);
2132   }
2133   else {
2134     stamp_data->time[0] = '\0';
2135   }
2136   if (scene->r.stamp & R_STAMP_FRAME) {
2137     SNPRINTF(stamp_data->frame, do_prefix ? "Frame %s" : "%s", stamp_data_template->frame);
2138   }
2139   else {
2140     stamp_data->frame[0] = '\0';
2141   }
2142   if (scene->r.stamp & R_STAMP_CAMERA) {
2143     SNPRINTF(stamp_data->camera, do_prefix ? "Camera %s" : "%s", stamp_data_template->camera);
2144   }
2145   else {
2146     stamp_data->camera[0] = '\0';
2147   }
2148   if (scene->r.stamp & R_STAMP_CAMERALENS) {
2149     SNPRINTF(
2150         stamp_data->cameralens, do_prefix ? "Lens %s" : "%s", stamp_data_template->cameralens);
2151   }
2152   else {
2153     stamp_data->cameralens[0] = '\0';
2154   }
2155   if (scene->r.stamp & R_STAMP_SCENE) {
2156     SNPRINTF(stamp_data->scene, do_prefix ? "Scene %s" : "%s", stamp_data_template->scene);
2157   }
2158   else {
2159     stamp_data->scene[0] = '\0';
2160   }
2161   if (scene->r.stamp & R_STAMP_SEQSTRIP) {
2162     SNPRINTF(stamp_data->strip, do_prefix ? "Strip %s" : "%s", stamp_data_template->strip);
2163   }
2164   else {
2165     stamp_data->strip[0] = '\0';
2166   }
2167   if (scene->r.stamp & R_STAMP_RENDERTIME) {
2168     SNPRINTF(stamp_data->rendertime,
2169              do_prefix ? "RenderTime %s" : "%s",
2170              stamp_data_template->rendertime);
2171   }
2172   else {
2173     stamp_data->rendertime[0] = '\0';
2174   }
2175   if (scene->r.stamp & R_STAMP_MEMORY) {
2176     SNPRINTF(stamp_data->memory, do_prefix ? "Peak Memory %s" : "%s", stamp_data_template->memory);
2177   }
2178   else {
2179     stamp_data->memory[0] = '\0';
2180   }
2181   if (scene->r.stamp & R_STAMP_HOSTNAME) {
2182     SNPRINTF(
2183         stamp_data->hostname, do_prefix ? "Hostname %s" : "%s", stamp_data_template->hostname);
2184   }
2185   else {
2186     stamp_data->hostname[0] = '\0';
2187   }
2188 }
2189 
BKE_image_stamp_buf(Scene * scene,Object * camera,const StampData * stamp_data_template,unsigned char * rect,float * rectf,int width,int height,int channels)2190 void BKE_image_stamp_buf(Scene *scene,
2191                          Object *camera,
2192                          const StampData *stamp_data_template,
2193                          unsigned char *rect,
2194                          float *rectf,
2195                          int width,
2196                          int height,
2197                          int channels)
2198 {
2199   struct StampData stamp_data;
2200   float w, h, pad;
2201   int x, y, y_ofs;
2202   float h_fixed;
2203   const int mono = blf_mono_font_render; /* XXX */
2204   struct ColorManagedDisplay *display;
2205   const char *display_device;
2206 
2207   /* vars for calculating wordwrap */
2208   struct {
2209     struct ResultBLF info;
2210     rctf rect;
2211   } wrap;
2212 
2213   /* this could be an argument if we want to operate on non linear float imbuf's
2214    * for now though this is only used for renders which use scene settings */
2215 
2216 #define TEXT_SIZE_CHECK(str, w, h) \
2217   ((str[0]) && ((void)(h = h_fixed), (w = BLF_width(mono, str, sizeof(str)))))
2218 
2219   /* must enable BLF_WORD_WRAP before using */
2220 #define TEXT_SIZE_CHECK_WORD_WRAP(str, w, h) \
2221   ((str[0]) && (BLF_boundbox_ex(mono, str, sizeof(str), &wrap.rect, &wrap.info), \
2222                 (void)(h = h_fixed * wrap.info.lines), \
2223                 (w = BLI_rctf_size_x(&wrap.rect))))
2224 
2225 #define BUFF_MARGIN_X 2
2226 #define BUFF_MARGIN_Y 1
2227 
2228   if (!rect && !rectf) {
2229     return;
2230   }
2231 
2232   display_device = scene->display_settings.display_device;
2233   display = IMB_colormanagement_display_get_named(display_device);
2234 
2235   bool do_prefix = (scene->r.stamp & R_STAMP_HIDE_LABELS) == 0;
2236   if (stamp_data_template == NULL) {
2237     stampdata(scene, camera, &stamp_data, do_prefix, true);
2238   }
2239   else {
2240     stampdata_from_template(&stamp_data, scene, stamp_data_template, do_prefix);
2241   }
2242 
2243   /* TODO, do_versions */
2244   if (scene->r.stamp_font_id < 8) {
2245     scene->r.stamp_font_id = 12;
2246   }
2247 
2248   /* set before return */
2249   BLF_size(mono, scene->r.stamp_font_id, 72);
2250   BLF_wordwrap(mono, width - (BUFF_MARGIN_X * 2));
2251 
2252   BLF_buffer(mono, rectf, rect, width, height, channels, display);
2253   BLF_buffer_col(mono, scene->r.fg_stamp);
2254   pad = BLF_width_max(mono);
2255 
2256   /* use 'h_fixed' rather than 'h', aligns better */
2257   h_fixed = BLF_height_max(mono);
2258   y_ofs = -BLF_descender(mono);
2259 
2260   x = 0;
2261   y = height;
2262 
2263   if (TEXT_SIZE_CHECK(stamp_data.file, w, h)) {
2264     /* Top left corner */
2265     y -= h;
2266 
2267     /* also a little of space to the background. */
2268     buf_rectfill_area(rect,
2269                       rectf,
2270                       width,
2271                       height,
2272                       scene->r.bg_stamp,
2273                       display,
2274                       x - BUFF_MARGIN_X,
2275                       y - BUFF_MARGIN_Y,
2276                       w + BUFF_MARGIN_X,
2277                       y + h + BUFF_MARGIN_Y);
2278 
2279     /* and draw the text. */
2280     BLF_position(mono, x, y + y_ofs, 0.0);
2281     BLF_draw_buffer(mono, stamp_data.file, BLF_DRAW_STR_DUMMY_MAX);
2282 
2283     /* the extra pixel for background. */
2284     y -= BUFF_MARGIN_Y * 2;
2285   }
2286 
2287   /* Top left corner, below File */
2288   if (TEXT_SIZE_CHECK(stamp_data.date, w, h)) {
2289     y -= h;
2290 
2291     /* and space for background. */
2292     buf_rectfill_area(rect,
2293                       rectf,
2294                       width,
2295                       height,
2296                       scene->r.bg_stamp,
2297                       display,
2298                       0,
2299                       y - BUFF_MARGIN_Y,
2300                       w + BUFF_MARGIN_X,
2301                       y + h + BUFF_MARGIN_Y);
2302 
2303     BLF_position(mono, x, y + y_ofs, 0.0);
2304     BLF_draw_buffer(mono, stamp_data.date, BLF_DRAW_STR_DUMMY_MAX);
2305 
2306     /* the extra pixel for background. */
2307     y -= BUFF_MARGIN_Y * 2;
2308   }
2309 
2310   /* Top left corner, below File, Date */
2311   if (TEXT_SIZE_CHECK(stamp_data.rendertime, w, h)) {
2312     y -= h;
2313 
2314     /* and space for background. */
2315     buf_rectfill_area(rect,
2316                       rectf,
2317                       width,
2318                       height,
2319                       scene->r.bg_stamp,
2320                       display,
2321                       0,
2322                       y - BUFF_MARGIN_Y,
2323                       w + BUFF_MARGIN_X,
2324                       y + h + BUFF_MARGIN_Y);
2325 
2326     BLF_position(mono, x, y + y_ofs, 0.0);
2327     BLF_draw_buffer(mono, stamp_data.rendertime, BLF_DRAW_STR_DUMMY_MAX);
2328 
2329     /* the extra pixel for background. */
2330     y -= BUFF_MARGIN_Y * 2;
2331   }
2332 
2333   /* Top left corner, below File, Date, Rendertime */
2334   if (TEXT_SIZE_CHECK(stamp_data.memory, w, h)) {
2335     y -= h;
2336 
2337     /* and space for background. */
2338     buf_rectfill_area(rect,
2339                       rectf,
2340                       width,
2341                       height,
2342                       scene->r.bg_stamp,
2343                       display,
2344                       0,
2345                       y - BUFF_MARGIN_Y,
2346                       w + BUFF_MARGIN_X,
2347                       y + h + BUFF_MARGIN_Y);
2348 
2349     BLF_position(mono, x, y + y_ofs, 0.0);
2350     BLF_draw_buffer(mono, stamp_data.memory, BLF_DRAW_STR_DUMMY_MAX);
2351 
2352     /* the extra pixel for background. */
2353     y -= BUFF_MARGIN_Y * 2;
2354   }
2355 
2356   /* Top left corner, below File, Date, Rendertime, Memory */
2357   if (TEXT_SIZE_CHECK(stamp_data.hostname, w, h)) {
2358     y -= h;
2359 
2360     /* and space for background. */
2361     buf_rectfill_area(rect,
2362                       rectf,
2363                       width,
2364                       height,
2365                       scene->r.bg_stamp,
2366                       display,
2367                       0,
2368                       y - BUFF_MARGIN_Y,
2369                       w + BUFF_MARGIN_X,
2370                       y + h + BUFF_MARGIN_Y);
2371 
2372     BLF_position(mono, x, y + y_ofs, 0.0);
2373     BLF_draw_buffer(mono, stamp_data.hostname, BLF_DRAW_STR_DUMMY_MAX);
2374 
2375     /* the extra pixel for background. */
2376     y -= BUFF_MARGIN_Y * 2;
2377   }
2378 
2379   /* Top left corner, below File, Date, Memory, Rendertime, Hostname */
2380   BLF_enable(mono, BLF_WORD_WRAP);
2381   if (TEXT_SIZE_CHECK_WORD_WRAP(stamp_data.note, w, h)) {
2382     y -= h;
2383 
2384     /* and space for background. */
2385     buf_rectfill_area(rect,
2386                       rectf,
2387                       width,
2388                       height,
2389                       scene->r.bg_stamp,
2390                       display,
2391                       0,
2392                       y - BUFF_MARGIN_Y,
2393                       w + BUFF_MARGIN_X,
2394                       y + h + BUFF_MARGIN_Y);
2395 
2396     BLF_position(mono, x, y + y_ofs + (h - h_fixed), 0.0);
2397     BLF_draw_buffer(mono, stamp_data.note, BLF_DRAW_STR_DUMMY_MAX);
2398   }
2399   BLF_disable(mono, BLF_WORD_WRAP);
2400 
2401   x = 0;
2402   y = 0;
2403 
2404   /* Bottom left corner, leaving space for timing */
2405   if (TEXT_SIZE_CHECK(stamp_data.marker, w, h)) {
2406 
2407     /* extra space for background. */
2408     buf_rectfill_area(rect,
2409                       rectf,
2410                       width,
2411                       height,
2412                       scene->r.bg_stamp,
2413                       display,
2414                       x - BUFF_MARGIN_X,
2415                       y - BUFF_MARGIN_Y,
2416                       w + BUFF_MARGIN_X,
2417                       y + h + BUFF_MARGIN_Y);
2418 
2419     /* and pad the text. */
2420     BLF_position(mono, x, y + y_ofs, 0.0);
2421     BLF_draw_buffer(mono, stamp_data.marker, BLF_DRAW_STR_DUMMY_MAX);
2422 
2423     /* space width. */
2424     x += w + pad;
2425   }
2426 
2427   /* Left bottom corner */
2428   if (TEXT_SIZE_CHECK(stamp_data.time, w, h)) {
2429 
2430     /* extra space for background */
2431     buf_rectfill_area(rect,
2432                       rectf,
2433                       width,
2434                       height,
2435                       scene->r.bg_stamp,
2436                       display,
2437                       x - BUFF_MARGIN_X,
2438                       y,
2439                       x + w + BUFF_MARGIN_X,
2440                       y + h + BUFF_MARGIN_Y);
2441 
2442     /* and pad the text. */
2443     BLF_position(mono, x, y + y_ofs, 0.0);
2444     BLF_draw_buffer(mono, stamp_data.time, BLF_DRAW_STR_DUMMY_MAX);
2445 
2446     /* space width. */
2447     x += w + pad;
2448   }
2449 
2450   if (TEXT_SIZE_CHECK(stamp_data.frame, w, h)) {
2451 
2452     /* extra space for background. */
2453     buf_rectfill_area(rect,
2454                       rectf,
2455                       width,
2456                       height,
2457                       scene->r.bg_stamp,
2458                       display,
2459                       x - BUFF_MARGIN_X,
2460                       y - BUFF_MARGIN_Y,
2461                       x + w + BUFF_MARGIN_X,
2462                       y + h + BUFF_MARGIN_Y);
2463 
2464     /* and pad the text. */
2465     BLF_position(mono, x, y + y_ofs, 0.0);
2466     BLF_draw_buffer(mono, stamp_data.frame, BLF_DRAW_STR_DUMMY_MAX);
2467 
2468     /* space width. */
2469     x += w + pad;
2470   }
2471 
2472   if (TEXT_SIZE_CHECK(stamp_data.camera, w, h)) {
2473 
2474     /* extra space for background. */
2475     buf_rectfill_area(rect,
2476                       rectf,
2477                       width,
2478                       height,
2479                       scene->r.bg_stamp,
2480                       display,
2481                       x - BUFF_MARGIN_X,
2482                       y - BUFF_MARGIN_Y,
2483                       x + w + BUFF_MARGIN_X,
2484                       y + h + BUFF_MARGIN_Y);
2485     BLF_position(mono, x, y + y_ofs, 0.0);
2486     BLF_draw_buffer(mono, stamp_data.camera, BLF_DRAW_STR_DUMMY_MAX);
2487 
2488     /* space width. */
2489     x += w + pad;
2490   }
2491 
2492   if (TEXT_SIZE_CHECK(stamp_data.cameralens, w, h)) {
2493 
2494     /* extra space for background. */
2495     buf_rectfill_area(rect,
2496                       rectf,
2497                       width,
2498                       height,
2499                       scene->r.bg_stamp,
2500                       display,
2501                       x - BUFF_MARGIN_X,
2502                       y - BUFF_MARGIN_Y,
2503                       x + w + BUFF_MARGIN_X,
2504                       y + h + BUFF_MARGIN_Y);
2505     BLF_position(mono, x, y + y_ofs, 0.0);
2506     BLF_draw_buffer(mono, stamp_data.cameralens, BLF_DRAW_STR_DUMMY_MAX);
2507   }
2508 
2509   if (TEXT_SIZE_CHECK(stamp_data.scene, w, h)) {
2510 
2511     /* Bottom right corner, with an extra space because blenfont is too strict! */
2512     x = width - w - 2;
2513 
2514     /* extra space for background. */
2515     buf_rectfill_area(rect,
2516                       rectf,
2517                       width,
2518                       height,
2519                       scene->r.bg_stamp,
2520                       display,
2521                       x - BUFF_MARGIN_X,
2522                       y - BUFF_MARGIN_Y,
2523                       x + w + BUFF_MARGIN_X,
2524                       y + h + BUFF_MARGIN_Y);
2525 
2526     /* and pad the text. */
2527     BLF_position(mono, x, y + y_ofs, 0.0);
2528     BLF_draw_buffer(mono, stamp_data.scene, BLF_DRAW_STR_DUMMY_MAX);
2529   }
2530 
2531   if (TEXT_SIZE_CHECK(stamp_data.strip, w, h)) {
2532 
2533     /* Top right corner, with an extra space because blenfont is too strict! */
2534     x = width - w - pad;
2535     y = height - h;
2536 
2537     /* extra space for background. */
2538     buf_rectfill_area(rect,
2539                       rectf,
2540                       width,
2541                       height,
2542                       scene->r.bg_stamp,
2543                       display,
2544                       x - BUFF_MARGIN_X,
2545                       y - BUFF_MARGIN_Y,
2546                       x + w + BUFF_MARGIN_X,
2547                       y + h + BUFF_MARGIN_Y);
2548 
2549     BLF_position(mono, x, y + y_ofs, 0.0);
2550     BLF_draw_buffer(mono, stamp_data.strip, BLF_DRAW_STR_DUMMY_MAX);
2551   }
2552 
2553   /* cleanup the buffer. */
2554   BLF_buffer(mono, NULL, NULL, 0, 0, 0, NULL);
2555   BLF_wordwrap(mono, 0);
2556 
2557 #undef TEXT_SIZE_CHECK
2558 #undef TEXT_SIZE_CHECK_WORD_WRAP
2559 #undef BUFF_MARGIN_X
2560 #undef BUFF_MARGIN_Y
2561 }
2562 
BKE_render_result_stamp_info(Scene * scene,Object * camera,struct RenderResult * rr,bool allocate_only)2563 void BKE_render_result_stamp_info(Scene *scene,
2564                                   Object *camera,
2565                                   struct RenderResult *rr,
2566                                   bool allocate_only)
2567 {
2568   struct StampData *stamp_data;
2569 
2570   if (!(scene && (scene->r.stamp & R_STAMP_ALL)) && !allocate_only) {
2571     return;
2572   }
2573 
2574   if (!rr->stamp_data) {
2575     stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2576   }
2577   else {
2578     stamp_data = rr->stamp_data;
2579   }
2580 
2581   if (!allocate_only) {
2582     stampdata(scene, camera, stamp_data, 0, true);
2583   }
2584 
2585   if (!rr->stamp_data) {
2586     rr->stamp_data = stamp_data;
2587   }
2588 }
2589 
BKE_stamp_info_from_scene_static(const Scene * scene)2590 struct StampData *BKE_stamp_info_from_scene_static(const Scene *scene)
2591 {
2592   struct StampData *stamp_data;
2593 
2594   if (!(scene && (scene->r.stamp & R_STAMP_ALL))) {
2595     return NULL;
2596   }
2597 
2598   /* Memory is allocated here (instead of by the caller) so that the caller
2599    * doesn't have to know the size of the StampData struct. */
2600   stamp_data = MEM_callocN(sizeof(StampData), __func__);
2601   stampdata(scene, NULL, stamp_data, 0, false);
2602 
2603   return stamp_data;
2604 }
2605 
2606 static const char *stamp_metadata_fields[] = {
2607     "File",
2608     "Note",
2609     "Date",
2610     "Marker",
2611     "Time",
2612     "Frame",
2613     "FrameRange",
2614     "Camera",
2615     "Lens",
2616     "Scene",
2617     "Strip",
2618     "RenderTime",
2619     "Memory",
2620     "Hostname",
2621     NULL,
2622 };
2623 
2624 /* Check whether the given metadata field name translates to a known field of
2625  * a stamp. */
BKE_stamp_is_known_field(const char * field_name)2626 bool BKE_stamp_is_known_field(const char *field_name)
2627 {
2628   int i = 0;
2629   while (stamp_metadata_fields[i] != NULL) {
2630     if (STREQ(field_name, stamp_metadata_fields[i])) {
2631       return true;
2632     }
2633     i++;
2634   }
2635   return false;
2636 }
2637 
BKE_stamp_info_callback(void * data,struct StampData * stamp_data,StampCallback callback,bool noskip)2638 void BKE_stamp_info_callback(void *data,
2639                              struct StampData *stamp_data,
2640                              StampCallback callback,
2641                              bool noskip)
2642 {
2643   if ((callback == NULL) || (stamp_data == NULL)) {
2644     return;
2645   }
2646 
2647 #define CALL(member, value_str) \
2648   if (noskip || stamp_data->member[0]) { \
2649     callback(data, value_str, stamp_data->member, sizeof(stamp_data->member)); \
2650   } \
2651   ((void)0)
2652 
2653   /* TODO(sergey): Use stamp_metadata_fields somehow, or make it more generic
2654    * meta information to avoid duplication. */
2655   CALL(file, "File");
2656   CALL(note, "Note");
2657   CALL(date, "Date");
2658   CALL(marker, "Marker");
2659   CALL(time, "Time");
2660   CALL(frame, "Frame");
2661   CALL(frame_range, "FrameRange");
2662   CALL(camera, "Camera");
2663   CALL(cameralens, "Lens");
2664   CALL(scene, "Scene");
2665   CALL(strip, "Strip");
2666   CALL(rendertime, "RenderTime");
2667   CALL(memory, "Memory");
2668   CALL(hostname, "Hostname");
2669 
2670   LISTBASE_FOREACH (StampDataCustomField *, custom_field, &stamp_data->custom_fields) {
2671     if (noskip || custom_field->value[0]) {
2672       callback(data, custom_field->key, custom_field->value, strlen(custom_field->value) + 1);
2673     }
2674   }
2675 
2676 #undef CALL
2677 }
2678 
BKE_render_result_stamp_data(RenderResult * rr,const char * key,const char * value)2679 void BKE_render_result_stamp_data(RenderResult *rr, const char *key, const char *value)
2680 {
2681   StampData *stamp_data;
2682   if (rr->stamp_data == NULL) {
2683     rr->stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2684   }
2685   stamp_data = rr->stamp_data;
2686   StampDataCustomField *field = MEM_mallocN(sizeof(StampDataCustomField),
2687                                             "StampData Custom Field");
2688   STRNCPY(field->key, key);
2689   field->value = BLI_strdup(value);
2690   BLI_addtail(&stamp_data->custom_fields, field);
2691 }
2692 
BKE_stamp_data_copy(const StampData * stamp_data)2693 StampData *BKE_stamp_data_copy(const StampData *stamp_data)
2694 {
2695   if (stamp_data == NULL) {
2696     return NULL;
2697   }
2698 
2699   StampData *stamp_datan = MEM_dupallocN(stamp_data);
2700   BLI_duplicatelist(&stamp_datan->custom_fields, &stamp_data->custom_fields);
2701 
2702   LISTBASE_FOREACH (StampDataCustomField *, custom_fieldn, &stamp_datan->custom_fields) {
2703     custom_fieldn->value = MEM_dupallocN(custom_fieldn->value);
2704   }
2705 
2706   return stamp_datan;
2707 }
2708 
BKE_stamp_data_free(StampData * stamp_data)2709 void BKE_stamp_data_free(StampData *stamp_data)
2710 {
2711   if (stamp_data == NULL) {
2712     return;
2713   }
2714   LISTBASE_FOREACH (StampDataCustomField *, custom_field, &stamp_data->custom_fields) {
2715     MEM_freeN(custom_field->value);
2716   }
2717   BLI_freelistN(&stamp_data->custom_fields);
2718   MEM_freeN(stamp_data);
2719 }
2720 
2721 /* wrap for callback only */
metadata_set_field(void * data,const char * propname,char * propvalue,int UNUSED (len))2722 static void metadata_set_field(void *data, const char *propname, char *propvalue, int UNUSED(len))
2723 {
2724   /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
2725   struct ImBuf *imbuf = data;
2726   IMB_metadata_set_field(imbuf->metadata, propname, propvalue);
2727 }
2728 
metadata_get_field(void * data,const char * propname,char * propvalue,int len)2729 static void metadata_get_field(void *data, const char *propname, char *propvalue, int len)
2730 {
2731   /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
2732   struct ImBuf *imbuf = data;
2733   IMB_metadata_get_field(imbuf->metadata, propname, propvalue, len);
2734 }
2735 
BKE_imbuf_stamp_info(RenderResult * rr,struct ImBuf * ibuf)2736 void BKE_imbuf_stamp_info(RenderResult *rr, struct ImBuf *ibuf)
2737 {
2738   struct StampData *stamp_data = rr->stamp_data;
2739   IMB_metadata_ensure(&ibuf->metadata);
2740   BKE_stamp_info_callback(ibuf, stamp_data, metadata_set_field, false);
2741 }
2742 
metadata_copy_custom_fields(const char * field,const char * value,void * rr_v)2743 static void metadata_copy_custom_fields(const char *field, const char *value, void *rr_v)
2744 {
2745   if (BKE_stamp_is_known_field(field)) {
2746     return;
2747   }
2748   RenderResult *rr = (RenderResult *)rr_v;
2749   BKE_render_result_stamp_data(rr, field, value);
2750 }
2751 
BKE_stamp_info_from_imbuf(RenderResult * rr,struct ImBuf * ibuf)2752 void BKE_stamp_info_from_imbuf(RenderResult *rr, struct ImBuf *ibuf)
2753 {
2754   if (rr->stamp_data == NULL) {
2755     rr->stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2756   }
2757   struct StampData *stamp_data = rr->stamp_data;
2758   IMB_metadata_ensure(&ibuf->metadata);
2759   BKE_stamp_info_callback(ibuf, stamp_data, metadata_get_field, true);
2760   /* Copy render engine specific settings. */
2761   IMB_metadata_foreach(ibuf, metadata_copy_custom_fields, rr);
2762 }
2763 
BKE_imbuf_alpha_test(ImBuf * ibuf)2764 bool BKE_imbuf_alpha_test(ImBuf *ibuf)
2765 {
2766   int tot;
2767   if (ibuf->rect_float) {
2768     const float *buf = ibuf->rect_float;
2769     for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2770       if (buf[3] < 1.0f) {
2771         return true;
2772       }
2773     }
2774   }
2775   else if (ibuf->rect) {
2776     unsigned char *buf = (unsigned char *)ibuf->rect;
2777     for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2778       if (buf[3] != 255) {
2779         return true;
2780       }
2781     }
2782   }
2783 
2784   return false;
2785 }
2786 
2787 /* note: imf->planes is ignored here, its assumed the image channels
2788  * are already set */
BKE_imbuf_write_prepare(ImBuf * ibuf,const ImageFormatData * imf)2789 void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf)
2790 {
2791   char imtype = imf->imtype;
2792   char compress = imf->compress;
2793   char quality = imf->quality;
2794 
2795   /* initialize all from image format */
2796   ibuf->foptions.flag = 0;
2797 
2798   if (imtype == R_IMF_IMTYPE_IRIS) {
2799     ibuf->ftype = IMB_FTYPE_IMAGIC;
2800   }
2801 #ifdef WITH_HDR
2802   else if (imtype == R_IMF_IMTYPE_RADHDR) {
2803     ibuf->ftype = IMB_FTYPE_RADHDR;
2804   }
2805 #endif
2806   else if (ELEM(imtype,
2807                 R_IMF_IMTYPE_PNG,
2808                 R_IMF_IMTYPE_FFMPEG,
2809                 R_IMF_IMTYPE_H264,
2810                 R_IMF_IMTYPE_THEORA,
2811                 R_IMF_IMTYPE_XVID)) {
2812     ibuf->ftype = IMB_FTYPE_PNG;
2813 
2814     if (imtype == R_IMF_IMTYPE_PNG) {
2815       if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2816         ibuf->foptions.flag |= PNG_16BIT;
2817       }
2818 
2819       ibuf->foptions.quality = compress;
2820     }
2821   }
2822 #ifdef WITH_DDS
2823   else if (imtype == R_IMF_IMTYPE_DDS) {
2824     ibuf->ftype = IMB_FTYPE_DDS;
2825   }
2826 #endif
2827   else if (imtype == R_IMF_IMTYPE_BMP) {
2828     ibuf->ftype = IMB_FTYPE_BMP;
2829   }
2830 #ifdef WITH_TIFF
2831   else if (imtype == R_IMF_IMTYPE_TIFF) {
2832     ibuf->ftype = IMB_FTYPE_TIF;
2833 
2834     if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2835       ibuf->foptions.flag |= TIF_16BIT;
2836     }
2837     if (imf->tiff_codec == R_IMF_TIFF_CODEC_NONE) {
2838       ibuf->foptions.flag |= TIF_COMPRESS_NONE;
2839     }
2840     else if (imf->tiff_codec == R_IMF_TIFF_CODEC_DEFLATE) {
2841       ibuf->foptions.flag |= TIF_COMPRESS_DEFLATE;
2842     }
2843     else if (imf->tiff_codec == R_IMF_TIFF_CODEC_LZW) {
2844       ibuf->foptions.flag |= TIF_COMPRESS_LZW;
2845     }
2846     else if (imf->tiff_codec == R_IMF_TIFF_CODEC_PACKBITS) {
2847       ibuf->foptions.flag |= TIF_COMPRESS_PACKBITS;
2848     }
2849   }
2850 #endif
2851 #ifdef WITH_OPENEXR
2852   else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
2853     ibuf->ftype = IMB_FTYPE_OPENEXR;
2854     if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2855       ibuf->foptions.flag |= OPENEXR_HALF;
2856     }
2857     ibuf->foptions.flag |= (imf->exr_codec & OPENEXR_COMPRESS);
2858 
2859     if (!(imf->flag & R_IMF_FLAG_ZBUF)) {
2860       /* Signal for exr saving. */
2861       IMB_freezbuffloatImBuf(ibuf);
2862     }
2863   }
2864 #endif
2865 #ifdef WITH_CINEON
2866   else if (imtype == R_IMF_IMTYPE_CINEON) {
2867     ibuf->ftype = IMB_FTYPE_CINEON;
2868     if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2869       ibuf->foptions.flag |= CINEON_LOG;
2870     }
2871     if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2872       ibuf->foptions.flag |= CINEON_16BIT;
2873     }
2874     else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2875       ibuf->foptions.flag |= CINEON_12BIT;
2876     }
2877     else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2878       ibuf->foptions.flag |= CINEON_10BIT;
2879     }
2880   }
2881   else if (imtype == R_IMF_IMTYPE_DPX) {
2882     ibuf->ftype = IMB_FTYPE_DPX;
2883     if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2884       ibuf->foptions.flag |= CINEON_LOG;
2885     }
2886     if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2887       ibuf->foptions.flag |= CINEON_16BIT;
2888     }
2889     else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2890       ibuf->foptions.flag |= CINEON_12BIT;
2891     }
2892     else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2893       ibuf->foptions.flag |= CINEON_10BIT;
2894     }
2895   }
2896 #endif
2897   else if (imtype == R_IMF_IMTYPE_TARGA) {
2898     ibuf->ftype = IMB_FTYPE_TGA;
2899   }
2900   else if (imtype == R_IMF_IMTYPE_RAWTGA) {
2901     ibuf->ftype = IMB_FTYPE_TGA;
2902     ibuf->foptions.flag = RAWTGA;
2903   }
2904 #ifdef WITH_OPENJPEG
2905   else if (imtype == R_IMF_IMTYPE_JP2) {
2906     if (quality < 10) {
2907       quality = 90;
2908     }
2909     ibuf->ftype = IMB_FTYPE_JP2;
2910     ibuf->foptions.quality = quality;
2911 
2912     if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2913       ibuf->foptions.flag |= JP2_16BIT;
2914     }
2915     else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2916       ibuf->foptions.flag |= JP2_12BIT;
2917     }
2918 
2919     if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
2920       ibuf->foptions.flag |= JP2_YCC;
2921     }
2922 
2923     if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
2924       ibuf->foptions.flag |= JP2_CINE;
2925       if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48) {
2926         ibuf->foptions.flag |= JP2_CINE_48FPS;
2927       }
2928     }
2929 
2930     if (imf->jp2_codec == R_IMF_JP2_CODEC_JP2) {
2931       ibuf->foptions.flag |= JP2_JP2;
2932     }
2933     else if (imf->jp2_codec == R_IMF_JP2_CODEC_J2K) {
2934       ibuf->foptions.flag |= JP2_J2K;
2935     }
2936     else {
2937       BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
2938     }
2939   }
2940 #endif
2941   else {
2942     /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
2943     if (quality < 10) {
2944       quality = 90;
2945     }
2946     ibuf->ftype = IMB_FTYPE_JPG;
2947     ibuf->foptions.quality = quality;
2948   }
2949 }
2950 
BKE_imbuf_write(ImBuf * ibuf,const char * name,const ImageFormatData * imf)2951 int BKE_imbuf_write(ImBuf *ibuf, const char *name, const ImageFormatData *imf)
2952 {
2953   int ok;
2954 
2955   BKE_imbuf_write_prepare(ibuf, imf);
2956 
2957   BLI_make_existing_file(name);
2958 
2959   ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
2960   if (ok == 0) {
2961     perror(name);
2962   }
2963 
2964   return ok;
2965 }
2966 
2967 /* same as BKE_imbuf_write() but crappy workaround not to permanently modify
2968  * _some_, values in the imbuf */
BKE_imbuf_write_as(ImBuf * ibuf,const char * name,ImageFormatData * imf,const bool save_copy)2969 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf, const bool save_copy)
2970 {
2971   ImBuf ibuf_back = *ibuf;
2972   int ok;
2973 
2974   /* all data is rgba anyway,
2975    * this just controls how to save for some formats */
2976   ibuf->planes = imf->planes;
2977 
2978   ok = BKE_imbuf_write(ibuf, name, imf);
2979 
2980   if (save_copy) {
2981     /* note that we are not restoring _all_ settings */
2982     ibuf->planes = ibuf_back.planes;
2983     ibuf->ftype = ibuf_back.ftype;
2984     ibuf->foptions = ibuf_back.foptions;
2985   }
2986 
2987   return ok;
2988 }
2989 
BKE_imbuf_write_stamp(Scene * scene,struct RenderResult * rr,ImBuf * ibuf,const char * name,const struct ImageFormatData * imf)2990 int BKE_imbuf_write_stamp(Scene *scene,
2991                           struct RenderResult *rr,
2992                           ImBuf *ibuf,
2993                           const char *name,
2994                           const struct ImageFormatData *imf)
2995 {
2996   if (scene && scene->r.stamp & R_STAMP_ALL) {
2997     BKE_imbuf_stamp_info(rr, ibuf);
2998   }
2999 
3000   return BKE_imbuf_write(ibuf, name, imf);
3001 }
3002 
do_makepicstring(char * string,const char * base,const char * relbase,int frame,const char imtype,const ImageFormatData * im_format,const bool use_ext,const bool use_frames,const char * suffix)3003 static void do_makepicstring(char *string,
3004                              const char *base,
3005                              const char *relbase,
3006                              int frame,
3007                              const char imtype,
3008                              const ImageFormatData *im_format,
3009                              const bool use_ext,
3010                              const bool use_frames,
3011                              const char *suffix)
3012 {
3013   if (string == NULL) {
3014     return;
3015   }
3016   BLI_strncpy(string, base, FILE_MAX - 10); /* weak assumption */
3017   BLI_path_abs(string, relbase);
3018 
3019   if (use_frames) {
3020     BLI_path_frame(string, frame, 4);
3021   }
3022 
3023   if (suffix) {
3024     BLI_path_suffix(string, FILE_MAX, suffix, "");
3025   }
3026 
3027   if (use_ext) {
3028     do_add_image_extension(string, imtype, im_format);
3029   }
3030 }
3031 
BKE_image_path_from_imformat(char * string,const char * base,const char * relbase,int frame,const ImageFormatData * im_format,const bool use_ext,const bool use_frames,const char * suffix)3032 void BKE_image_path_from_imformat(char *string,
3033                                   const char *base,
3034                                   const char *relbase,
3035                                   int frame,
3036                                   const ImageFormatData *im_format,
3037                                   const bool use_ext,
3038                                   const bool use_frames,
3039                                   const char *suffix)
3040 {
3041   do_makepicstring(
3042       string, base, relbase, frame, im_format->imtype, im_format, use_ext, use_frames, suffix);
3043 }
3044 
BKE_image_path_from_imtype(char * string,const char * base,const char * relbase,int frame,const char imtype,const bool use_ext,const bool use_frames,const char * suffix)3045 void BKE_image_path_from_imtype(char *string,
3046                                 const char *base,
3047                                 const char *relbase,
3048                                 int frame,
3049                                 const char imtype,
3050                                 const bool use_ext,
3051                                 const bool use_frames,
3052                                 const char *suffix)
3053 {
3054   do_makepicstring(string, base, relbase, frame, imtype, NULL, use_ext, use_frames, suffix);
3055 }
3056 
openanim_noload(const char * name,int flags,int streamindex,char colorspace[IMA_MAX_SPACE])3057 struct anim *openanim_noload(const char *name,
3058                              int flags,
3059                              int streamindex,
3060                              char colorspace[IMA_MAX_SPACE])
3061 {
3062   struct anim *anim;
3063 
3064   anim = IMB_open_anim(name, flags, streamindex, colorspace);
3065   return anim;
3066 }
3067 
3068 /* used by sequencer too */
openanim(const char * name,int flags,int streamindex,char colorspace[IMA_MAX_SPACE])3069 struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
3070 {
3071   struct anim *anim;
3072   struct ImBuf *ibuf;
3073 
3074   anim = IMB_open_anim(name, flags, streamindex, colorspace);
3075   if (anim == NULL) {
3076     return NULL;
3077   }
3078 
3079   ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
3080   if (ibuf == NULL) {
3081     if (BLI_exists(name)) {
3082       printf("not an anim: %s\n", name);
3083     }
3084     else {
3085       printf("anim file doesn't exist: %s\n", name);
3086     }
3087     IMB_free_anim(anim);
3088     return NULL;
3089   }
3090   IMB_freeImBuf(ibuf);
3091 
3092   return anim;
3093 }
3094 
3095 /* ************************* New Image API *************** */
3096 
3097 /* Notes about Image storage
3098  * - packedfile
3099  *   -> written in .blend
3100  * - filename
3101  *   -> written in .blend
3102  * - movie
3103  *   -> comes from packedfile or filename
3104  * - renderresult
3105  *   -> comes from packedfile or filename
3106  * - listbase
3107  *   -> ibufs from exrhandle
3108  * - flipbook array
3109  *   -> ibufs come from movie, temporary renderresult or sequence
3110  * - ibuf
3111  *   -> comes from packedfile or filename or generated
3112  */
3113 
3114 /* forces existence of 1 Image for renderout or nodes, returns Image */
3115 /* name is only for default, when making new one */
BKE_image_ensure_viewer(Main * bmain,int type,const char * name)3116 Image *BKE_image_ensure_viewer(Main *bmain, int type, const char *name)
3117 {
3118   Image *ima;
3119 
3120   for (ima = bmain->images.first; ima; ima = ima->id.next) {
3121     if (ima->source == IMA_SRC_VIEWER) {
3122       if (ima->type == type) {
3123         break;
3124       }
3125     }
3126   }
3127 
3128   if (ima == NULL) {
3129     ima = image_alloc(bmain, name, IMA_SRC_VIEWER, type);
3130   }
3131 
3132   /* happens on reload, imagewindow cannot be image user when hidden*/
3133   if (ima->id.us == 0) {
3134     id_us_ensure_real(&ima->id);
3135   }
3136 
3137   return ima;
3138 }
3139 
image_viewer_create_views(const RenderData * rd,Image * ima)3140 static void image_viewer_create_views(const RenderData *rd, Image *ima)
3141 {
3142   if ((rd->scemode & R_MULTIVIEW) == 0) {
3143     image_add_view(ima, "", "");
3144   }
3145   else {
3146     SceneRenderView *srv;
3147     for (srv = rd->views.first; srv; srv = srv->next) {
3148       if (BKE_scene_multiview_is_render_view_active(rd, srv) == false) {
3149         continue;
3150       }
3151       image_add_view(ima, srv->name, "");
3152     }
3153   }
3154 }
3155 
3156 /* Reset the image cache and views when the Viewer Nodes views don't match the scene views */
BKE_image_ensure_viewer_views(const RenderData * rd,Image * ima,ImageUser * iuser)3157 void BKE_image_ensure_viewer_views(const RenderData *rd, Image *ima, ImageUser *iuser)
3158 {
3159   bool do_reset;
3160   const bool is_multiview = (rd->scemode & R_MULTIVIEW) != 0;
3161 
3162   BLI_thread_lock(LOCK_DRAW_IMAGE);
3163 
3164   if (!BKE_scene_multiview_is_stereo3d(rd)) {
3165     iuser->flag &= ~IMA_SHOW_STEREO;
3166   }
3167 
3168   /* see if all scene render views are in the image view list */
3169   do_reset = (BKE_scene_multiview_num_views_get(rd) != BLI_listbase_count(&ima->views));
3170 
3171   /* multiview also needs to be sure all the views are synced */
3172   if (is_multiview && !do_reset) {
3173     SceneRenderView *srv;
3174     ImageView *iv;
3175 
3176     for (iv = ima->views.first; iv; iv = iv->next) {
3177       srv = BLI_findstring(&rd->views, iv->name, offsetof(SceneRenderView, name));
3178       if ((srv == NULL) || (BKE_scene_multiview_is_render_view_active(rd, srv) == false)) {
3179         do_reset = true;
3180         break;
3181       }
3182     }
3183   }
3184 
3185   if (do_reset) {
3186     BLI_mutex_lock(image_mutex);
3187 
3188     image_free_cached_frames(ima);
3189     BKE_image_free_views(ima);
3190 
3191     /* add new views */
3192     image_viewer_create_views(rd, ima);
3193 
3194     BLI_mutex_unlock(image_mutex);
3195   }
3196 
3197   BLI_thread_unlock(LOCK_DRAW_IMAGE);
3198 }
3199 
image_walk_ntree_all_users(bNodeTree * ntree,ID * id,void * customdata,void callback (Image * ima,ID * iuser_id,ImageUser * iuser,void * customdata))3200 static void image_walk_ntree_all_users(
3201     bNodeTree *ntree,
3202     ID *id,
3203     void *customdata,
3204     void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
3205 {
3206   switch (ntree->type) {
3207     case NTREE_SHADER:
3208       LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
3209         if (node->id) {
3210           if (node->type == SH_NODE_TEX_IMAGE) {
3211             NodeTexImage *tex = node->storage;
3212             Image *ima = (Image *)node->id;
3213             callback(ima, id, &tex->iuser, customdata);
3214           }
3215           if (node->type == SH_NODE_TEX_ENVIRONMENT) {
3216             NodeTexImage *tex = node->storage;
3217             Image *ima = (Image *)node->id;
3218             callback(ima, id, &tex->iuser, customdata);
3219           }
3220         }
3221       }
3222       break;
3223     case NTREE_TEXTURE:
3224       LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
3225         if (node->id && node->type == TEX_NODE_IMAGE) {
3226           Image *ima = (Image *)node->id;
3227           ImageUser *iuser = node->storage;
3228           callback(ima, id, iuser, customdata);
3229         }
3230       }
3231       break;
3232     case NTREE_COMPOSIT:
3233       LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
3234         if (node->id && node->type == CMP_NODE_IMAGE) {
3235           Image *ima = (Image *)node->id;
3236           ImageUser *iuser = node->storage;
3237           callback(ima, id, iuser, customdata);
3238         }
3239       }
3240       break;
3241   }
3242 }
3243 
image_walk_id_all_users(ID * id,bool skip_nested_nodes,void * customdata,void callback (Image * ima,ID * iuser_id,ImageUser * iuser,void * customdata))3244 static void image_walk_id_all_users(
3245     ID *id,
3246     bool skip_nested_nodes,
3247     void *customdata,
3248     void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
3249 {
3250   switch (GS(id->name)) {
3251     case ID_OB: {
3252       Object *ob = (Object *)id;
3253       if (ob->empty_drawtype == OB_EMPTY_IMAGE && ob->data) {
3254         callback(ob->data, &ob->id, ob->iuser, customdata);
3255       }
3256       break;
3257     }
3258     case ID_MA: {
3259       Material *ma = (Material *)id;
3260       if (ma->nodetree && ma->use_nodes && !skip_nested_nodes) {
3261         image_walk_ntree_all_users(ma->nodetree, &ma->id, customdata, callback);
3262       }
3263       break;
3264     }
3265     case ID_LA: {
3266       Light *light = (Light *)id;
3267       if (light->nodetree && light->use_nodes && !skip_nested_nodes) {
3268         image_walk_ntree_all_users(light->nodetree, &light->id, customdata, callback);
3269       }
3270       break;
3271     }
3272     case ID_WO: {
3273       World *world = (World *)id;
3274       if (world->nodetree && world->use_nodes && !skip_nested_nodes) {
3275         image_walk_ntree_all_users(world->nodetree, &world->id, customdata, callback);
3276       }
3277       break;
3278     }
3279     case ID_TE: {
3280       Tex *tex = (Tex *)id;
3281       if (tex->type == TEX_IMAGE && tex->ima) {
3282         callback(tex->ima, &tex->id, &tex->iuser, customdata);
3283       }
3284       if (tex->nodetree && tex->use_nodes && !skip_nested_nodes) {
3285         image_walk_ntree_all_users(tex->nodetree, &tex->id, customdata, callback);
3286       }
3287       break;
3288     }
3289     case ID_NT: {
3290       bNodeTree *ntree = (bNodeTree *)id;
3291       image_walk_ntree_all_users(ntree, &ntree->id, customdata, callback);
3292       break;
3293     }
3294     case ID_CA: {
3295       Camera *cam = (Camera *)id;
3296       LISTBASE_FOREACH (CameraBGImage *, bgpic, &cam->bg_images) {
3297         callback(bgpic->ima, NULL, &bgpic->iuser, customdata);
3298       }
3299       break;
3300     }
3301     case ID_WM: {
3302       wmWindowManager *wm = (wmWindowManager *)id;
3303       LISTBASE_FOREACH (wmWindow *, win, &wm->windows) {
3304         const bScreen *screen = BKE_workspace_active_screen_get(win->workspace_hook);
3305 
3306         LISTBASE_FOREACH (ScrArea *, area, &screen->areabase) {
3307           if (area->spacetype == SPACE_IMAGE) {
3308             SpaceImage *sima = area->spacedata.first;
3309             callback(sima->image, NULL, &sima->iuser, customdata);
3310           }
3311         }
3312       }
3313       break;
3314     }
3315     case ID_SCE: {
3316       Scene *scene = (Scene *)id;
3317       if (scene->nodetree && scene->use_nodes && !skip_nested_nodes) {
3318         image_walk_ntree_all_users(scene->nodetree, &scene->id, customdata, callback);
3319       }
3320       break;
3321     }
3322     case ID_SIM: {
3323       Simulation *simulation = (Simulation *)id;
3324       image_walk_ntree_all_users(simulation->nodetree, &simulation->id, customdata, callback);
3325       break;
3326     }
3327     default:
3328       break;
3329   }
3330 }
3331 
BKE_image_walk_all_users(const Main * mainp,void * customdata,void callback (Image * ima,ID * iuser_id,ImageUser * iuser,void * customdata))3332 void BKE_image_walk_all_users(
3333     const Main *mainp,
3334     void *customdata,
3335     void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
3336 {
3337   for (Scene *scene = mainp->scenes.first; scene; scene = scene->id.next) {
3338     image_walk_id_all_users(&scene->id, false, customdata, callback);
3339   }
3340 
3341   for (Object *ob = mainp->objects.first; ob; ob = ob->id.next) {
3342     image_walk_id_all_users(&ob->id, false, customdata, callback);
3343   }
3344 
3345   for (bNodeTree *ntree = mainp->nodetrees.first; ntree; ntree = ntree->id.next) {
3346     image_walk_id_all_users(&ntree->id, false, customdata, callback);
3347   }
3348 
3349   for (Material *ma = mainp->materials.first; ma; ma = ma->id.next) {
3350     image_walk_id_all_users(&ma->id, false, customdata, callback);
3351   }
3352 
3353   for (Light *light = mainp->materials.first; light; light = light->id.next) {
3354     image_walk_id_all_users(&light->id, false, customdata, callback);
3355   }
3356 
3357   for (World *world = mainp->materials.first; world; world = world->id.next) {
3358     image_walk_id_all_users(&world->id, false, customdata, callback);
3359   }
3360 
3361   for (Tex *tex = mainp->textures.first; tex; tex = tex->id.next) {
3362     image_walk_id_all_users(&tex->id, false, customdata, callback);
3363   }
3364 
3365   for (Camera *cam = mainp->cameras.first; cam; cam = cam->id.next) {
3366     image_walk_id_all_users(&cam->id, false, customdata, callback);
3367   }
3368 
3369   for (wmWindowManager *wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
3370     image_walk_id_all_users(&wm->id, false, customdata, callback);
3371   }
3372 }
3373 
image_tag_frame_recalc(Image * ima,ID * iuser_id,ImageUser * iuser,void * customdata)3374 static void image_tag_frame_recalc(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata)
3375 {
3376   Image *changed_image = customdata;
3377 
3378   if (ima == changed_image && BKE_image_is_animated(ima)) {
3379     iuser->flag |= IMA_NEED_FRAME_RECALC;
3380     iuser->ok = 1;
3381 
3382     if (iuser_id) {
3383       /* Must copy image user changes to CoW datablock. */
3384       DEG_id_tag_update(iuser_id, ID_RECALC_COPY_ON_WRITE);
3385     }
3386   }
3387 }
3388 
image_tag_reload(Image * ima,ID * iuser_id,ImageUser * iuser,void * customdata)3389 static void image_tag_reload(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata)
3390 {
3391   Image *changed_image = customdata;
3392 
3393   if (ima == changed_image) {
3394     iuser->ok = 1;
3395     if (iuser->scene) {
3396       image_update_views_format(ima, iuser);
3397     }
3398     if (iuser_id) {
3399       /* Must copy image user changes to CoW datablock. */
3400       DEG_id_tag_update(iuser_id, ID_RECALC_COPY_ON_WRITE);
3401     }
3402   }
3403 }
3404 
BKE_imageuser_default(ImageUser * iuser)3405 void BKE_imageuser_default(ImageUser *iuser)
3406 {
3407   memset(iuser, 0, sizeof(ImageUser));
3408   iuser->ok = 1;
3409   iuser->frames = 100;
3410   iuser->sfra = 1;
3411 }
3412 
BKE_image_init_imageuser(Image * ima,ImageUser * iuser)3413 void BKE_image_init_imageuser(Image *ima, ImageUser *iuser)
3414 {
3415   RenderResult *rr = ima->rr;
3416 
3417   iuser->multi_index = 0;
3418   iuser->layer = iuser->pass = iuser->view = 0;
3419 
3420   if (rr) {
3421     BKE_image_multilayer_index(rr, iuser);
3422   }
3423 }
3424 
image_free_tile(Image * ima,ImageTile * tile)3425 static void image_free_tile(Image *ima, ImageTile *tile)
3426 {
3427   for (int i = 0; i < TEXTARGET_COUNT; i++) {
3428     /* Only two textures depends on all tiles, so if this is a secondary tile we can keep the other
3429      * two. */
3430     if (tile != ima->tiles.first && !(ELEM(i, TEXTARGET_2D_ARRAY, TEXTARGET_TILE_MAPPING))) {
3431       continue;
3432     }
3433 
3434     for (int eye = 0; eye < 2; eye++) {
3435       if (ima->gputexture[i][eye] != NULL) {
3436         GPU_texture_free(ima->gputexture[i][eye]);
3437         ima->gputexture[i][eye] = NULL;
3438       }
3439     }
3440   }
3441 
3442   if (BKE_image_is_multiview(ima)) {
3443     const int totviews = BLI_listbase_count(&ima->views);
3444     for (int i = 0; i < totviews; i++) {
3445       image_remove_ibuf(ima, i, tile->tile_number);
3446     }
3447   }
3448   else {
3449     image_remove_ibuf(ima, 0, tile->tile_number);
3450   }
3451 }
3452 
BKE_image_signal(Main * bmain,Image * ima,ImageUser * iuser,int signal)3453 void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal)
3454 {
3455   if (ima == NULL) {
3456     return;
3457   }
3458 
3459   BLI_mutex_lock(image_mutex);
3460 
3461   switch (signal) {
3462     case IMA_SIGNAL_FREE:
3463       BKE_image_free_buffers(ima);
3464 
3465       if (iuser) {
3466         iuser->ok = 1;
3467         if (iuser->scene) {
3468           image_update_views_format(ima, iuser);
3469         }
3470       }
3471       break;
3472     case IMA_SIGNAL_SRC_CHANGE:
3473       if (ima->type == IMA_TYPE_UV_TEST) {
3474         if (ima->source != IMA_SRC_GENERATED) {
3475           ima->type = IMA_TYPE_IMAGE;
3476         }
3477       }
3478 
3479       if (ima->source == IMA_SRC_GENERATED) {
3480         if (ima->gen_x == 0 || ima->gen_y == 0) {
3481           ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, IMA_NO_INDEX, 0);
3482           if (ibuf) {
3483             ima->gen_x = ibuf->x;
3484             ima->gen_y = ibuf->y;
3485             IMB_freeImBuf(ibuf);
3486           }
3487         }
3488 
3489         /* Changing source type to generated will likely change file format
3490          * used by generated image buffer. Saving different file format to
3491          * the old name might confuse other applications.
3492          *
3493          * Here we ensure original image path wouldn't be used when saving
3494          * generated image.
3495          */
3496         ima->filepath[0] = '\0';
3497       }
3498 
3499       if (ima->source != IMA_SRC_TILED) {
3500         /* Free all but the first tile. */
3501         ImageTile *base_tile = BKE_image_get_tile(ima, 0);
3502         BLI_assert(base_tile == ima->tiles.first);
3503         for (ImageTile *tile = base_tile->next, *tile_next; tile; tile = tile_next) {
3504           tile_next = tile->next;
3505           image_free_tile(ima, tile);
3506           MEM_freeN(tile);
3507         }
3508         base_tile->next = NULL;
3509         ima->tiles.last = base_tile;
3510       }
3511 
3512       /* image buffers for non-sequence multilayer will share buffers with RenderResult,
3513        * however sequence multilayer will own buffers. Such logic makes switching from
3514        * single multilayer file to sequence completely unstable
3515        * since changes in nodes seems this workaround isn't needed anymore, all sockets
3516        * are nicely detecting anyway, but freeing buffers always here makes multilayer
3517        * sequences behave stable
3518        */
3519       BKE_image_free_buffers(ima);
3520 
3521       LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
3522         tile->ok = 1;
3523       }
3524 
3525       if (iuser) {
3526         image_tag_frame_recalc(ima, NULL, iuser, ima);
3527       }
3528       BKE_image_walk_all_users(bmain, ima, image_tag_frame_recalc);
3529 
3530       break;
3531 
3532     case IMA_SIGNAL_RELOAD:
3533       /* try to repack file */
3534       if (BKE_image_has_packedfile(ima)) {
3535         const int totfiles = image_num_files(ima);
3536 
3537         if (totfiles != BLI_listbase_count_at_most(&ima->packedfiles, totfiles + 1)) {
3538           /* in case there are new available files to be loaded */
3539           image_free_packedfiles(ima);
3540           BKE_image_packfiles(NULL, ima, ID_BLEND_PATH(bmain, &ima->id));
3541         }
3542         else {
3543           ImagePackedFile *imapf;
3544           for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
3545             PackedFile *pf;
3546             pf = BKE_packedfile_new(NULL, imapf->filepath, ID_BLEND_PATH(bmain, &ima->id));
3547             if (pf) {
3548               BKE_packedfile_free(imapf->packedfile);
3549               imapf->packedfile = pf;
3550             }
3551             else {
3552               printf("ERROR: Image \"%s\" not available. Keeping packed image\n", imapf->filepath);
3553             }
3554           }
3555         }
3556 
3557         if (BKE_image_has_packedfile(ima)) {
3558           BKE_image_free_buffers(ima);
3559         }
3560       }
3561       else {
3562         BKE_image_free_buffers(ima);
3563       }
3564 
3565       if (iuser) {
3566         image_tag_reload(ima, NULL, iuser, ima);
3567       }
3568       BKE_image_walk_all_users(bmain, ima, image_tag_reload);
3569       break;
3570     case IMA_SIGNAL_USER_NEW_IMAGE:
3571       if (iuser) {
3572         iuser->ok = 1;
3573         if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
3574           if (ima->type == IMA_TYPE_MULTILAYER) {
3575             BKE_image_init_imageuser(ima, iuser);
3576           }
3577         }
3578       }
3579       break;
3580     case IMA_SIGNAL_COLORMANAGE:
3581       BKE_image_free_buffers(ima);
3582 
3583       LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
3584         tile->ok = 1;
3585       }
3586 
3587       if (iuser) {
3588         iuser->ok = 1;
3589       }
3590 
3591       break;
3592   }
3593 
3594   BLI_mutex_unlock(image_mutex);
3595 
3596   /* don't use notifiers because they are not 100% sure to succeeded
3597    * this also makes sure all scenes are accounted for. */
3598   {
3599     Scene *scene;
3600     for (scene = bmain->scenes.first; scene; scene = scene->id.next) {
3601       if (scene->nodetree) {
3602         nodeUpdateID(scene->nodetree, &ima->id);
3603       }
3604     }
3605   }
3606 }
3607 
3608 /* return renderpass for a given pass index and active view */
3609 /* fallback to available if there are missing passes for active view */
image_render_pass_get(RenderLayer * rl,const int pass,const int view,int * r_passindex)3610 static RenderPass *image_render_pass_get(RenderLayer *rl,
3611                                          const int pass,
3612                                          const int view,
3613                                          int *r_passindex)
3614 {
3615   RenderPass *rpass_ret = NULL;
3616   RenderPass *rpass;
3617 
3618   int rp_index = 0;
3619   const char *rp_name = "";
3620 
3621   for (rpass = rl->passes.first; rpass; rpass = rpass->next, rp_index++) {
3622     if (rp_index == pass) {
3623       rpass_ret = rpass;
3624       if (view == 0) {
3625         /* no multiview or left eye */
3626         break;
3627       }
3628 
3629       rp_name = rpass->name;
3630     }
3631     /* multiview */
3632     else if (rp_name[0] && STREQ(rpass->name, rp_name) && (rpass->view_id == view)) {
3633       rpass_ret = rpass;
3634       break;
3635     }
3636   }
3637 
3638   /* fallback to the first pass in the layer */
3639   if (rpass_ret == NULL) {
3640     rp_index = 0;
3641     rpass_ret = rl->passes.first;
3642   }
3643 
3644   if (r_passindex) {
3645     *r_passindex = (rpass == rpass_ret ? rp_index : pass);
3646   }
3647 
3648   return rpass_ret;
3649 }
3650 
BKE_image_get_tile_label(Image * ima,ImageTile * tile,char * label,int len_label)3651 void BKE_image_get_tile_label(Image *ima, ImageTile *tile, char *label, int len_label)
3652 {
3653   label[0] = '\0';
3654   if (ima == NULL || tile == NULL) {
3655     return;
3656   }
3657 
3658   if (tile->label[0]) {
3659     BLI_strncpy(label, tile->label, len_label);
3660   }
3661   else {
3662     BLI_snprintf(label, len_label, "%d", tile->tile_number);
3663   }
3664 }
3665 
BKE_image_add_tile(struct Image * ima,int tile_number,const char * label)3666 ImageTile *BKE_image_add_tile(struct Image *ima, int tile_number, const char *label)
3667 {
3668   if (ima->source != IMA_SRC_TILED) {
3669     return NULL;
3670   }
3671 
3672   if (tile_number < 1001 || tile_number > IMA_UDIM_MAX) {
3673     return NULL;
3674   }
3675 
3676   /* Search the first tile that has a higher number.
3677    * We then insert before that to keep the list sorted. */
3678   ImageTile *next_tile;
3679   for (next_tile = ima->tiles.first; next_tile; next_tile = next_tile->next) {
3680     if (next_tile->tile_number == tile_number) {
3681       /* Tile already exists. */
3682       return NULL;
3683     }
3684     if (next_tile->tile_number > tile_number) {
3685       break;
3686     }
3687   }
3688 
3689   ImageTile *tile = MEM_callocN(sizeof(ImageTile), "image new tile");
3690   tile->ok = IMA_OK;
3691   tile->tile_number = tile_number;
3692 
3693   if (next_tile) {
3694     BLI_insertlinkbefore(&ima->tiles, next_tile, tile);
3695   }
3696   else {
3697     BLI_addtail(&ima->tiles, tile);
3698   }
3699 
3700   if (label) {
3701     BLI_strncpy(tile->label, label, sizeof(tile->label));
3702   }
3703 
3704   for (int eye = 0; eye < 2; eye++) {
3705     /* Reallocate GPU tile array. */
3706     if (ima->gputexture[TEXTARGET_2D_ARRAY][eye] != NULL) {
3707       GPU_texture_free(ima->gputexture[TEXTARGET_2D_ARRAY][eye]);
3708       ima->gputexture[TEXTARGET_2D_ARRAY][eye] = NULL;
3709     }
3710     if (ima->gputexture[TEXTARGET_TILE_MAPPING][eye] != NULL) {
3711       GPU_texture_free(ima->gputexture[TEXTARGET_TILE_MAPPING][eye]);
3712       ima->gputexture[TEXTARGET_TILE_MAPPING][eye] = NULL;
3713     }
3714   }
3715 
3716   return tile;
3717 }
3718 
BKE_image_remove_tile(struct Image * ima,ImageTile * tile)3719 bool BKE_image_remove_tile(struct Image *ima, ImageTile *tile)
3720 {
3721   if (ima == NULL || tile == NULL || ima->source != IMA_SRC_TILED) {
3722     return false;
3723   }
3724 
3725   if (tile == ima->tiles.first) {
3726     /* Can't remove first tile. */
3727     return false;
3728   }
3729 
3730   image_free_tile(ima, tile);
3731   BLI_remlink(&ima->tiles, tile);
3732   MEM_freeN(tile);
3733 
3734   return true;
3735 }
3736 
BKE_image_fill_tile(struct Image * ima,ImageTile * tile,int width,int height,const float color[4],int gen_type,int planes,bool is_float)3737 bool BKE_image_fill_tile(struct Image *ima,
3738                          ImageTile *tile,
3739                          int width,
3740                          int height,
3741                          const float color[4],
3742                          int gen_type,
3743                          int planes,
3744                          bool is_float)
3745 {
3746   if (ima == NULL || tile == NULL || ima->source != IMA_SRC_TILED) {
3747     return false;
3748   }
3749 
3750   image_free_tile(ima, tile);
3751 
3752   ImBuf *tile_ibuf = add_ibuf_size(
3753       width, height, ima->filepath, planes, is_float, gen_type, color, &ima->colorspace_settings);
3754 
3755   if (tile_ibuf != NULL) {
3756     image_assign_ibuf(ima, tile_ibuf, 0, tile->tile_number);
3757     BKE_image_release_ibuf(ima, tile_ibuf, NULL);
3758     tile->ok = IMA_OK;
3759     return true;
3760   }
3761   return false;
3762 }
3763 
3764 /* if layer or pass changes, we need an index for the imbufs list */
3765 /* note it is called for rendered results, but it doesn't use the index! */
3766 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
BKE_image_multilayer_index(RenderResult * rr,ImageUser * iuser)3767 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
3768 {
3769   RenderLayer *rl;
3770   RenderPass *rpass = NULL;
3771 
3772   if (rr == NULL) {
3773     return NULL;
3774   }
3775 
3776   if (iuser) {
3777     short index = 0, rv_index, rl_index = 0;
3778     bool is_stereo = (iuser->flag & IMA_SHOW_STEREO) && RE_RenderResult_is_stereo(rr);
3779 
3780     rv_index = is_stereo ? iuser->multiview_eye : iuser->view;
3781     if (RE_HasCombinedLayer(rr)) {
3782       rl_index += 1;
3783     }
3784 
3785     for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
3786       if (iuser->layer == rl_index) {
3787         int rp_index;
3788         rpass = image_render_pass_get(rl, iuser->pass, rv_index, &rp_index);
3789         iuser->multi_index = index + rp_index;
3790         break;
3791       }
3792 
3793       index += BLI_listbase_count(&rl->passes);
3794     }
3795   }
3796 
3797   return rpass;
3798 }
3799 
BKE_image_multiview_index(Image * ima,ImageUser * iuser)3800 void BKE_image_multiview_index(Image *ima, ImageUser *iuser)
3801 {
3802   if (iuser) {
3803     bool is_stereo = BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO);
3804     if (is_stereo) {
3805       iuser->multi_index = iuser->multiview_eye;
3806     }
3807     else {
3808       if ((iuser->view < 0) ||
3809           (iuser->view >= BLI_listbase_count_at_most(&ima->views, iuser->view + 1))) {
3810         iuser->multi_index = iuser->view = 0;
3811       }
3812       else {
3813         iuser->multi_index = iuser->view;
3814       }
3815     }
3816   }
3817 }
3818 
3819 /* if layer or pass changes, we need an index for the imbufs list */
3820 /* note it is called for rendered results, but it doesn't use the index! */
3821 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
BKE_image_is_multilayer(Image * ima)3822 bool BKE_image_is_multilayer(Image *ima)
3823 {
3824   if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
3825     if (ima->type == IMA_TYPE_MULTILAYER) {
3826       return true;
3827     }
3828   }
3829   else if (ima->source == IMA_SRC_VIEWER) {
3830     if (ima->type == IMA_TYPE_R_RESULT) {
3831       return true;
3832     }
3833   }
3834   return false;
3835 }
3836 
BKE_image_is_multiview(Image * ima)3837 bool BKE_image_is_multiview(Image *ima)
3838 {
3839   ImageView *view = ima->views.first;
3840   return (view && (view->next || view->name[0]));
3841 }
3842 
BKE_image_is_stereo(Image * ima)3843 bool BKE_image_is_stereo(Image *ima)
3844 {
3845   return BKE_image_is_multiview(ima) &&
3846          (BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)) &&
3847           BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name)));
3848 }
3849 
image_init_multilayer_multiview(Image * ima,RenderResult * rr)3850 static void image_init_multilayer_multiview(Image *ima, RenderResult *rr)
3851 {
3852   /* update image views from render views, but only if they actually changed,
3853    * to avoid invalid memory access during render. ideally these should always
3854    * be acquired with a mutex along with the render result, but there are still
3855    * some places with just an image pointer that need to access views */
3856   if (rr && BLI_listbase_count(&ima->views) == BLI_listbase_count(&rr->views)) {
3857     ImageView *iv = ima->views.first;
3858     RenderView *rv = rr->views.first;
3859     bool modified = false;
3860     for (; rv; rv = rv->next, iv = iv->next) {
3861       modified |= !STREQ(rv->name, iv->name);
3862     }
3863     if (!modified) {
3864       return;
3865     }
3866   }
3867 
3868   BKE_image_free_views(ima);
3869 
3870   if (rr) {
3871     LISTBASE_FOREACH (RenderView *, rv, &rr->views) {
3872       ImageView *iv = MEM_callocN(sizeof(ImageView), "Viewer Image View");
3873       STRNCPY(iv->name, rv->name);
3874       BLI_addtail(&ima->views, iv);
3875     }
3876   }
3877 }
3878 
BKE_image_acquire_renderresult(Scene * scene,Image * ima)3879 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
3880 {
3881   RenderResult *rr = NULL;
3882   if (ima->rr) {
3883     rr = ima->rr;
3884   }
3885   else if (ima->type == IMA_TYPE_R_RESULT) {
3886     if (ima->render_slot == ima->last_render_slot) {
3887       rr = RE_AcquireResultRead(RE_GetSceneRender(scene));
3888     }
3889     else {
3890       rr = BKE_image_get_renderslot(ima, ima->render_slot)->render;
3891     }
3892 
3893     /* set proper views */
3894     image_init_multilayer_multiview(ima, rr);
3895   }
3896 
3897   return rr;
3898 }
3899 
BKE_image_release_renderresult(Scene * scene,Image * ima)3900 void BKE_image_release_renderresult(Scene *scene, Image *ima)
3901 {
3902   if (ima->rr) {
3903     /* pass */
3904   }
3905   else if (ima->type == IMA_TYPE_R_RESULT) {
3906     if (ima->render_slot == ima->last_render_slot) {
3907       RE_ReleaseResult(RE_GetSceneRender(scene));
3908     }
3909   }
3910 }
3911 
BKE_image_is_openexr(struct Image * ima)3912 bool BKE_image_is_openexr(struct Image *ima)
3913 {
3914 #ifdef WITH_OPENEXR
3915   if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
3916     return BLI_path_extension_check(ima->filepath, ".exr");
3917   }
3918 #else
3919   UNUSED_VARS(ima);
3920 #endif
3921   return false;
3922 }
3923 
BKE_image_backup_render(Scene * scene,Image * ima,bool free_current_slot)3924 void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
3925 {
3926   /* called right before rendering, ima->renderslots contains render
3927    * result pointers for everything but the current render */
3928   Render *re = RE_GetSceneRender(scene);
3929 
3930   /* Ensure we always have a valid render slot. */
3931   if (!ima->renderslots.first) {
3932     BKE_image_add_renderslot(ima, NULL);
3933     ima->render_slot = 0;
3934     ima->last_render_slot = 0;
3935   }
3936   else if (ima->render_slot >= BLI_listbase_count(&ima->renderslots)) {
3937     ima->render_slot = 0;
3938     ima->last_render_slot = 0;
3939   }
3940 
3941   RenderSlot *last_slot = BKE_image_get_renderslot(ima, ima->last_render_slot);
3942   RenderSlot *cur_slot = BKE_image_get_renderslot(ima, ima->render_slot);
3943 
3944   if (last_slot && ima->render_slot != ima->last_render_slot) {
3945     last_slot->render = NULL;
3946     RE_SwapResult(re, &last_slot->render);
3947 
3948     if (cur_slot->render) {
3949       if (free_current_slot) {
3950         BKE_image_clear_renderslot(ima, NULL, ima->render_slot);
3951       }
3952       else {
3953         RE_SwapResult(re, &cur_slot->render);
3954       }
3955     }
3956   }
3957 
3958   ima->last_render_slot = ima->render_slot;
3959 }
3960 
3961 /**************************** multiview load openexr *********************************/
3962 
image_add_view(Image * ima,const char * viewname,const char * filepath)3963 static void image_add_view(Image *ima, const char *viewname, const char *filepath)
3964 {
3965   ImageView *iv;
3966 
3967   iv = MEM_mallocN(sizeof(ImageView), "Viewer Image View");
3968   STRNCPY(iv->name, viewname);
3969   STRNCPY(iv->filepath, filepath);
3970 
3971   /* For stereo drawing we need to ensure:
3972    * STEREO_LEFT_NAME  == STEREO_LEFT_ID and
3973    * STEREO_RIGHT_NAME == STEREO_RIGHT_ID */
3974 
3975   if (STREQ(viewname, STEREO_LEFT_NAME)) {
3976     BLI_addhead(&ima->views, iv);
3977   }
3978   else if (STREQ(viewname, STEREO_RIGHT_NAME)) {
3979     ImageView *left_iv = BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name));
3980 
3981     if (left_iv == NULL) {
3982       BLI_addhead(&ima->views, iv);
3983     }
3984     else {
3985       BLI_insertlinkafter(&ima->views, left_iv, iv);
3986     }
3987   }
3988   else {
3989     BLI_addtail(&ima->views, iv);
3990   }
3991 }
3992 
3993 /* after imbuf load, openexr type can return with a exrhandle open */
3994 /* in that case we have to build a render-result */
3995 #ifdef WITH_OPENEXR
image_create_multilayer(Image * ima,ImBuf * ibuf,int framenr)3996 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
3997 {
3998   const char *colorspace = ima->colorspace_settings.name;
3999   bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL);
4000 
4001   /* only load rr once for multiview */
4002   if (!ima->rr) {
4003     ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
4004   }
4005 
4006   IMB_exr_close(ibuf->userdata);
4007 
4008   ibuf->userdata = NULL;
4009   if (ima->rr != NULL) {
4010     ima->rr->framenr = framenr;
4011     BKE_stamp_info_from_imbuf(ima->rr, ibuf);
4012   }
4013 
4014   /* set proper views */
4015   image_init_multilayer_multiview(ima, ima->rr);
4016 }
4017 #endif /* WITH_OPENEXR */
4018 
4019 /* common stuff to do with images after loading */
image_init_after_load(Image * ima,ImageUser * iuser,ImBuf * UNUSED (ibuf))4020 static void image_init_after_load(Image *ima, ImageUser *iuser, ImBuf *UNUSED(ibuf))
4021 {
4022   /* Preview is NULL when it has never been used as an icon before.
4023    * Never handle previews/icons outside of main thread. */
4024   if (G.background == 0 && ima->preview == NULL && BLI_thread_is_main()) {
4025     BKE_icon_changed(BKE_icon_id_ensure(&ima->id));
4026   }
4027 
4028   /* timer */
4029   BKE_image_tag_time(ima);
4030 
4031   ImageTile *tile = BKE_image_get_tile_from_iuser(ima, iuser);
4032   /* Images should never get loaded if the corresponding tile does not exist,
4033    * but we should at least not crash if it happens due to a bug elsewhere. */
4034   BLI_assert(tile != NULL);
4035   if (tile != NULL) {
4036     tile->ok = IMA_OK_LOADED;
4037   }
4038 }
4039 
imbuf_alpha_flags_for_image(Image * ima)4040 static int imbuf_alpha_flags_for_image(Image *ima)
4041 {
4042   switch (ima->alpha_mode) {
4043     case IMA_ALPHA_STRAIGHT:
4044       return 0;
4045     case IMA_ALPHA_PREMUL:
4046       return IB_alphamode_premul;
4047     case IMA_ALPHA_CHANNEL_PACKED:
4048       return IB_alphamode_channel_packed;
4049     case IMA_ALPHA_IGNORE:
4050       return IB_alphamode_ignore;
4051   }
4052 
4053   return 0;
4054 }
4055 
4056 /* the number of files will vary according to the stereo format */
image_num_files(Image * ima)4057 static int image_num_files(Image *ima)
4058 {
4059   const bool is_multiview = BKE_image_is_multiview(ima);
4060 
4061   if (!is_multiview) {
4062     return 1;
4063   }
4064   if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
4065     return 1;
4066   }
4067   /* R_IMF_VIEWS_INDIVIDUAL */
4068 
4069   return BLI_listbase_count(&ima->views);
4070 }
4071 
load_sequence_single(Image * ima,ImageUser * iuser,int frame,const int view_id,bool * r_assign)4072 static ImBuf *load_sequence_single(
4073     Image *ima, ImageUser *iuser, int frame, const int view_id, bool *r_assign)
4074 {
4075   struct ImBuf *ibuf;
4076   char name[FILE_MAX];
4077   int flag;
4078   ImageUser iuser_t = {0};
4079 
4080   ima->lastframe = frame;
4081 
4082   if (iuser) {
4083     iuser_t = *iuser;
4084   }
4085   else {
4086     /* BKE_image_user_file_path() uses this value for file name for sequences. */
4087     iuser_t.framenr = frame;
4088     /* TODO(sergey): Do we need to initialize something else here? */
4089   }
4090 
4091   iuser_t.view = view_id;
4092   BKE_image_user_file_path(&iuser_t, ima, name);
4093 
4094   flag = IB_rect | IB_multilayer | IB_metadata;
4095   flag |= imbuf_alpha_flags_for_image(ima);
4096 
4097   /* read ibuf */
4098   ibuf = IMB_loadiffname(name, flag, ima->colorspace_settings.name);
4099 
4100 #if 0
4101   if (ibuf) {
4102     printf(AT " loaded %s\n", name);
4103   }
4104   else {
4105     printf(AT " missed %s\n", name);
4106   }
4107 #endif
4108 
4109   if (ibuf) {
4110 #ifdef WITH_OPENEXR
4111     if (ibuf->ftype == IMB_FTYPE_OPENEXR && ibuf->userdata) {
4112       /* Handle multilayer and multiview cases, don't assign ibuf here.
4113        * will be set layer in BKE_image_acquire_ibuf from ima->rr. */
4114       if (IMB_exr_has_multilayer(ibuf->userdata)) {
4115         image_create_multilayer(ima, ibuf, frame);
4116         ima->type = IMA_TYPE_MULTILAYER;
4117         IMB_freeImBuf(ibuf);
4118         ibuf = NULL;
4119       }
4120     }
4121     else {
4122       image_init_after_load(ima, iuser, ibuf);
4123       *r_assign = true;
4124     }
4125 #else
4126     image_init_after_load(ima, iuser, ibuf);
4127     *r_assign = true;
4128 #endif
4129   }
4130   else {
4131     ImageTile *tile = BKE_image_get_tile_from_iuser(ima, iuser);
4132     if (tile != NULL) {
4133       tile->ok = 0;
4134     }
4135   }
4136 
4137   return ibuf;
4138 }
4139 
image_load_sequence_file(Image * ima,ImageUser * iuser,int entry,int frame)4140 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int entry, int frame)
4141 {
4142   struct ImBuf *ibuf = NULL;
4143   const bool is_multiview = BKE_image_is_multiview(ima);
4144   const int totfiles = image_num_files(ima);
4145   bool assign = false;
4146 
4147   if (!is_multiview) {
4148     ibuf = load_sequence_single(ima, iuser, frame, 0, &assign);
4149     if (assign) {
4150       image_assign_ibuf(ima, ibuf, 0, entry);
4151     }
4152   }
4153   else {
4154     const int totviews = BLI_listbase_count(&ima->views);
4155     struct ImBuf **ibuf_arr;
4156 
4157     ibuf_arr = MEM_mallocN(sizeof(ImBuf *) * totviews, "Image Views Imbufs");
4158 
4159     for (int i = 0; i < totfiles; i++) {
4160       ibuf_arr[i] = load_sequence_single(ima, iuser, frame, i, &assign);
4161     }
4162 
4163     if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D) {
4164       IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]);
4165     }
4166 
4167     /* return the original requested ImBuf */
4168     ibuf = ibuf_arr[(iuser ? iuser->multi_index : 0)];
4169 
4170     if (assign) {
4171       for (int i = 0; i < totviews; i++) {
4172         image_assign_ibuf(ima, ibuf_arr[i], i, entry);
4173       }
4174     }
4175 
4176     /* "remove" the others (decrease their refcount) */
4177     for (int i = 0; i < totviews; i++) {
4178       if (ibuf_arr[i] != ibuf) {
4179         IMB_freeImBuf(ibuf_arr[i]);
4180       }
4181     }
4182 
4183     /* cleanup */
4184     MEM_freeN(ibuf_arr);
4185   }
4186 
4187   return ibuf;
4188 }
4189 
image_load_sequence_multilayer(Image * ima,ImageUser * iuser,int entry,int frame)4190 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int entry, int frame)
4191 {
4192   struct ImBuf *ibuf = NULL;
4193   ImageTile *tile = BKE_image_get_tile_from_iuser(ima, iuser);
4194 
4195   /* either we load from RenderResult, or we have to load a new one */
4196 
4197   /* check for new RenderResult */
4198   if (ima->rr == NULL || frame != ima->rr->framenr) {
4199     if (ima->rr) {
4200       /* Cached image buffers shares pointers with render result,
4201        * need to ensure there's no image buffers are hanging around
4202        * with dead links after freeing the render result.
4203        */
4204       image_free_cached_frames(ima);
4205       RE_FreeRenderResult(ima->rr);
4206       ima->rr = NULL;
4207     }
4208 
4209     ibuf = image_load_sequence_file(ima, iuser, entry, frame);
4210 
4211     if (ibuf) { /* actually an error */
4212       ima->type = IMA_TYPE_IMAGE;
4213       printf("error, multi is normal image\n");
4214     }
4215   }
4216   if (ima->rr) {
4217     RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
4218 
4219     if (rpass) {
4220       // printf("load from pass %s\n", rpass->name);
4221       /* since we free  render results, we copy the rect */
4222       ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
4223       ibuf->rect_float = MEM_dupallocN(rpass->rect);
4224       ibuf->flags |= IB_rectfloat;
4225       ibuf->mall = IB_rectfloat;
4226       ibuf->channels = rpass->channels;
4227 
4228       BKE_imbuf_stamp_info(ima->rr, ibuf);
4229 
4230       image_init_after_load(ima, iuser, ibuf);
4231       image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, entry);
4232     }
4233     // else printf("pass not found\n");
4234   }
4235   else {
4236     tile->ok = 0;
4237   }
4238 
4239   if (iuser) {
4240     iuser->ok = tile->ok;
4241   }
4242 
4243   return ibuf;
4244 }
4245 
load_movie_single(Image * ima,ImageUser * iuser,int frame,const int view_id)4246 static ImBuf *load_movie_single(Image *ima, ImageUser *iuser, int frame, const int view_id)
4247 {
4248   struct ImBuf *ibuf = NULL;
4249   ImageAnim *ia;
4250 
4251   ia = BLI_findlink(&ima->anims, view_id);
4252 
4253   ImageTile *tile = BKE_image_get_tile(ima, 0);
4254 
4255   if (ia->anim == NULL) {
4256     char str[FILE_MAX];
4257     int flags = IB_rect;
4258     ImageUser iuser_t;
4259 
4260     if (ima->flag & IMA_DEINTERLACE) {
4261       flags |= IB_animdeinterlace;
4262     }
4263 
4264     if (iuser) {
4265       iuser_t = *iuser;
4266     }
4267 
4268     iuser_t.view = view_id;
4269 
4270     BKE_image_user_file_path(&iuser_t, ima, str);
4271 
4272     /* FIXME: make several stream accessible in image editor, too*/
4273     ia->anim = openanim(str, flags, 0, ima->colorspace_settings.name);
4274 
4275     /* let's initialize this user */
4276     if (ia->anim && iuser && iuser->frames == 0) {
4277       iuser->frames = IMB_anim_get_duration(ia->anim, IMB_TC_RECORD_RUN);
4278     }
4279   }
4280 
4281   if (ia->anim) {
4282     int dur = IMB_anim_get_duration(ia->anim, IMB_TC_RECORD_RUN);
4283     int fra = frame - 1;
4284 
4285     if (fra < 0) {
4286       fra = 0;
4287     }
4288     if (fra > (dur - 1)) {
4289       fra = dur - 1;
4290     }
4291     ibuf = IMB_makeSingleUser(IMB_anim_absolute(ia->anim, fra, IMB_TC_RECORD_RUN, IMB_PROXY_NONE));
4292 
4293     if (ibuf) {
4294       image_init_after_load(ima, iuser, ibuf);
4295     }
4296     else {
4297       tile->ok = 0;
4298     }
4299   }
4300   else {
4301     tile->ok = 0;
4302   }
4303 
4304   return ibuf;
4305 }
4306 
image_load_movie_file(Image * ima,ImageUser * iuser,int frame)4307 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
4308 {
4309   struct ImBuf *ibuf = NULL;
4310   const bool is_multiview = BKE_image_is_multiview(ima);
4311   const int totfiles = image_num_files(ima);
4312   ImageTile *tile = BKE_image_get_tile(ima, 0);
4313 
4314   if (totfiles != BLI_listbase_count_at_most(&ima->anims, totfiles + 1)) {
4315     image_free_anims(ima);
4316 
4317     for (int i = 0; i < totfiles; i++) {
4318       /* allocate the ImageAnim */
4319       ImageAnim *ia = MEM_callocN(sizeof(ImageAnim), "Image Anim");
4320       BLI_addtail(&ima->anims, ia);
4321     }
4322   }
4323 
4324   if (!is_multiview) {
4325     ibuf = load_movie_single(ima, iuser, frame, 0);
4326     image_assign_ibuf(ima, ibuf, 0, frame);
4327   }
4328   else {
4329     struct ImBuf **ibuf_arr;
4330     const int totviews = BLI_listbase_count(&ima->views);
4331 
4332     ibuf_arr = MEM_mallocN(sizeof(ImBuf *) * totviews, "Image Views (movie) Imbufs");
4333 
4334     for (int i = 0; i < totfiles; i++) {
4335       ibuf_arr[i] = load_movie_single(ima, iuser, frame, i);
4336     }
4337 
4338     if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D) {
4339       IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]);
4340     }
4341 
4342     for (int i = 0; i < totviews; i++) {
4343       if (ibuf_arr[i]) {
4344         image_assign_ibuf(ima, ibuf_arr[i], i, frame);
4345       }
4346       else {
4347         tile->ok = 0;
4348       }
4349     }
4350 
4351     /* return the original requested ImBuf */
4352     ibuf = ibuf_arr[(iuser ? iuser->multi_index : 0)];
4353 
4354     /* "remove" the others (decrease their refcount) */
4355     for (int i = 0; i < totviews; i++) {
4356       if (ibuf_arr[i] != ibuf) {
4357         IMB_freeImBuf(ibuf_arr[i]);
4358       }
4359     }
4360 
4361     /* cleanup */
4362     MEM_freeN(ibuf_arr);
4363   }
4364 
4365   if (iuser) {
4366     iuser->ok = tile->ok;
4367   }
4368 
4369   return ibuf;
4370 }
4371 
load_image_single(Image * ima,ImageUser * iuser,int cfra,const int view_id,const bool has_packed,bool * r_assign)4372 static ImBuf *load_image_single(Image *ima,
4373                                 ImageUser *iuser,
4374                                 int cfra,
4375                                 const int view_id,
4376                                 const bool has_packed,
4377                                 bool *r_assign)
4378 {
4379   char filepath[FILE_MAX];
4380   struct ImBuf *ibuf = NULL;
4381   int flag;
4382 
4383   /* is there a PackedFile with this image ? */
4384   if (has_packed) {
4385     ImagePackedFile *imapf;
4386 
4387     flag = IB_rect | IB_multilayer;
4388     flag |= imbuf_alpha_flags_for_image(ima);
4389 
4390     imapf = BLI_findlink(&ima->packedfiles, view_id);
4391     if (imapf->packedfile) {
4392       ibuf = IMB_ibImageFromMemory((unsigned char *)imapf->packedfile->data,
4393                                    imapf->packedfile->size,
4394                                    flag,
4395                                    ima->colorspace_settings.name,
4396                                    "<packed data>");
4397     }
4398   }
4399   else {
4400     ImageUser iuser_t;
4401 
4402     flag = IB_rect | IB_multilayer | IB_metadata;
4403     flag |= imbuf_alpha_flags_for_image(ima);
4404 
4405     /* get the correct filepath */
4406     BKE_image_user_frame_calc(ima, iuser, cfra);
4407 
4408     if (iuser) {
4409       iuser_t = *iuser;
4410     }
4411     else {
4412       iuser_t.framenr = ima->lastframe;
4413     }
4414 
4415     iuser_t.view = view_id;
4416 
4417     BKE_image_user_file_path(&iuser_t, ima, filepath);
4418 
4419     /* read ibuf */
4420     ibuf = IMB_loadiffname(filepath, flag, ima->colorspace_settings.name);
4421   }
4422 
4423   if (ibuf) {
4424 #ifdef WITH_OPENEXR
4425     if (ibuf->ftype == IMB_FTYPE_OPENEXR && ibuf->userdata) {
4426       /* Handle multilayer and multiview cases, don't assign ibuf here.
4427        * will be set layer in BKE_image_acquire_ibuf from ima->rr. */
4428       if (IMB_exr_has_multilayer(ibuf->userdata)) {
4429         image_create_multilayer(ima, ibuf, cfra);
4430         ima->type = IMA_TYPE_MULTILAYER;
4431         IMB_freeImBuf(ibuf);
4432         ibuf = NULL;
4433       }
4434     }
4435     else
4436 #endif
4437     {
4438       image_init_after_load(ima, iuser, ibuf);
4439       *r_assign = true;
4440 
4441       /* make packed file for autopack */
4442       if ((has_packed == false) && (G.fileflags & G_FILE_AUTOPACK)) {
4443         ImagePackedFile *imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image Pack-file");
4444         BLI_addtail(&ima->packedfiles, imapf);
4445 
4446         STRNCPY(imapf->filepath, filepath);
4447         imapf->packedfile = BKE_packedfile_new(
4448             NULL, filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
4449       }
4450     }
4451   }
4452   else {
4453     ImageTile *tile = BKE_image_get_tile_from_iuser(ima, iuser);
4454     tile->ok = 0;
4455   }
4456 
4457   return ibuf;
4458 }
4459 
4460 /* warning, 'iuser' can be NULL
4461  * note: Image->views was already populated (in image_update_views_format)
4462  */
image_load_image_file(Image * ima,ImageUser * iuser,int cfra)4463 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
4464 {
4465   struct ImBuf *ibuf = NULL;
4466   bool assign = false;
4467   const bool is_multiview = BKE_image_is_multiview(ima);
4468   const int totfiles = image_num_files(ima);
4469   bool has_packed = BKE_image_has_packedfile(ima);
4470 
4471   /* always ensure clean ima */
4472   BKE_image_free_buffers(ima);
4473 
4474   /* this should never happen, but just playing safe */
4475   if (has_packed) {
4476     if (totfiles != BLI_listbase_count_at_most(&ima->packedfiles, totfiles + 1)) {
4477       image_free_packedfiles(ima);
4478       has_packed = false;
4479     }
4480   }
4481 
4482   if (!is_multiview) {
4483     ibuf = load_image_single(ima, iuser, cfra, 0, has_packed, &assign);
4484     if (assign) {
4485       image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
4486     }
4487   }
4488   else {
4489     struct ImBuf **ibuf_arr;
4490     const int totviews = BLI_listbase_count(&ima->views);
4491     BLI_assert(totviews > 0);
4492 
4493     ibuf_arr = MEM_callocN(sizeof(ImBuf *) * totviews, "Image Views Imbufs");
4494 
4495     for (int i = 0; i < totfiles; i++) {
4496       ibuf_arr[i] = load_image_single(ima, iuser, cfra, i, has_packed, &assign);
4497     }
4498 
4499     /* multi-views/multi-layers OpenEXR files directly populate ima, and return NULL ibuf... */
4500     if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D && ibuf_arr[0] &&
4501         totfiles == 1 && totviews >= 2) {
4502       IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]);
4503     }
4504 
4505     /* return the original requested ImBuf */
4506     int i = (iuser && iuser->multi_index < totviews) ? iuser->multi_index : 0;
4507     ibuf = ibuf_arr[i];
4508 
4509     if (assign) {
4510       for (i = 0; i < totviews; i++) {
4511         image_assign_ibuf(ima, ibuf_arr[i], i, 0);
4512       }
4513     }
4514 
4515     /* "remove" the others (decrease their refcount) */
4516     for (i = 0; i < totviews; i++) {
4517       if (ibuf_arr[i] != ibuf) {
4518         IMB_freeImBuf(ibuf_arr[i]);
4519       }
4520     }
4521 
4522     /* cleanup */
4523     MEM_freeN(ibuf_arr);
4524   }
4525 
4526   if (iuser) {
4527     ImageTile *tile = BKE_image_get_tile(ima, 0);
4528     iuser->ok = tile->ok;
4529   }
4530 
4531   return ibuf;
4532 }
4533 
image_get_ibuf_multilayer(Image * ima,ImageUser * iuser)4534 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
4535 {
4536   ImBuf *ibuf = NULL;
4537 
4538   if (ima->rr == NULL) {
4539     ibuf = image_load_image_file(ima, iuser, 0);
4540     if (ibuf) { /* actually an error */
4541       ima->type = IMA_TYPE_IMAGE;
4542       return ibuf;
4543     }
4544   }
4545   if (ima->rr) {
4546     RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
4547 
4548     if (rpass) {
4549       ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
4550 
4551       image_init_after_load(ima, iuser, ibuf);
4552 
4553       ibuf->rect_float = rpass->rect;
4554       ibuf->flags |= IB_rectfloat;
4555       ibuf->channels = rpass->channels;
4556 
4557       BKE_imbuf_stamp_info(ima->rr, ibuf);
4558 
4559       image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
4560     }
4561   }
4562 
4563   ImageTile *tile = BKE_image_get_tile(ima, 0);
4564   if (ibuf == NULL) {
4565     tile->ok = 0;
4566   }
4567   if (iuser) {
4568     iuser->ok = tile->ok;
4569   }
4570 
4571   return ibuf;
4572 }
4573 
4574 /* showing RGBA result itself (from compo/sequence) or
4575  * like exr, using layers etc */
4576 /* always returns a single ibuf, also during render progress */
image_get_render_result(Image * ima,ImageUser * iuser,void ** r_lock)4577 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_lock)
4578 {
4579   Render *re;
4580   RenderResult rres;
4581   RenderView *rv;
4582   float *rectf, *rectz;
4583   unsigned int *rect;
4584   float dither;
4585   int channels, layer, pass;
4586   ImBuf *ibuf;
4587   int from_render = (ima->render_slot == ima->last_render_slot);
4588   int actview;
4589 
4590   if (!(iuser && iuser->scene)) {
4591     return NULL;
4592   }
4593 
4594   /* if we the caller is not going to release the lock, don't give the image */
4595   if (!r_lock) {
4596     return NULL;
4597   }
4598 
4599   re = RE_GetSceneRender(iuser->scene);
4600 
4601   channels = 4;
4602   layer = iuser->layer;
4603   pass = iuser->pass;
4604   actview = iuser->view;
4605 
4606   if (BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO)) {
4607     actview = iuser->multiview_eye;
4608   }
4609 
4610   RenderSlot *slot;
4611   if (from_render) {
4612     RE_AcquireResultImage(re, &rres, actview);
4613   }
4614   else if ((slot = BKE_image_get_renderslot(ima, ima->render_slot))->render) {
4615     rres = *(slot->render);
4616     rres.have_combined = ((RenderView *)rres.views.first)->rectf != NULL;
4617   }
4618   else {
4619     memset(&rres, 0, sizeof(RenderResult));
4620   }
4621 
4622   if (!(rres.rectx > 0 && rres.recty > 0)) {
4623     if (from_render) {
4624       RE_ReleaseResultImage(re);
4625     }
4626     return NULL;
4627   }
4628 
4629   /* release is done in BKE_image_release_ibuf using r_lock */
4630   if (from_render) {
4631     BLI_thread_lock(LOCK_VIEWER);
4632     *r_lock = re;
4633     rv = NULL;
4634   }
4635   else {
4636     rv = BLI_findlink(&rres.views, actview);
4637     if (rv == NULL) {
4638       rv = rres.views.first;
4639     }
4640   }
4641 
4642   /* this gives active layer, composite or sequence result */
4643   if (rv == NULL) {
4644     rect = (unsigned int *)rres.rect32;
4645     rectf = rres.rectf;
4646     rectz = rres.rectz;
4647   }
4648   else {
4649     rect = (unsigned int *)rv->rect32;
4650     rectf = rv->rectf;
4651     rectz = rv->rectz;
4652   }
4653 
4654   dither = iuser->scene->r.dither_intensity;
4655 
4656   /* combined layer gets added as first layer */
4657   if (rres.have_combined && layer == 0) {
4658     /* pass */
4659   }
4660   else if (rect && layer == 0) {
4661     /* rect32 is set when there's a Sequence pass, this pass seems
4662      * to have layer=0 (this is from image_buttons.c)
4663      * in this case we ignore float buffer, because it could have
4664      * hung from previous pass which was float
4665      */
4666     rectf = NULL;
4667   }
4668   else if (rres.layers.first) {
4669     RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
4670     if (rl) {
4671       RenderPass *rpass = image_render_pass_get(rl, pass, actview, NULL);
4672       if (rpass) {
4673         rectf = rpass->rect;
4674         if (pass != 0) {
4675           channels = rpass->channels;
4676           dither = 0.0f; /* don't dither passes */
4677         }
4678       }
4679 
4680       for (rpass = rl->passes.first; rpass; rpass = rpass->next) {
4681         if (STREQ(rpass->name, RE_PASSNAME_Z) && rpass->view_id == actview) {
4682           rectz = rpass->rect;
4683         }
4684       }
4685     }
4686   }
4687 
4688   ibuf = image_get_cached_ibuf_for_index_entry(ima, IMA_NO_INDEX, 0);
4689 
4690   /* make ibuf if needed, and initialize it */
4691   if (ibuf == NULL) {
4692     ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
4693     image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
4694   }
4695 
4696   /* Set color space settings for a byte buffer.
4697    *
4698    * This is mainly to make it so color management treats byte buffer
4699    * from render result with Save Buffers enabled as final display buffer
4700    * and doesn't apply any color management on it.
4701    *
4702    * For other cases we need to be sure it stays to default byte buffer space.
4703    */
4704   if (ibuf->rect != rect) {
4705     const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
4706     IMB_colormanagement_assign_rect_colorspace(ibuf, colorspace);
4707   }
4708 
4709   /* invalidate color managed buffers if render result changed */
4710   BLI_thread_lock(LOCK_COLORMANAGE);
4711   if (ibuf->x != rres.rectx || ibuf->y != rres.recty || ibuf->rect_float != rectf) {
4712     ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
4713   }
4714 
4715   ibuf->x = rres.rectx;
4716   ibuf->y = rres.recty;
4717 
4718   if (rect) {
4719     imb_freerectImBuf(ibuf);
4720     ibuf->rect = rect;
4721   }
4722   else {
4723     /* byte buffer of render result has been freed, make sure image buffers
4724      * does not reference to this buffer anymore
4725      * need check for whether byte buffer was allocated and owned by image itself
4726      * or if it's reusing buffer from render result
4727      */
4728     if ((ibuf->mall & IB_rect) == 0) {
4729       ibuf->rect = NULL;
4730     }
4731   }
4732 
4733   if (rectf) {
4734     ibuf->rect_float = rectf;
4735     ibuf->flags |= IB_rectfloat;
4736     ibuf->channels = channels;
4737   }
4738   else {
4739     ibuf->rect_float = NULL;
4740     ibuf->flags &= ~IB_rectfloat;
4741   }
4742 
4743   if (rectz) {
4744     ibuf->zbuf_float = rectz;
4745     ibuf->flags |= IB_zbuffloat;
4746   }
4747   else {
4748     ibuf->zbuf_float = NULL;
4749     ibuf->flags &= ~IB_zbuffloat;
4750   }
4751 
4752   /* TODO(sergey): Make this faster by either simply referencing the stamp
4753    * or by changing both ImBug and RenderResult to use same data type to
4754    * store metadata. */
4755   if (ibuf->metadata != NULL) {
4756     IMB_metadata_free(ibuf->metadata);
4757     ibuf->metadata = NULL;
4758   }
4759   BKE_imbuf_stamp_info(&rres, ibuf);
4760 
4761   BLI_thread_unlock(LOCK_COLORMANAGE);
4762 
4763   ibuf->dither = dither;
4764 
4765   ImageTile *tile = BKE_image_get_tile(ima, 0);
4766   tile->ok = IMA_OK_LOADED;
4767 
4768   return ibuf;
4769 }
4770 
image_get_multiview_index(Image * ima,ImageUser * iuser)4771 static int image_get_multiview_index(Image *ima, ImageUser *iuser)
4772 {
4773   const bool is_multilayer = BKE_image_is_multilayer(ima);
4774   const bool is_backdrop = (ima->source == IMA_SRC_VIEWER) && (ima->type == IMA_TYPE_COMPOSITE) &&
4775                            (iuser == NULL);
4776   int index = BKE_image_has_multiple_ibufs(ima) ? 0 : IMA_NO_INDEX;
4777 
4778   if (is_multilayer) {
4779     return iuser ? iuser->multi_index : index;
4780   }
4781   if (is_backdrop) {
4782     if (BKE_image_is_stereo(ima)) {
4783       /* backdrop hackaround (since there is no iuser */
4784       return ima->eye;
4785     }
4786   }
4787   else if (BKE_image_is_multiview(ima)) {
4788     return iuser ? iuser->multi_index : index;
4789   }
4790 
4791   return index;
4792 }
4793 
image_get_entry_and_index(Image * ima,ImageUser * iuser,int * r_entry,int * r_index)4794 static void image_get_entry_and_index(Image *ima, ImageUser *iuser, int *r_entry, int *r_index)
4795 {
4796   int frame = 0, index = image_get_multiview_index(ima, iuser);
4797 
4798   /* see if we already have an appropriate ibuf, with image source and type */
4799   if (ima->source == IMA_SRC_MOVIE) {
4800     frame = iuser ? iuser->framenr : ima->lastframe;
4801   }
4802   else if (ima->source == IMA_SRC_SEQUENCE) {
4803     if (ima->type == IMA_TYPE_IMAGE) {
4804       frame = iuser ? iuser->framenr : ima->lastframe;
4805     }
4806     else if (ima->type == IMA_TYPE_MULTILAYER) {
4807       frame = iuser ? iuser->framenr : ima->lastframe;
4808     }
4809   }
4810   else if (ima->source == IMA_SRC_TILED) {
4811     frame = (iuser && iuser->tile) ? iuser->tile : 1001;
4812   }
4813 
4814   *r_entry = frame;
4815   *r_index = index;
4816 }
4817 
4818 /* Get the ibuf from an image cache for a given image user.
4819  *
4820  * Returns referenced image buffer if it exists, callee is to
4821  * call IMB_freeImBuf to de-reference the image buffer after
4822  * it's done handling it.
4823  */
image_get_cached_ibuf(Image * ima,ImageUser * iuser,int * r_entry,int * r_index)4824 static ImBuf *image_get_cached_ibuf(Image *ima, ImageUser *iuser, int *r_entry, int *r_index)
4825 {
4826   ImBuf *ibuf = NULL;
4827   int entry = 0, index = image_get_multiview_index(ima, iuser);
4828 
4829   /* see if we already have an appropriate ibuf, with image source and type */
4830   if (ima->source == IMA_SRC_MOVIE) {
4831     entry = iuser ? iuser->framenr : ima->lastframe;
4832     ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry);
4833     ima->lastframe = entry;
4834   }
4835   else if (ima->source == IMA_SRC_SEQUENCE) {
4836     if (ima->type == IMA_TYPE_IMAGE) {
4837       entry = iuser ? iuser->framenr : ima->lastframe;
4838       ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry);
4839       ima->lastframe = entry;
4840 
4841       /* counter the fact that image is set as invalid when loading a frame
4842        * that is not in the cache (through image_acquire_ibuf for instance),
4843        * yet we have valid frames in the cache loaded */
4844       if (ibuf) {
4845         ImageTile *tile = BKE_image_get_tile(ima, 0);
4846         tile->ok = IMA_OK_LOADED;
4847 
4848         if (iuser) {
4849           iuser->ok = tile->ok;
4850         }
4851       }
4852     }
4853     else if (ima->type == IMA_TYPE_MULTILAYER) {
4854       entry = iuser ? iuser->framenr : ima->lastframe;
4855       ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry);
4856     }
4857   }
4858   else if (ima->source == IMA_SRC_FILE) {
4859     if (ima->type == IMA_TYPE_IMAGE) {
4860       ibuf = image_get_cached_ibuf_for_index_entry(ima, index, 0);
4861     }
4862     else if (ima->type == IMA_TYPE_MULTILAYER) {
4863       ibuf = image_get_cached_ibuf_for_index_entry(ima, index, 0);
4864     }
4865   }
4866   else if (ima->source == IMA_SRC_GENERATED) {
4867     ibuf = image_get_cached_ibuf_for_index_entry(ima, index, 0);
4868   }
4869   else if (ima->source == IMA_SRC_VIEWER) {
4870     /* always verify entirely, not that this shouldn't happen
4871      * as part of texture sampling in rendering anyway, so not
4872      * a big bottleneck */
4873   }
4874   else if (ima->source == IMA_SRC_TILED) {
4875     if (ELEM(ima->type, IMA_TYPE_IMAGE, IMA_TYPE_MULTILAYER)) {
4876       entry = (iuser && iuser->tile) ? iuser->tile : 1001;
4877       ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry);
4878 
4879       if ((ima->type == IMA_TYPE_IMAGE) && ibuf != NULL) {
4880         ImageTile *tile = BKE_image_get_tile(ima, entry);
4881         tile->ok = IMA_OK_LOADED;
4882 
4883         /* iuser->ok is useless for tiled images because iuser->tile changes all the time. */
4884         if (iuser != NULL) {
4885           iuser->ok = 1;
4886         }
4887       }
4888     }
4889   }
4890 
4891   if (r_entry) {
4892     *r_entry = entry;
4893   }
4894 
4895   if (r_index) {
4896     *r_index = index;
4897   }
4898 
4899   return ibuf;
4900 }
4901 
image_quick_test(Image * ima,const ImageUser * iuser)4902 BLI_INLINE bool image_quick_test(Image *ima, const ImageUser *iuser)
4903 {
4904   if (ima == NULL) {
4905     return false;
4906   }
4907 
4908   if (iuser) {
4909     if (iuser->ok == 0) {
4910       return false;
4911     }
4912   }
4913 
4914   ImageTile *tile = BKE_image_get_tile_from_iuser(ima, iuser);
4915   if (tile == NULL) {
4916     return false;
4917   }
4918   if (tile->ok == 0) {
4919     return false;
4920   }
4921 
4922   return true;
4923 }
4924 
4925 /* Checks optional ImageUser and verifies/creates ImBuf.
4926  *
4927  * not thread-safe, so callee should worry about thread locks
4928  */
image_acquire_ibuf(Image * ima,ImageUser * iuser,void ** r_lock)4929 static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock)
4930 {
4931   ImBuf *ibuf = NULL;
4932   int entry = 0, index = 0;
4933 
4934   if (r_lock) {
4935     *r_lock = NULL;
4936   }
4937 
4938   /* quick reject tests */
4939   if (!image_quick_test(ima, iuser)) {
4940     return NULL;
4941   }
4942 
4943   ibuf = image_get_cached_ibuf(ima, iuser, &entry, &index);
4944 
4945   if (ibuf == NULL) {
4946     /* we are sure we have to load the ibuf, using source and type */
4947     if (ima->source == IMA_SRC_MOVIE) {
4948       /* source is from single file, use flipbook to store ibuf */
4949       ibuf = image_load_movie_file(ima, iuser, entry);
4950     }
4951     else if (ima->source == IMA_SRC_SEQUENCE) {
4952       if (ima->type == IMA_TYPE_IMAGE) {
4953         /* regular files, ibufs in flipbook, allows saving */
4954         ibuf = image_load_sequence_file(ima, iuser, entry, entry);
4955       }
4956       /* no else; on load the ima type can change */
4957       if (ima->type == IMA_TYPE_MULTILAYER) {
4958         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
4959         ibuf = image_load_sequence_multilayer(ima, iuser, entry, entry);
4960       }
4961     }
4962     else if (ima->source == IMA_SRC_TILED) {
4963       if (ima->type == IMA_TYPE_IMAGE) {
4964         /* regular files, ibufs in flipbook, allows saving */
4965         ibuf = image_load_sequence_file(ima, iuser, entry, 0);
4966       }
4967       /* no else; on load the ima type can change */
4968       if (ima->type == IMA_TYPE_MULTILAYER) {
4969         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
4970         ibuf = image_load_sequence_multilayer(ima, iuser, entry, 0);
4971       }
4972     }
4973     else if (ima->source == IMA_SRC_FILE) {
4974 
4975       if (ima->type == IMA_TYPE_IMAGE) {
4976         ibuf = image_load_image_file(ima, iuser, entry); /* cfra only for '#', this global is OK */
4977       }
4978       /* no else; on load the ima type can change */
4979       if (ima->type == IMA_TYPE_MULTILAYER) {
4980         /* keeps render result, stores ibufs in listbase, allows saving */
4981         ibuf = image_get_ibuf_multilayer(ima, iuser);
4982       }
4983     }
4984     else if (ima->source == IMA_SRC_GENERATED) {
4985       /* generated is: ibuf is allocated dynamically */
4986       /* UV testgrid or black or solid etc */
4987       if (ima->gen_x == 0) {
4988         ima->gen_x = 1024;
4989       }
4990       if (ima->gen_y == 0) {
4991         ima->gen_y = 1024;
4992       }
4993       if (ima->gen_depth == 0) {
4994         ima->gen_depth = 24;
4995       }
4996       ibuf = add_ibuf_size(ima->gen_x,
4997                            ima->gen_y,
4998                            ima->filepath,
4999                            ima->gen_depth,
5000                            (ima->gen_flag & IMA_GEN_FLOAT) != 0,
5001                            ima->gen_type,
5002                            ima->gen_color,
5003                            &ima->colorspace_settings);
5004       image_assign_ibuf(ima, ibuf, index, 0);
5005       ImageTile *tile = BKE_image_get_tile(ima, 0);
5006       tile->ok = IMA_OK_LOADED;
5007     }
5008     else if (ima->source == IMA_SRC_VIEWER) {
5009       if (ima->type == IMA_TYPE_R_RESULT) {
5010         /* always verify entirely, and potentially
5011          * returns pointer to release later */
5012         ibuf = image_get_render_result(ima, iuser, r_lock);
5013       }
5014       else if (ima->type == IMA_TYPE_COMPOSITE) {
5015         /* requires lock/unlock, otherwise don't return image */
5016         if (r_lock) {
5017           /* unlock in BKE_image_release_ibuf */
5018           BLI_thread_lock(LOCK_VIEWER);
5019           *r_lock = ima;
5020 
5021           /* XXX anim play for viewer nodes not yet supported */
5022           entry = 0;  // XXX iuser ? iuser->framenr : 0;
5023           ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry);
5024 
5025           if (!ibuf) {
5026             /* Composite Viewer, all handled in compositor */
5027             /* fake ibuf, will be filled in compositor */
5028             ibuf = IMB_allocImBuf(256, 256, 32, IB_rect | IB_rectfloat);
5029             image_assign_ibuf(ima, ibuf, index, entry);
5030           }
5031         }
5032       }
5033     }
5034 
5035     /* We only want movies and sequences to be memory limited. */
5036     if (ibuf != NULL && !ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
5037       ibuf->userflags |= IB_PERSISTENT;
5038     }
5039   }
5040 
5041   BKE_image_tag_time(ima);
5042 
5043   return ibuf;
5044 }
5045 
5046 /* return image buffer for given image and user
5047  *
5048  * - will lock render result if image type is render result and lock is not NULL
5049  * - will return NULL if image type if render or composite result and lock is NULL
5050  *
5051  * references the result, BKE_image_release_ibuf should be used to de-reference
5052  */
BKE_image_acquire_ibuf(Image * ima,ImageUser * iuser,void ** r_lock)5053 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock)
5054 {
5055   ImBuf *ibuf;
5056 
5057   BLI_mutex_lock(image_mutex);
5058 
5059   ibuf = image_acquire_ibuf(ima, iuser, r_lock);
5060 
5061   BLI_mutex_unlock(image_mutex);
5062 
5063   return ibuf;
5064 }
5065 
BKE_image_release_ibuf(Image * ima,ImBuf * ibuf,void * lock)5066 void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
5067 {
5068   if (lock != NULL) {
5069     /* for getting image during threaded render / compositing, need to release */
5070     if (lock == ima) {
5071       BLI_thread_unlock(LOCK_VIEWER); /* viewer image */
5072     }
5073     else {
5074       RE_ReleaseResultImage(lock);    /* render result */
5075       BLI_thread_unlock(LOCK_VIEWER); /* view image imbuf */
5076     }
5077   }
5078 
5079   if (ibuf) {
5080     BLI_mutex_lock(image_mutex);
5081     IMB_freeImBuf(ibuf);
5082     BLI_mutex_unlock(image_mutex);
5083   }
5084 }
5085 
5086 /* checks whether there's an image buffer for given image and user */
BKE_image_has_ibuf(Image * ima,ImageUser * iuser)5087 bool BKE_image_has_ibuf(Image *ima, ImageUser *iuser)
5088 {
5089   ImBuf *ibuf;
5090 
5091   /* quick reject tests */
5092   if (!image_quick_test(ima, iuser)) {
5093     return false;
5094   }
5095 
5096   BLI_mutex_lock(image_mutex);
5097 
5098   ibuf = image_get_cached_ibuf(ima, iuser, NULL, NULL);
5099 
5100   if (!ibuf) {
5101     ibuf = image_acquire_ibuf(ima, iuser, NULL);
5102   }
5103 
5104   BLI_mutex_unlock(image_mutex);
5105 
5106   IMB_freeImBuf(ibuf);
5107 
5108   return ibuf != NULL;
5109 }
5110 
5111 /* ******** Pool for image buffers ********  */
5112 
5113 typedef struct ImagePoolItem {
5114   struct ImagePoolItem *next, *prev;
5115   Image *image;
5116   ImBuf *ibuf;
5117   int index;
5118   int entry;
5119 } ImagePoolItem;
5120 
5121 typedef struct ImagePool {
5122   ListBase image_buffers;
5123   BLI_mempool *memory_pool;
5124 } ImagePool;
5125 
BKE_image_pool_new(void)5126 ImagePool *BKE_image_pool_new(void)
5127 {
5128   ImagePool *pool = MEM_callocN(sizeof(ImagePool), "Image Pool");
5129   pool->memory_pool = BLI_mempool_create(sizeof(ImagePoolItem), 0, 128, BLI_MEMPOOL_NOP);
5130 
5131   return pool;
5132 }
5133 
BKE_image_pool_free(ImagePool * pool)5134 void BKE_image_pool_free(ImagePool *pool)
5135 {
5136   /* Use single lock to dereference all the image buffers. */
5137   BLI_mutex_lock(image_mutex);
5138   for (ImagePoolItem *item = pool->image_buffers.first; item != NULL; item = item->next) {
5139     if (item->ibuf != NULL) {
5140       IMB_freeImBuf(item->ibuf);
5141     }
5142   }
5143   BLI_mutex_unlock(image_mutex);
5144 
5145   BLI_mempool_destroy(pool->memory_pool);
5146   MEM_freeN(pool);
5147 }
5148 
image_pool_find_item(ImagePool * pool,Image * image,int entry,int index,bool * found)5149 BLI_INLINE ImBuf *image_pool_find_item(
5150     ImagePool *pool, Image *image, int entry, int index, bool *found)
5151 {
5152   ImagePoolItem *item;
5153 
5154   *found = false;
5155 
5156   for (item = pool->image_buffers.first; item; item = item->next) {
5157     if (item->image == image && item->entry == entry && item->index == index) {
5158       *found = true;
5159       return item->ibuf;
5160     }
5161   }
5162 
5163   return NULL;
5164 }
5165 
BKE_image_pool_acquire_ibuf(Image * ima,ImageUser * iuser,ImagePool * pool)5166 ImBuf *BKE_image_pool_acquire_ibuf(Image *ima, ImageUser *iuser, ImagePool *pool)
5167 {
5168   ImBuf *ibuf;
5169   int index, entry;
5170   bool found;
5171 
5172   if (!image_quick_test(ima, iuser)) {
5173     return NULL;
5174   }
5175 
5176   if (pool == NULL) {
5177     /* pool could be NULL, in this case use general acquire function */
5178     return BKE_image_acquire_ibuf(ima, iuser, NULL);
5179   }
5180 
5181   image_get_entry_and_index(ima, iuser, &entry, &index);
5182 
5183   ibuf = image_pool_find_item(pool, ima, entry, index, &found);
5184   if (found) {
5185     return ibuf;
5186   }
5187 
5188   BLI_mutex_lock(image_mutex);
5189 
5190   ibuf = image_pool_find_item(pool, ima, entry, index, &found);
5191 
5192   /* will also create item even in cases image buffer failed to load,
5193    * prevents trying to load the same buggy file multiple times
5194    */
5195   if (!found) {
5196     ImagePoolItem *item;
5197 
5198     ibuf = image_acquire_ibuf(ima, iuser, NULL);
5199 
5200     item = BLI_mempool_alloc(pool->memory_pool);
5201     item->image = ima;
5202     item->entry = entry;
5203     item->index = index;
5204     item->ibuf = ibuf;
5205 
5206     BLI_addtail(&pool->image_buffers, item);
5207   }
5208 
5209   BLI_mutex_unlock(image_mutex);
5210 
5211   return ibuf;
5212 }
5213 
BKE_image_pool_release_ibuf(Image * ima,ImBuf * ibuf,ImagePool * pool)5214 void BKE_image_pool_release_ibuf(Image *ima, ImBuf *ibuf, ImagePool *pool)
5215 {
5216   /* if pool wasn't actually used, use general release stuff,
5217    * for pools image buffers will be dereferenced on pool free
5218    */
5219   if (pool == NULL) {
5220     BKE_image_release_ibuf(ima, ibuf, NULL);
5221   }
5222 }
5223 
BKE_image_user_frame_get(const ImageUser * iuser,int cfra,bool * r_is_in_range)5224 int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, bool *r_is_in_range)
5225 {
5226   const int len = iuser->frames;
5227 
5228   if (r_is_in_range) {
5229     *r_is_in_range = false;
5230   }
5231 
5232   if (len == 0) {
5233     return 0;
5234   }
5235 
5236   int framenr;
5237   cfra = cfra - iuser->sfra + 1;
5238 
5239   /* cyclic */
5240   if (iuser->cycl) {
5241     cfra = ((cfra) % len);
5242     if (cfra < 0) {
5243       cfra += len;
5244     }
5245     if (cfra == 0) {
5246       cfra = len;
5247     }
5248 
5249     if (r_is_in_range) {
5250       *r_is_in_range = true;
5251     }
5252   }
5253 
5254   if (cfra < 0) {
5255     cfra = 0;
5256   }
5257   else if (cfra > len) {
5258     cfra = len;
5259   }
5260   else {
5261     if (r_is_in_range) {
5262       *r_is_in_range = true;
5263     }
5264   }
5265 
5266   /* transform to images space */
5267   framenr = cfra;
5268   if (framenr > iuser->frames) {
5269     framenr = iuser->frames;
5270   }
5271 
5272   if (iuser->cycl) {
5273     framenr = ((framenr) % len);
5274     while (framenr < 0) {
5275       framenr += len;
5276     }
5277     if (framenr == 0) {
5278       framenr = len;
5279     }
5280   }
5281 
5282   /* important to apply after else we cant loop on frames 100 - 110 for eg. */
5283   framenr += iuser->offset;
5284 
5285   return framenr;
5286 }
5287 
BKE_image_user_frame_calc(Image * ima,ImageUser * iuser,int cfra)5288 void BKE_image_user_frame_calc(Image *ima, ImageUser *iuser, int cfra)
5289 {
5290   if (iuser) {
5291     if (ima && BKE_image_is_animated(ima)) {
5292       /* Compute current frame for animated image. */
5293       bool is_in_range;
5294       const int framenr = BKE_image_user_frame_get(iuser, cfra, &is_in_range);
5295 
5296       if (is_in_range) {
5297         iuser->flag |= IMA_USER_FRAME_IN_RANGE;
5298       }
5299       else {
5300         iuser->flag &= ~IMA_USER_FRAME_IN_RANGE;
5301       }
5302 
5303       iuser->framenr = framenr;
5304     }
5305     else {
5306       /* Set fixed frame number for still image. */
5307       iuser->framenr = 0;
5308       iuser->flag |= IMA_USER_FRAME_IN_RANGE;
5309     }
5310 
5311     if (ima && ima->gpuframenr != iuser->framenr) {
5312       /* Note: a single texture and refresh doesn't really work when
5313        * multiple image users may use different frames, this is to
5314        * be improved with perhaps a GPU texture cache. */
5315       ima->gpuflag |= IMA_GPU_REFRESH;
5316       ima->gpuframenr = iuser->framenr;
5317     }
5318 
5319     if (iuser->ok == 0) {
5320       iuser->ok = 1;
5321     }
5322 
5323     if (ima) {
5324       LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
5325         if (tile->ok == 0) {
5326           tile->ok = IMA_OK;
5327         }
5328       }
5329     }
5330 
5331     iuser->flag &= ~IMA_NEED_FRAME_RECALC;
5332   }
5333 }
5334 
5335 /* goes over all ImageUsers, and sets frame numbers if auto-refresh is set */
image_editors_update_frame(Image * ima,ID * UNUSED (iuser_id),ImageUser * iuser,void * customdata)5336 static void image_editors_update_frame(Image *ima,
5337                                        ID *UNUSED(iuser_id),
5338                                        ImageUser *iuser,
5339                                        void *customdata)
5340 {
5341   int cfra = *(int *)customdata;
5342 
5343   if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
5344     BKE_image_user_frame_calc(ima, iuser, cfra);
5345   }
5346 }
5347 
BKE_image_editors_update_frame(const Main * bmain,int cfra)5348 void BKE_image_editors_update_frame(const Main *bmain, int cfra)
5349 {
5350   /* This only updates images used by the user interface. For others the
5351    * dependency graph will call BKE_image_user_id_eval_animation. */
5352   wmWindowManager *wm = bmain->wm.first;
5353   image_walk_id_all_users(&wm->id, false, &cfra, image_editors_update_frame);
5354 }
5355 
image_user_id_has_animation(Image * ima,ID * UNUSED (iuser_id),ImageUser * UNUSED (iuser),void * customdata)5356 static void image_user_id_has_animation(Image *ima,
5357                                         ID *UNUSED(iuser_id),
5358                                         ImageUser *UNUSED(iuser),
5359                                         void *customdata)
5360 {
5361   if (ima && BKE_image_is_animated(ima)) {
5362     *(bool *)customdata = true;
5363   }
5364 }
5365 
BKE_image_user_id_has_animation(ID * id)5366 bool BKE_image_user_id_has_animation(ID *id)
5367 {
5368   /* For the dependency graph, this does not consider nested node
5369    * trees as these are handled as their own datablock. */
5370   bool has_animation = false;
5371   bool skip_nested_nodes = true;
5372   image_walk_id_all_users(id, skip_nested_nodes, &has_animation, image_user_id_has_animation);
5373   return has_animation;
5374 }
5375 
image_user_id_eval_animation(Image * ima,ID * UNUSED (iduser_id),ImageUser * iuser,void * customdata)5376 static void image_user_id_eval_animation(Image *ima,
5377                                          ID *UNUSED(iduser_id),
5378                                          ImageUser *iuser,
5379                                          void *customdata)
5380 {
5381   if (ima && BKE_image_is_animated(ima)) {
5382     Depsgraph *depsgraph = (Depsgraph *)customdata;
5383 
5384     if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC) ||
5385         (DEG_get_mode(depsgraph) == DAG_EVAL_RENDER)) {
5386       float cfra = DEG_get_ctime(depsgraph);
5387 
5388       BKE_image_user_frame_calc(ima, iuser, cfra);
5389     }
5390   }
5391 }
5392 
BKE_image_user_id_eval_animation(Depsgraph * depsgraph,ID * id)5393 void BKE_image_user_id_eval_animation(Depsgraph *depsgraph, ID *id)
5394 {
5395   /* This is called from the dependency graph to update the image
5396    * users in data-blocks. It computes the current frame number
5397    * and tags the image to be refreshed.
5398    * This does not consider nested node trees as these are handled
5399    * as their own data-block. */
5400   bool skip_nested_nodes = true;
5401   image_walk_id_all_users(id, skip_nested_nodes, depsgraph, image_user_id_eval_animation);
5402 }
5403 
BKE_image_user_file_path(ImageUser * iuser,Image * ima,char * filepath)5404 void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath)
5405 {
5406   if (BKE_image_is_multiview(ima)) {
5407     ImageView *iv = BLI_findlink(&ima->views, iuser->view);
5408     if (iv->filepath[0]) {
5409       BLI_strncpy(filepath, iv->filepath, FILE_MAX);
5410     }
5411     else {
5412       BLI_strncpy(filepath, ima->filepath, FILE_MAX);
5413     }
5414   }
5415   else {
5416     BLI_strncpy(filepath, ima->filepath, FILE_MAX);
5417   }
5418 
5419   if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
5420     char head[FILE_MAX], tail[FILE_MAX];
5421     unsigned short numlen;
5422 
5423     int index;
5424     if (ima->source == IMA_SRC_SEQUENCE) {
5425       index = iuser ? iuser->framenr : ima->lastframe;
5426     }
5427     else {
5428       index = (iuser && iuser->tile) ? iuser->tile : 1001;
5429     }
5430 
5431     BLI_path_sequence_decode(filepath, head, tail, &numlen);
5432     BLI_path_sequence_encode(filepath, head, tail, numlen, index);
5433   }
5434 
5435   BLI_path_abs(filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
5436 }
5437 
BKE_image_has_alpha(struct Image * image)5438 bool BKE_image_has_alpha(struct Image *image)
5439 {
5440   ImBuf *ibuf;
5441   void *lock;
5442   int planes;
5443 
5444   ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
5445   planes = (ibuf ? ibuf->planes : 0);
5446   BKE_image_release_ibuf(image, ibuf, lock);
5447 
5448   if (planes == 32) {
5449     return true;
5450   }
5451 
5452   return false;
5453 }
5454 
BKE_image_get_size(Image * image,ImageUser * iuser,int * r_width,int * r_height)5455 void BKE_image_get_size(Image *image, ImageUser *iuser, int *r_width, int *r_height)
5456 {
5457   ImBuf *ibuf = NULL;
5458   void *lock;
5459 
5460   if (image != NULL) {
5461     ibuf = BKE_image_acquire_ibuf(image, iuser, &lock);
5462   }
5463 
5464   if (ibuf && ibuf->x > 0 && ibuf->y > 0) {
5465     *r_width = ibuf->x;
5466     *r_height = ibuf->y;
5467   }
5468   else if (image != NULL && image->type == IMA_TYPE_R_RESULT && iuser != NULL &&
5469            iuser->scene != NULL) {
5470     Scene *scene = iuser->scene;
5471     *r_width = (scene->r.xsch * scene->r.size) / 100;
5472     *r_height = (scene->r.ysch * scene->r.size) / 100;
5473     if ((scene->r.mode & R_BORDER) && (scene->r.mode & R_CROP)) {
5474       *r_width *= BLI_rctf_size_x(&scene->r.border);
5475       *r_height *= BLI_rctf_size_y(&scene->r.border);
5476     }
5477   }
5478   else {
5479     *r_width = IMG_SIZE_FALLBACK;
5480     *r_height = IMG_SIZE_FALLBACK;
5481   }
5482 
5483   if (image != NULL) {
5484     BKE_image_release_ibuf(image, ibuf, lock);
5485   }
5486 }
5487 
BKE_image_get_size_fl(Image * image,ImageUser * iuser,float r_size[2])5488 void BKE_image_get_size_fl(Image *image, ImageUser *iuser, float r_size[2])
5489 {
5490   int width, height;
5491   BKE_image_get_size(image, iuser, &width, &height);
5492 
5493   r_size[0] = (float)width;
5494   r_size[1] = (float)height;
5495 }
5496 
BKE_image_get_aspect(Image * image,float * r_aspx,float * r_aspy)5497 void BKE_image_get_aspect(Image *image, float *r_aspx, float *r_aspy)
5498 {
5499   *r_aspx = 1.0;
5500 
5501   /* x is always 1 */
5502   if (image) {
5503     *r_aspy = image->aspy / image->aspx;
5504   }
5505   else {
5506     *r_aspy = 1.0f;
5507   }
5508 }
5509 
BKE_image_get_pixels_for_frame(struct Image * image,int frame,int tile)5510 unsigned char *BKE_image_get_pixels_for_frame(struct Image *image, int frame, int tile)
5511 {
5512   ImageUser iuser;
5513   BKE_imageuser_default(&iuser);
5514   void *lock;
5515   ImBuf *ibuf;
5516   unsigned char *pixels = NULL;
5517 
5518   iuser.framenr = frame;
5519   iuser.tile = tile;
5520 
5521   ibuf = BKE_image_acquire_ibuf(image, &iuser, &lock);
5522 
5523   if (ibuf) {
5524     pixels = (unsigned char *)ibuf->rect;
5525 
5526     if (pixels) {
5527       pixels = MEM_dupallocN(pixels);
5528     }
5529 
5530     BKE_image_release_ibuf(image, ibuf, lock);
5531   }
5532 
5533   if (!pixels) {
5534     return NULL;
5535   }
5536 
5537   return pixels;
5538 }
5539 
BKE_image_get_float_pixels_for_frame(struct Image * image,int frame,int tile)5540 float *BKE_image_get_float_pixels_for_frame(struct Image *image, int frame, int tile)
5541 {
5542   ImageUser iuser;
5543   BKE_imageuser_default(&iuser);
5544   void *lock;
5545   ImBuf *ibuf;
5546   float *pixels = NULL;
5547 
5548   iuser.framenr = frame;
5549   iuser.tile = tile;
5550 
5551   ibuf = BKE_image_acquire_ibuf(image, &iuser, &lock);
5552 
5553   if (ibuf) {
5554     pixels = ibuf->rect_float;
5555 
5556     if (pixels) {
5557       pixels = MEM_dupallocN(pixels);
5558     }
5559 
5560     BKE_image_release_ibuf(image, ibuf, lock);
5561   }
5562 
5563   if (!pixels) {
5564     return NULL;
5565   }
5566 
5567   return pixels;
5568 }
5569 
BKE_image_sequence_guess_offset(Image * image)5570 int BKE_image_sequence_guess_offset(Image *image)
5571 {
5572   return BLI_path_sequence_decode(image->filepath, NULL, NULL, NULL);
5573 }
5574 
BKE_image_has_anim(Image * ima)5575 bool BKE_image_has_anim(Image *ima)
5576 {
5577   return (BLI_listbase_is_empty(&ima->anims) == false);
5578 }
5579 
BKE_image_has_packedfile(Image * ima)5580 bool BKE_image_has_packedfile(Image *ima)
5581 {
5582   return (BLI_listbase_is_empty(&ima->packedfiles) == false);
5583 }
5584 
BKE_image_has_filepath(Image * ima)5585 bool BKE_image_has_filepath(Image *ima)
5586 {
5587   /* This could be improved to detect cases like //../../, currently path
5588    * remapping empty file paths empty. */
5589   return ima->filepath[0] != '\0';
5590 }
5591 
5592 /* Checks the image buffer changes with time (not keyframed values). */
BKE_image_is_animated(Image * image)5593 bool BKE_image_is_animated(Image *image)
5594 {
5595   return ELEM(image->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE);
5596 }
5597 
5598 /* Checks whether the image consists of multiple buffers. */
BKE_image_has_multiple_ibufs(Image * image)5599 bool BKE_image_has_multiple_ibufs(Image *image)
5600 {
5601   return ELEM(image->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE, IMA_SRC_TILED);
5602 }
5603 
5604 /* Image modifications */
BKE_image_is_dirty_writable(Image * image,bool * r_is_writable)5605 bool BKE_image_is_dirty_writable(Image *image, bool *r_is_writable)
5606 {
5607   bool is_dirty = false;
5608   bool is_writable = false;
5609 
5610   BLI_mutex_lock(image_mutex);
5611   if (image->cache != NULL) {
5612     struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);
5613 
5614     while (!IMB_moviecacheIter_done(iter)) {
5615       ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
5616       if (ibuf->userflags & IB_BITMAPDIRTY) {
5617         is_writable = BKE_image_buffer_format_writable(ibuf);
5618         is_dirty = true;
5619         break;
5620       }
5621       IMB_moviecacheIter_step(iter);
5622     }
5623     IMB_moviecacheIter_free(iter);
5624   }
5625   BLI_mutex_unlock(image_mutex);
5626 
5627   if (r_is_writable) {
5628     *r_is_writable = is_writable;
5629   }
5630 
5631   return is_dirty;
5632 }
5633 
BKE_image_is_dirty(Image * image)5634 bool BKE_image_is_dirty(Image *image)
5635 {
5636   return BKE_image_is_dirty_writable(image, NULL);
5637 }
5638 
BKE_image_mark_dirty(Image * UNUSED (image),ImBuf * ibuf)5639 void BKE_image_mark_dirty(Image *UNUSED(image), ImBuf *ibuf)
5640 {
5641   ibuf->userflags |= IB_BITMAPDIRTY;
5642 }
5643 
BKE_image_buffer_format_writable(ImBuf * ibuf)5644 bool BKE_image_buffer_format_writable(ImBuf *ibuf)
5645 {
5646   ImageFormatData im_format;
5647   ImbFormatOptions options_dummy;
5648   BKE_imbuf_to_image_format(&im_format, ibuf);
5649   return (BKE_image_imtype_to_ftype(im_format.imtype, &options_dummy) == ibuf->ftype);
5650 }
5651 
BKE_image_file_format_set(Image * image,int ftype,const ImbFormatOptions * options)5652 void BKE_image_file_format_set(Image *image, int ftype, const ImbFormatOptions *options)
5653 {
5654   BLI_mutex_lock(image_mutex);
5655   if (image->cache != NULL) {
5656     struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);
5657 
5658     while (!IMB_moviecacheIter_done(iter)) {
5659       ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
5660       ibuf->ftype = ftype;
5661       ibuf->foptions = *options;
5662       IMB_moviecacheIter_step(iter);
5663     }
5664     IMB_moviecacheIter_free(iter);
5665   }
5666   BLI_mutex_unlock(image_mutex);
5667 }
5668 
BKE_image_has_loaded_ibuf(Image * image)5669 bool BKE_image_has_loaded_ibuf(Image *image)
5670 {
5671   bool has_loaded_ibuf = false;
5672 
5673   BLI_mutex_lock(image_mutex);
5674   if (image->cache != NULL) {
5675     struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);
5676 
5677     while (!IMB_moviecacheIter_done(iter)) {
5678       has_loaded_ibuf = true;
5679       break;
5680     }
5681     IMB_moviecacheIter_free(iter);
5682   }
5683   BLI_mutex_unlock(image_mutex);
5684 
5685   return has_loaded_ibuf;
5686 }
5687 
5688 /**
5689  * References the result, #BKE_image_release_ibuf is to be called to de-reference.
5690  * Use lock=NULL when calling #BKE_image_release_ibuf().
5691  */
BKE_image_get_ibuf_with_name(Image * image,const char * name)5692 ImBuf *BKE_image_get_ibuf_with_name(Image *image, const char *name)
5693 {
5694   ImBuf *ibuf = NULL;
5695 
5696   BLI_mutex_lock(image_mutex);
5697   if (image->cache != NULL) {
5698     struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);
5699 
5700     while (!IMB_moviecacheIter_done(iter)) {
5701       ImBuf *current_ibuf = IMB_moviecacheIter_getImBuf(iter);
5702       if (STREQ(current_ibuf->name, name)) {
5703         ibuf = current_ibuf;
5704         IMB_refImBuf(ibuf);
5705         break;
5706       }
5707       IMB_moviecacheIter_step(iter);
5708     }
5709     IMB_moviecacheIter_free(iter);
5710   }
5711   BLI_mutex_unlock(image_mutex);
5712 
5713   return ibuf;
5714 }
5715 
5716 /**
5717  * References the result, #BKE_image_release_ibuf is to be called to de-reference.
5718  * Use lock=NULL when calling #BKE_image_release_ibuf().
5719  *
5720  * TODO(sergey): This is actually "get first item from the cache", which is
5721  *               not so much predictable. But using first loaded image buffer
5722  *               was also malicious logic and all the areas which uses this
5723  *               function are to be re-considered.
5724  */
BKE_image_get_first_ibuf(Image * image)5725 ImBuf *BKE_image_get_first_ibuf(Image *image)
5726 {
5727   ImBuf *ibuf = NULL;
5728 
5729   BLI_mutex_lock(image_mutex);
5730   if (image->cache != NULL) {
5731     struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);
5732 
5733     while (!IMB_moviecacheIter_done(iter)) {
5734       ibuf = IMB_moviecacheIter_getImBuf(iter);
5735       IMB_refImBuf(ibuf);
5736       break;
5737     }
5738     IMB_moviecacheIter_free(iter);
5739   }
5740   BLI_mutex_unlock(image_mutex);
5741 
5742   return ibuf;
5743 }
5744 
image_update_views_format(Image * ima,ImageUser * iuser)5745 static void image_update_views_format(Image *ima, ImageUser *iuser)
5746 {
5747   SceneRenderView *srv;
5748   ImageView *iv;
5749   Scene *scene = iuser->scene;
5750   const bool is_multiview = ((scene->r.scemode & R_MULTIVIEW) != 0) &&
5751                             ((ima->flag & IMA_USE_VIEWS) != 0);
5752 
5753   /* reset the image views */
5754   BKE_image_free_views(ima);
5755 
5756   if (!is_multiview) {
5757     /* nothing to do */
5758   }
5759   else if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
5760     const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
5761 
5762     for (int i = 0; i < 2; i++) {
5763       image_add_view(ima, names[i], ima->filepath);
5764     }
5765     return;
5766   }
5767   else {
5768     /* R_IMF_VIEWS_INDIVIDUAL */
5769     char prefix[FILE_MAX] = {'\0'};
5770     char *name = ima->filepath;
5771     const char *ext = NULL;
5772 
5773     BKE_scene_multiview_view_prefix_get(scene, name, prefix, &ext);
5774 
5775     if (prefix[0] == '\0') {
5776       BKE_image_free_views(ima);
5777       return;
5778     }
5779 
5780     /* create all the image views */
5781     for (srv = scene->r.views.first; srv; srv = srv->next) {
5782       if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
5783         char filepath[FILE_MAX];
5784         SNPRINTF(filepath, "%s%s%s", prefix, srv->suffix, ext);
5785         image_add_view(ima, srv->name, filepath);
5786       }
5787     }
5788 
5789     /* check if the files are all available */
5790     iv = ima->views.last;
5791     while (iv) {
5792       int file;
5793       char str[FILE_MAX];
5794 
5795       STRNCPY(str, iv->filepath);
5796       BLI_path_abs(str, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
5797 
5798       /* exists? */
5799       file = BLI_open(str, O_BINARY | O_RDONLY, 0);
5800       if (file == -1) {
5801         ImageView *iv_del = iv;
5802         iv = iv->prev;
5803         BLI_remlink(&ima->views, iv_del);
5804         MEM_freeN(iv_del);
5805       }
5806       else {
5807         iv = iv->prev;
5808         close(file);
5809       }
5810     }
5811 
5812     /* all good */
5813     if (!BKE_image_is_multiview(ima)) {
5814       BKE_image_free_views(ima);
5815     }
5816   }
5817 }
5818 
5819 /**************************** Render Slots ***************************/
5820 
BKE_image_add_renderslot(Image * ima,const char * name)5821 RenderSlot *BKE_image_add_renderslot(Image *ima, const char *name)
5822 {
5823   RenderSlot *slot = MEM_callocN(sizeof(RenderSlot), "Image new Render Slot");
5824   if (name && name[0]) {
5825     BLI_strncpy(slot->name, name, sizeof(slot->name));
5826   }
5827   else {
5828     int n = BLI_listbase_count(&ima->renderslots) + 1;
5829     BLI_snprintf(slot->name, sizeof(slot->name), "Slot %d", n);
5830   }
5831   BLI_addtail(&ima->renderslots, slot);
5832   return slot;
5833 }
5834 
BKE_image_remove_renderslot(Image * ima,ImageUser * iuser,int index)5835 bool BKE_image_remove_renderslot(Image *ima, ImageUser *iuser, int index)
5836 {
5837   if (index == ima->last_render_slot) {
5838     /* Don't remove render slot while rendering to it. */
5839     if (G.is_rendering) {
5840       return false;
5841     }
5842   }
5843 
5844   int num_slots = BLI_listbase_count(&ima->renderslots);
5845   if (index >= num_slots || num_slots == 1) {
5846     return false;
5847   }
5848 
5849   RenderSlot *remove_slot = BLI_findlink(&ima->renderslots, index);
5850   RenderSlot *current_slot = BLI_findlink(&ima->renderslots, ima->render_slot);
5851   RenderSlot *current_last_slot = BLI_findlink(&ima->renderslots, ima->last_render_slot);
5852 
5853   RenderSlot *next_slot;
5854   if (current_slot == remove_slot) {
5855     next_slot = BLI_findlink(&ima->renderslots, (index == num_slots - 1) ? index - 1 : index + 1);
5856   }
5857   else {
5858     next_slot = current_slot;
5859   }
5860 
5861   /* If the slot to be removed is the slot with the last render,
5862    * make another slot the last render slot. */
5863   if (remove_slot == current_last_slot) {
5864     /* Choose the currently selected slot unless that one is being removed,
5865      * in that case take the next one. */
5866     RenderSlot *next_last_slot;
5867     if (current_slot == remove_slot) {
5868       next_last_slot = next_slot;
5869     }
5870     else {
5871       next_last_slot = current_slot;
5872     }
5873 
5874     if (!iuser) {
5875       return false;
5876     }
5877     Render *re = RE_GetSceneRender(iuser->scene);
5878     if (!re) {
5879       return false;
5880     }
5881     RE_SwapResult(re, &current_last_slot->render);
5882     RE_SwapResult(re, &next_last_slot->render);
5883     current_last_slot = next_last_slot;
5884   }
5885 
5886   current_slot = next_slot;
5887 
5888   BLI_remlink(&ima->renderslots, remove_slot);
5889 
5890   ima->render_slot = BLI_findindex(&ima->renderslots, current_slot);
5891   ima->last_render_slot = BLI_findindex(&ima->renderslots, current_last_slot);
5892 
5893   if (remove_slot->render) {
5894     RE_FreeRenderResult(remove_slot->render);
5895   }
5896   MEM_freeN(remove_slot);
5897 
5898   return true;
5899 }
5900 
BKE_image_clear_renderslot(Image * ima,ImageUser * iuser,int index)5901 bool BKE_image_clear_renderslot(Image *ima, ImageUser *iuser, int index)
5902 {
5903   if (index == ima->last_render_slot) {
5904     if (!iuser) {
5905       return false;
5906     }
5907     if (G.is_rendering) {
5908       return false;
5909     }
5910     Render *re = RE_GetSceneRender(iuser->scene);
5911     if (!re) {
5912       return false;
5913     }
5914     RE_ClearResult(re);
5915     return true;
5916   }
5917 
5918   RenderSlot *slot = BLI_findlink(&ima->renderslots, index);
5919   if (!slot) {
5920     return false;
5921   }
5922   if (slot->render) {
5923     RE_FreeRenderResult(slot->render);
5924     slot->render = NULL;
5925   }
5926   return true;
5927 }
5928 
BKE_image_get_renderslot(Image * ima,int index)5929 RenderSlot *BKE_image_get_renderslot(Image *ima, int index)
5930 {
5931   /* Can be NULL for images without render slots. */
5932   return BLI_findlink(&ima->renderslots, index);
5933 }
5934