1 module gfm.sdl2.sdlimage;
2 
3 import std.string;
4 
5 import derelict.util.exception,
6        derelict.sdl2.sdl,
7        derelict.sdl2.image;
8 
9 import std.experimental.logger;
10 
11 import gfm.sdl2.sdl,
12        gfm.sdl2.surface;
13 
14 /// Load images using SDL_image, a SDL companion library able to load various image formats.
15 final class SDLImage
16 {
17     public
18     {
19         /// Loads the SDL_image library.
20         /// SDL must be already initialized.
21         /// Throws: $(D SDL2Exception) on error.
22         this(SDL2 sdl2, int flags = IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF | IMG_INIT_WEBP)
23         {
24             _sdl2 = sdl2; // force loading of SDL first
25             _logger = sdl2._logger;
26             _SDLImageInitialized = false;
27 
28             try
29             {
30                 DerelictSDL2Image.load();
31             }
32             catch(DerelictException e)
33             {
34                 throw new SDL2Exception(e.msg);
35             }
36 
37             int inited = IMG_Init(flags);
38             _SDLImageInitialized = true;
39         }
40 
41         /// Releases the SDL resource.
42         ~this()
43         {
44             if (_SDLImageInitialized)
45             {
46                 debug ensureNotInGC("SDLImage");
47                 _SDLImageInitialized = false;
48                 IMG_Quit();
49             }
50         }
51 
52         /// Load an image.
53         /// Returns: A SDL surface with loaded content.
54         /// Throws: $(D SDL2Exception) on error.
55         SDL2Surface load(string path)
56         {
57             immutable(char)* pathz = toStringz(path);
58             SDL_Surface* surface = IMG_Load(pathz);
59             if (surface is null)
60                 throwSDL2ImageException("IMG_Load");
61 
62             return new SDL2Surface(_sdl2, surface, SDL2Surface.Owned.YES);
63         }
64     }
65 
66     private
67     {
68         Logger _logger;
69         SDL2 _sdl2;
70         bool _SDLImageInitialized;
71 
72         void throwSDL2ImageException(string callThatFailed)
73         {
74             string message = format("%s failed: %s", callThatFailed, getErrorString());
75             throw new SDL2Exception(message);
76         }
77 
78         const(char)[] getErrorString()
79         {
80             return fromStringz(IMG_GetError());
81         }
82     }
83 }