Last active
January 16, 2018 20:26
-
-
Save admsyn/54663fb81234aa987f8491c5d457fb84 to your computer and use it in GitHub Desktop.
NSView to ofTexture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void viewToTex(NSView * view, ofTexture& tex) { | |
// this is based on listing 11-3 at | |
// https://developer.apple.com/library/content/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_texturedata/opengl_texturedata.html | |
NSBitmapImageRep * bitmap = [view bitmapImageRepForCachingDisplayInRect:view.visibleRect]; | |
[view cacheDisplayInRect:view.visibleRect toBitmapImageRep:bitmap]; | |
glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.bytesPerRow / bitmap.samplesPerPixel); | |
glPixelStorei(GL_UNPACK_ALIGNMENT, 1); | |
if (tex.getTextureData().textureID == 0) { | |
throw std::runtime_error("texture isn't allocated"); | |
} | |
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, tex.getTextureData().textureID); | |
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR); | |
if(!bitmap.isPlanar && (bitmap.samplesPerPixel == 3 || bitmap.samplesPerPixel == 4)) { | |
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, | |
0, | |
bitmap.samplesPerPixel == 4 ? GL_RGBA8 : GL_RGB8, | |
bitmap.pixelsWide, | |
bitmap.pixelsHigh, | |
0, | |
bitmap.samplesPerPixel == 4 ? GL_RGBA : GL_RGB, | |
GL_UNSIGNED_BYTE, | |
bitmap.bitmapData); | |
} else { | |
throw std::runtime_error("unsupported bitmap data"); | |
} | |
// hail-mary reset back to default | |
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); | |
glPixelStorei(GL_UNPACK_ALIGNMENT, 4); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSView * view = ...; | |
renderedTexture = ofTexture(); | |
renderedTexture.allocate(512, 512, GL_RGBA); | |
viewToTex(view, renderedTexture); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment