From 4ce0e0e10d0cb02173c246f56f5b751e8f85d070 Mon Sep 17 00:00:00 2001 From: Epicalert Date: Sat, 6 Feb 2021 21:19:33 +0800 Subject: [PATCH] Add support for webp textures This allows for models to use lossy textures with an alpha channel, none of the formats supported by stb_image.h could do this. --- CMakeLists.txt | 4 +++- cmake/FindWebP.cmake | 9 +++++++++ src/graphics.cpp | 23 ++++++++++++++++++++++- 3 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 cmake/FindWebP.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index e6159de..48c5c32 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,8 @@ cmake_minimum_required( VERSION 3.0 ) project( Facecam2D VERSION 0.1.0 ) +set( CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake ) find_package( libzip REQUIRED ) +find_package( WebP REQUIRED ) find_package( OpenCV REQUIRED ) message (STATUS "Found OpenCV at: " ${OpenCV_INCLUDE_DIRS} ) find_package( OpenGL REQUIRED ) @@ -43,4 +45,4 @@ add_executable( fc2d src/toml.c src/tomlcpp.cpp ) -target_link_libraries( fc2d ${OpenCV_LIBS} ${OPENGL_LIBRARIES} FreeGLUT::freeglut GLEW::glew zip ) +target_link_libraries( fc2d ${OpenCV_LIBS} ${OPENGL_LIBRARIES} ${WEBP_LIBRARIES} FreeGLUT::freeglut GLEW::glew zip ) diff --git a/cmake/FindWebP.cmake b/cmake/FindWebP.cmake new file mode 100644 index 0000000..7923d51 --- /dev/null +++ b/cmake/FindWebP.cmake @@ -0,0 +1,9 @@ +find_path( WEBP_INCLUDE_DIR NAMES webp/decode.h ) + +find_library( WEBP_LIBRARY NAMES webp PATHS /usr/lib /usr/lib64 /lib /lib64 /usr/local/lib ) + +if (WEBP_INCLUDE_DIR AND WEBP_LIBRARY) + set(WEBP_INCLUDE_DIR ${WEBP_INCLUDE_DIR}) + set(WEBP_LIBRARIES ${WEBP_LIBRARY}) + set( WEBP_FOUND "TRUE" ) +endif (WEBP_INCLUDE_DIR AND WEBP_LIBRARY) diff --git a/src/graphics.cpp b/src/graphics.cpp index f955894..4597032 100644 --- a/src/graphics.cpp +++ b/src/graphics.cpp @@ -8,6 +8,8 @@ #define STB_IMAGE_IMPLEMENTATION #include +#include + #include #include @@ -103,7 +105,26 @@ void initTexture (GLuint* texNum, unsigned char* buffer, size_t bufferLength) { glBindTexture(GL_TEXTURE_2D, *texNum); int x, y, channels; - GLubyte* pixels = stbi_load_from_memory(buffer, bufferLength, &x, &y, &channels, 4); + GLubyte* pixels; + int webp = WebPGetInfo(buffer, bufferLength, &x, &y); + if (webp) { + pixels = WebPDecodeRGBA(buffer, bufferLength, &x, &y); + } else { + //try stb_image (png, jpg, gif, etc) + pixels = stbi_load_from_memory(buffer, bufferLength, &x, &y, &channels, 4); + if (!pixels) { + std::cerr << "Corrupt or unsupported texture format!" << std::endl; + + GLubyte defaultPixels[] = + {255, 0, 255, 255, 0, 0, 0, 255, + 0, 0, 0, 255, 255, 0, 255, 255 }; + + pixels = defaultPixels; + x = 2; + y = 2; + } + } + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);