Guest User

Untitled

a guest
Oct 2nd, 2025
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.33 KB | Source Code | 0 0
  1. SDL_GPUTexture* Game::LoadGPUTextureFromFile(SDL_GPUDevice* device,
  2.                                              SDL_GPUCommandBuffer* cmd_buffer,
  3.                                              const char* file, Uint32 layer) {
  4.   SDL_Surface* texture_surface{IMG_Load(file)};
  5.   SDL_ConvertSurface(texture_surface, SDL_PIXELFORMAT_RGBA32);
  6.  
  7.   if (!texture_surface) {
  8.     SDL_Log("texture surface not loaded :( %s", SDL_GetError());
  9.   }
  10.   if (texture_surface == nullptr) {
  11.     SDL_Log("Failed to Load image '%s': %s", file, SDL_GetError());
  12.     exit_code_ = SDL_APP_FAILURE;
  13.     is_running_ = false;
  14.     return nullptr;
  15.   }
  16.  
  17.   std::size_t size = texture_surface->h * texture_surface->pitch;
  18.  
  19.   SDL_GPUTransferBufferCreateInfo transfer_buffer_info{
  20.       .usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD,
  21.       .size = static_cast<Uint32>(size)};
  22.  
  23.   SDL_GPUTransferBuffer* transfer_buffer{
  24.       SDL_CreateGPUTransferBuffer(device, &transfer_buffer_info)};
  25.   void* destination{SDL_MapGPUTransferBuffer(device, transfer_buffer, false)};
  26.   SDL_memcpy(destination, texture_surface->pixels, size);
  27.   SDL_UnmapGPUTransferBuffer(device, transfer_buffer);
  28.  
  29.   SDL_GPUTextureCreateInfo texture_info = {
  30.       .type = SDL_GPU_TEXTURETYPE_2D,
  31.       .format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM,
  32.       .usage = SDL_GPU_TEXTUREUSAGE_SAMPLER,
  33.       .width = static_cast<Uint32>(texture_surface->w),
  34.       .height = static_cast<Uint32>(texture_surface->h),
  35.       .layer_count_or_depth = 1,
  36.       .num_levels = 0,
  37.   };
  38.  
  39.   SDL_GPUTexture* texture{SDL_CreateGPUTexture(device, &texture_info)};
  40.   if (texture == nullptr) {
  41.     SDL_Log("Failed to Load GPUTexture: %s", SDL_GetError());
  42.     exit_code_ = SDL_APP_FAILURE;
  43.     is_running_ = false;
  44.     return nullptr;
  45.   }
  46.  
  47.   SDL_GPUTextureTransferInfo texture_transfer_buffer_info = {
  48.       .transfer_buffer = transfer_buffer};
  49.  
  50.   SDL_GPUTextureRegion texture_region{
  51.       .texture = texture,
  52.       .mip_level = 1,
  53.       .layer = layer,
  54.       .w = static_cast<Uint32>(texture_surface->w),
  55.       .h = static_cast<Uint32>(texture_surface->h),
  56.       .d = 1};
  57.  
  58.   SDL_GPUCopyPass* copy_pass{SDL_BeginGPUCopyPass(cmd_buffer)};
  59.  
  60.   SDL_UploadToGPUTexture(copy_pass, &texture_transfer_buffer_info,
  61.                          &texture_region, true);
  62.  
  63.   SDL_DestroySurface(texture_surface);
  64.  
  65.   return texture;
  66. }
Tags: cpp
Advertisement
Add Comment
Please, Sign In to add comment