Add glTF PBR model loading
[opengl.git] / image.cpp
1 #include "image.hpp"
2 #include <ImageIO/ImageIO.h>
3
4 Image::Image(const std::string &path) {
5         CFStringRef str = CFStringCreateWithCString(NULL, path.c_str(), kCFStringEncodingUTF8);
6         CFURLRef url = CFURLCreateWithFileSystemPath(NULL, str, kCFURLPOSIXPathStyle, false);
7         CGImageSourceRef source = CGImageSourceCreateWithURL(url, NULL);
8         CGImageRef ref = CGImageSourceCreateImageAtIndex(source, 0, NULL);
9
10         _width = CGImageGetWidth(ref), _height = CGImageGetHeight(ref);
11         info = CGImageGetBitmapInfo(ref);
12         alphaInfo = CGImageGetAlphaInfo(ref);
13         colorSpace = CGImageGetColorSpace(ref);
14         bitsPerComponent = CGImageGetBitsPerComponent(ref);
15
16         dataRef = CGDataProviderCopyData(CGImageGetDataProvider(ref));
17         CGImageRelease(ref);
18
19 }
20
21 unsigned char *Image::data() const {
22         return (unsigned char*) CFDataGetBytePtr(dataRef);
23 }
24
25 GLfloat Image::width() const { return _width; }
26 GLfloat Image::height() const { return _height; }
27
28 // TODO: Properly implement this for both internal format + format
29 GLenum Image::format() const {
30         if (CGColorSpaceGetModel(colorSpace) == kCGColorSpaceModelMonochrome) {
31                 return GL_DEPTH_COMPONENT;
32         }
33         if (alphaInfo == kCGImageAlphaNone) {
34                 return GL_RGB;
35         }
36         return GL_RGBA;
37 }
38
39 GLint Image::internalFormat() const {
40         switch (format()) {
41                 case GL_DEPTH_COMPONENT: return GL_DEPTH_COMPONENT;
42                 case GL_RGB: return GL_RGB;
43                 default: return GL_RGBA;
44         }
45 }
46
47 GLenum Image::type() const {
48         bool isFloat = info & kCGBitmapFloatComponents;
49         if (isFloat) return GL_FLOAT;
50         return GL_UNSIGNED_BYTE;
51         
52         //TODO:
53         /* switch (bitsPerComponent) { */
54         /*      case 1: return GL_UNSIGNED_BYTE; */
55         /*      case 16: return GL_UNSIGNED_SHORT; */
56         /*  case 24: */ 
57 }
58
59 Image::~Image() { CFRelease(dataRef); }