|
| 1 | +#include "JPEGTexture.h" |
| 2 | +#include <cstdlib> |
| 3 | +#include <cstring> |
| 4 | +#include <gx2/mem.h> |
| 5 | +#include <turbojpeg.h> |
| 6 | + |
| 7 | +GX2Texture *JPEG_LoadTexture(std::span<uint8_t> data) { |
| 8 | + GX2Texture *texture = nullptr; |
| 9 | + |
| 10 | + tjhandle handle = tjInitDecompress(); |
| 11 | + if (!handle) { |
| 12 | + return nullptr; |
| 13 | + } |
| 14 | + |
| 15 | + int height; |
| 16 | + int width; |
| 17 | + int subsamp; |
| 18 | + int colorspace; |
| 19 | + if (tjDecompressHeader3(handle, |
| 20 | + data.data(), data.size(), |
| 21 | + &width, &height, |
| 22 | + &subsamp, &colorspace)) { |
| 23 | + goto error; |
| 24 | + } |
| 25 | + |
| 26 | + texture = static_cast<GX2Texture *>(std::malloc(sizeof(GX2Texture))); |
| 27 | + if (!texture) { |
| 28 | + goto error; |
| 29 | + } |
| 30 | + |
| 31 | + std::memset(texture, 0, sizeof(GX2Texture)); |
| 32 | + texture->surface.width = width; |
| 33 | + texture->surface.height = height; |
| 34 | + texture->surface.depth = 1; |
| 35 | + texture->surface.mipLevels = 1; |
| 36 | + texture->surface.format = GX2_SURFACE_FORMAT_UNORM_R8_G8_B8_A8; |
| 37 | + texture->surface.aa = GX2_AA_MODE1X; |
| 38 | + texture->surface.use = GX2_SURFACE_USE_TEXTURE; |
| 39 | + texture->surface.dim = GX2_SURFACE_DIM_TEXTURE_2D; |
| 40 | + texture->surface.tileMode = GX2_TILE_MODE_LINEAR_ALIGNED; |
| 41 | + texture->surface.swizzle = 0; |
| 42 | + texture->viewFirstMip = 0; |
| 43 | + texture->viewNumMips = 1; |
| 44 | + texture->viewFirstSlice = 0; |
| 45 | + texture->viewNumSlices = 1; |
| 46 | + texture->compMap = 0x0010203; |
| 47 | + GX2CalcSurfaceSizeAndAlignment(&texture->surface); |
| 48 | + GX2InitTextureRegs(texture); |
| 49 | + |
| 50 | + if (texture->surface.imageSize == 0) { |
| 51 | + goto error; |
| 52 | + } |
| 53 | + |
| 54 | + texture->surface.image = std::aligned_alloc(texture->surface.alignment, |
| 55 | + texture->surface.imageSize); |
| 56 | + if (!texture->surface.image) { |
| 57 | + goto error; |
| 58 | + } |
| 59 | + |
| 60 | + if (tjDecompress2(handle, |
| 61 | + data.data(), data.size(), |
| 62 | + static_cast<unsigned char *>(texture->surface.image), |
| 63 | + width, |
| 64 | + texture->surface.pitch * 4, |
| 65 | + height, |
| 66 | + TJPF_RGBA, |
| 67 | + 0)) { |
| 68 | + goto error; |
| 69 | + } |
| 70 | + |
| 71 | + tjDestroy(handle); |
| 72 | + |
| 73 | + GX2Invalidate(GX2_INVALIDATE_MODE_CPU | GX2_INVALIDATE_MODE_TEXTURE, |
| 74 | + texture->surface.image, texture->surface.imageSize); |
| 75 | + return texture; |
| 76 | + |
| 77 | +error: |
| 78 | + if (texture) { |
| 79 | + std::free(texture->surface.image); |
| 80 | + } |
| 81 | + std::free(texture); |
| 82 | + tjDestroy(handle); |
| 83 | + return nullptr; |
| 84 | +} |
0 commit comments