Fix cross-platform rendering and optimize frame performance

Correct selection orientation, game-entry lifecycle, mounted NPCs, labels and skill panels. Add the native GPU scene path, resident geometry, bounded texture and Python caches, and collision broad phase.

Pin the independently maintained Metin2 SDK through a submodule and document reproducible setup. Include rendering regressions and macOS packaging improvements.

Validation: client Debug build and 12 targeted client tests passed; SDK build and all 14 SDK tests passed.
This commit is contained in:
shen
2026-10-11 17:55:53 -07:00
parent 08cc8865be
commit 281418f351
101 changed files with 6244 additions and 1877 deletions
+298
View File
@@ -0,0 +1,298 @@
#include "HardwareScene.h"
#include "shaders/SceneSpirv.h"
#include <cstring>
#include <algorithm>
#include <unordered_set>
namespace ava2 {
namespace {
constexpr const char* metal = R"(
#include <metal_stdlib>
using namespace metal;
struct Input { float4 position [[attribute(0)]]; float4 color [[attribute(1)]]; float2 uv [[attribute(2)]]; float4 normal [[attribute(3)]]; uint4 bones [[attribute(4)]]; float4 weights [[attribute(5)]]; };
struct Transform { float4 world[4]; float4 mvp[4]; float4 diffuse,ambient,emissive,lightDirection,lightAmbient,lightDiffuse,fogColor,fogParams,modes,skin; };
struct Output { float4 position [[position]]; float4 color; float2 uv; };
float4 rows(float4 p,float4 a,float4 b,float4 c,float4 d){return p.x*a+p.y*b+p.z*c+p.w*d;}
vertex Output scene_vertex(Input in [[stage_in]], uint instance [[instance_id]], constant Transform& header [[buffer(0)]], constant float4* palette [[buffer(1)]], device const Transform* instances [[buffer(2)]]) {
Transform t=header.modes.x>1.5 ? instances[instance] : header;
float4 p=in.position; float3 n=in.normal.xyz;
if(t.skin.x>0.5){float4 sp=0;float3 sn=0;float total=0;
for(uint i=0;i<4;++i)if(in.weights[i]>0 && in.bones[i]<uint(t.skin.x)){
uint b=in.bones[i]*4;float w=in.weights[i];
sp+=rows(p,palette[b],palette[b+1],palette[b+2],palette[b+3])*w;
sn+=rows(float4(n,0),palette[b],palette[b+1],palette[b+2],palette[b+3]).xyz*w;total+=w;
}if(total>0.0001){p=float4(sp.xyz,1);n=sn;}
}
float4 clip=p,c=in.color;
if(t.modes.x>0.5){
clip=rows(p,t.mvp[0],t.mvp[1],t.mvp[2],t.mvp[3]);c*=t.diffuse;
if(t.modes.y>0.5 && in.normal.w>0.5){float3 wn=rows(float4(n,0),t.world[0],t.world[1],t.world[2],t.world[3]).xyz;
float len=length(wn);if(len>0.00001)wn/=len;
float ndotl=max(0.f,dot(wn,t.lightDirection.xyz));c.rgb=clamp(t.emissive.rgb+t.ambient.rgb*t.lightAmbient.rgb+c.rgb*t.lightDiffuse.rgb*ndotl,0.f,1.f);
}
if(t.modes.z>0.5 && clip.w>0){float f=t.modes.z>1.5 ? exp(-clamp(clip.w*t.fogParams.x,0.f,10.f)) : clamp((t.fogParams.z-clip.w)/(t.fogParams.z-t.fogParams.y),0.f,1.f);c.rgb=mix(t.fogColor.rgb,c.rgb,f);}
if(t.modes.w>0.5)clip.z=0;
}
Output out;out.position=clip;out.color=c;out.uv=in.uv;return out;
}
fragment float4 scene_fragment(Output in [[stage_in]], texture2d<float> image [[texture(0)]], sampler sampling [[sampler(0)]], constant float4& params [[buffer(0)]]) {
float4 c=image.sample(sampling,in.uv)*in.color;
if(params.x>=0.0 && c.a<=params.x) discard_fragment();
if(params.y>0.5) c.a=1.0;
return c;
}
)";
}
HardwareScene::~HardwareScene() {
for (auto& [key,mesh]:resident_) {SDL_ReleaseGPUBuffer(device_,mesh.vertices);SDL_ReleaseGPUBuffer(device_,mesh.indices);}
if(instances_)SDL_ReleaseGPUBuffer(device_,instances_);
if(instanceTransfer_)SDL_ReleaseGPUTransferBuffer(device_,instanceTransfer_);
if(output_) SDL_DestroyTexture(output_);
for(auto& [key,t]:textures_) SDL_ReleaseGPUTexture(device_,t.texture);
for(auto& [key,p]:pipelines_) SDL_ReleaseGPUGraphicsPipeline(device_,p);
if(color_) SDL_ReleaseGPUTexture(device_,color_);
if(depth_) SDL_ReleaseGPUTexture(device_,depth_);
if(vertex_) SDL_ReleaseGPUShader(device_,vertex_);
if(fragment_) SDL_ReleaseGPUShader(device_,fragment_);
if(sampler_) SDL_ReleaseGPUSampler(device_,sampler_);
if(vertices_) SDL_ReleaseGPUBuffer(device_,vertices_);
if(indices_) SDL_ReleaseGPUBuffer(device_,indices_);
if(transfer_) SDL_ReleaseGPUTransferBuffer(device_,transfer_);
}
SDL_GPUTexture* HardwareScene::FindTexture(const std::string& key) {
auto it=textures_.find(key);if(it==textures_.end())return nullptr;
it->second.lastUsed=frame_+1;return it->second.texture;
}
SDL_GPUTexture* HardwareScene::Texture(const std::string& key,int width,int height,const void* rgba) {
if(auto* found=FindTexture(key))return found;
// Own uploads on the same queue as the 3D pass. SDL_Renderer's pending
// texture uploads are submitted at Present, after our custom command buffer.
SDL_GPUTextureCreateInfo ti{};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;ti.width=width;ti.height=height;ti.layer_count_or_depth=1;ti.num_levels=1;
auto* texture=SDL_CreateGPUTexture(device_,&ti);if(!texture)return nullptr;
SDL_GPUTransferBufferCreateInfo transferInfo{};transferInfo.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;transferInfo.size=width*height*4;
auto* transfer=SDL_CreateGPUTransferBuffer(device_,&transferInfo);
auto* bytes=transfer ? SDL_MapGPUTransferBuffer(device_,transfer,false) : nullptr;
auto* command=bytes ? SDL_AcquireGPUCommandBuffer(device_) : nullptr;
if(!bytes || !command) {
if(bytes)SDL_UnmapGPUTransferBuffer(device_,transfer);
if(transfer)SDL_ReleaseGPUTransferBuffer(device_,transfer);
SDL_ReleaseGPUTexture(device_,texture);return nullptr;
}
std::memcpy(bytes,rgba,transferInfo.size);SDL_UnmapGPUTransferBuffer(device_,transfer);
auto* copy=SDL_BeginGPUCopyPass(command);
if(!copy){SDL_CancelGPUCommandBuffer(command);SDL_ReleaseGPUTransferBuffer(device_,transfer);SDL_ReleaseGPUTexture(device_,texture);return nullptr;}
SDL_GPUTextureTransferInfo source{};source.transfer_buffer=transfer;source.pixels_per_row=width;source.rows_per_layer=height;
SDL_GPUTextureRegion dest{};dest.texture=texture;dest.w=width;dest.h=height;dest.d=1;
SDL_UploadToGPUTexture(copy,&source,&dest,false);SDL_EndGPUCopyPass(copy);
const bool submitted=SDL_SubmitGPUCommandBuffer(command);SDL_ReleaseGPUTransferBuffer(device_,transfer);
if(!submitted){SDL_ReleaseGPUTexture(device_,texture);return nullptr;}
const size_t imageBytes=size_t(width)*height*4;
textures_.emplace(key,TextureEntry{texture,imageBytes,frame_+1});textureBytes_+=imageBytes;++textureUploads_;return texture;
}
bool HardwareScene::Initialize(SDL_Renderer* renderer,int width,int height) {
if(!vertex_) {
bool msl=(SDL_GetGPUShaderFormats(device_) & SDL_GPU_SHADERFORMAT_MSL)!=0;
SDL_GPUShaderCreateInfo info{};
info.format=msl ? SDL_GPU_SHADERFORMAT_MSL : SDL_GPU_SHADERFORMAT_SPIRV;
info.stage=SDL_GPU_SHADERSTAGE_VERTEX; info.num_uniform_buffers=2;info.num_storage_buffers=1;
info.code=msl ? reinterpret_cast<const Uint8*>(metal) : scene_vert_spv;
info.code_size=msl ? std::strlen(metal) : sizeof(scene_vert_spv);
info.entrypoint=msl ? "scene_vertex" : "main";
vertex_=SDL_CreateGPUShader(device_,&info);
info.stage=SDL_GPU_SHADERSTAGE_FRAGMENT; info.num_samplers=1;info.num_uniform_buffers=1;info.num_storage_buffers=0;
info.code=msl ? reinterpret_cast<const Uint8*>(metal) : scene_frag_spv;
info.code_size=msl ? std::strlen(metal) : sizeof(scene_frag_spv);
info.entrypoint=msl ? "scene_fragment" : "main";
fragment_=SDL_CreateGPUShader(device_,&info);
SDL_GPUSamplerCreateInfo si{};
si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;
si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_REPEAT;
sampler_=SDL_CreateGPUSampler(device_,&si);
const Uint32 white=0xffffffff;
white_=Texture("__ava2_white",1,1,&white);
}
if(!vertex_ || !fragment_ || !sampler_ || !white_) return false;
if(width_!=width || height_!=height) {
if(output_) SDL_DestroyTexture(output_);
if(color_) SDL_ReleaseGPUTexture(device_,color_);
if(depth_) SDL_ReleaseGPUTexture(device_,depth_);
output_=nullptr;color_=depth_=nullptr;
SDL_GPUTextureCreateInfo ti{};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.width=width;ti.height=height;ti.layer_count_or_depth=1;ti.num_levels=1;
ti.format=SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;
color_=SDL_CreateGPUTexture(device_,&ti);
ti.format=SDL_GPU_TEXTUREFORMAT_D32_FLOAT;ti.usage=SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET;
depth_=SDL_CreateGPUTexture(device_,&ti);
if(!color_ || !depth_) return false;
auto props=SDL_CreateProperties();
SDL_SetPointerProperty(props,SDL_PROP_TEXTURE_CREATE_GPU_TEXTURE_POINTER,color_);
SDL_SetNumberProperty(props,SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER,SDL_PIXELFORMAT_ABGR8888);
SDL_SetNumberProperty(props,SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER,width);
SDL_SetNumberProperty(props,SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER,height);
output_=SDL_CreateTextureWithProperties(renderer,props);SDL_DestroyProperties(props);
if(!output_)return false;
// The target accumulates premultiplied colors. Transparent pixels keep
// the Python selection background and other existing 2D layers intact.
SDL_SetTextureBlendMode(output_,SDL_BLENDMODE_BLEND_PREMULTIPLIED);
width_=width;height_=height;
}
return true;
}
SDL_GPUGraphicsPipeline* HardwareScene::Pipeline(const HardwareBatch& b) {
unsigned key=b.cull|(b.depth<<3)|(b.depthWrite<<4)|(b.blend<<5)|(b.additive<<6);
auto it=pipelines_.find(key);if(it!=pipelines_.end())return it->second;
SDL_GPUGraphicsPipelineCreateInfo info{};
info.vertex_shader=vertex_;info.fragment_shader=fragment_;info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
SDL_GPUVertexBufferDescription buffer{};buffer.slot=0;buffer.pitch=sizeof(HardwareVertex);buffer.input_rate=SDL_GPU_VERTEXINPUTRATE_VERTEX;
SDL_GPUVertexAttribute attributes[6]{};
attributes[0]={0,0,SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4,0};
attributes[1]={1,0,SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4,16};
attributes[2]={2,0,SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2,32};
attributes[3]={3,0,SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4,40};
attributes[4]={4,0,SDL_GPU_VERTEXELEMENTFORMAT_UINT4,56};
attributes[5]={5,0,SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4,72};
info.vertex_input_state={&buffer,1,attributes,6};
info.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
info.rasterizer_state.front_face=SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE;
info.rasterizer_state.cull_mode=b.cull==1 ? SDL_GPU_CULLMODE_NONE : b.cull==2 ? SDL_GPU_CULLMODE_BACK : SDL_GPU_CULLMODE_FRONT;
info.depth_stencil_state.compare_op=SDL_GPU_COMPAREOP_LESS_OR_EQUAL;
info.depth_stencil_state.enable_depth_test=b.depth;
info.depth_stencil_state.enable_depth_write=b.depthWrite;
SDL_GPUColorTargetDescription target{};target.format=SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
auto& blend=target.blend_state;blend.enable_blend=b.blend||b.additive;
blend.src_color_blendfactor=SDL_GPU_BLENDFACTOR_SRC_ALPHA;
blend.dst_color_blendfactor=b.additive ? SDL_GPU_BLENDFACTOR_ONE : SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
blend.color_blend_op=blend.alpha_blend_op=SDL_GPU_BLENDOP_ADD;
blend.src_alpha_blendfactor=SDL_GPU_BLENDFACTOR_ONE;blend.dst_alpha_blendfactor=SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
info.target_info.color_target_descriptions=&target;info.target_info.num_color_targets=1;
info.target_info.has_depth_stencil_target=true;info.target_info.depth_stencil_format=SDL_GPU_TEXTUREFORMAT_D32_FLOAT;
auto* p=SDL_CreateGPUGraphicsPipeline(device_,&info);if(p)pipelines_.emplace(key,p);return p;
}
HardwareVertex MakeHardwareVertex(const Render3DDraw& mesh,size_t i) {
HardwareVertex v{};
v.position[0]=mesh.positions[i*3];v.position[1]=mesh.positions[i*3+1];v.position[2]=mesh.positions[i*3+2];v.position[3]=1;
uint32_t color=i<mesh.diffuse.size() ? mesh.diffuse[i] : 0xffffffff;
v.color[0]=((color>>16)&255)/255.f;v.color[1]=((color>>8)&255)/255.f;v.color[2]=(color&255)/255.f;v.color[3]=(color>>24)/255.f;
if(i*2+1<mesh.uv0.size()){v.uv[0]=mesh.uv0[i*2];v.uv[1]=mesh.uv0[i*2+1];}
if(i*3+2<mesh.normals.size()){for(int k=0;k<3;++k)v.normal[k]=mesh.normals[i*3+k];v.normal[3]=1;}
if(i*4+3<mesh.bone_indices.size() && i*4+3<mesh.bone_weights.size())for(int k=0;k<4;++k){v.bones[k]=mesh.bone_indices[i*4+k];v.weights[k]=mesh.bone_weights[i*4+k];}
return v;
}
HardwareScene::ResidentMesh* HardwareScene::Resident(const std::shared_ptr<const Render3DDraw>& geometry) {
auto it=resident_.find(geometry.get());
if(it!=resident_.end()){it->second.lastUsed=frame_;return &it->second;}
const auto& mesh=*geometry;
const size_t count=mesh.positions.size()/3;
if(!count || mesh.indices.empty())return nullptr;
for(auto index:mesh.indices)if(index>=count)return nullptr;
std::vector<HardwareVertex> packed;packed.reserve(count);
for(size_t i=0;i<count;++i)packed.push_back(MakeHardwareVertex(mesh,i));
const uint32_t vb=packed.size()*sizeof(HardwareVertex),ib=mesh.indices.size()*sizeof(uint32_t);
SDL_GPUBufferCreateInfo bi{};bi.usage=SDL_GPU_BUFFERUSAGE_VERTEX;bi.size=vb;
ResidentMesh r;r.source=geometry;r.vertices=SDL_CreateGPUBuffer(device_,&bi);
bi.usage=SDL_GPU_BUFFERUSAGE_INDEX;bi.size=ib;r.indices=SDL_CreateGPUBuffer(device_,&bi);
SDL_GPUTransferBufferCreateInfo ti{};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=vb+ib;
auto* transfer=SDL_CreateGPUTransferBuffer(device_,&ti);
auto* bytes=transfer ? static_cast<Uint8*>(SDL_MapGPUTransferBuffer(device_,transfer,false)) : nullptr;
auto* command=bytes && r.vertices && r.indices ? SDL_AcquireGPUCommandBuffer(device_) : nullptr;
if(!command){if(bytes)SDL_UnmapGPUTransferBuffer(device_,transfer);if(transfer)SDL_ReleaseGPUTransferBuffer(device_,transfer);if(r.vertices)SDL_ReleaseGPUBuffer(device_,r.vertices);if(r.indices)SDL_ReleaseGPUBuffer(device_,r.indices);return nullptr;}
std::memcpy(bytes,packed.data(),vb);std::memcpy(bytes+vb,mesh.indices.data(),ib);SDL_UnmapGPUTransferBuffer(device_,transfer);
auto* copy=SDL_BeginGPUCopyPass(command);
if(!copy){SDL_CancelGPUCommandBuffer(command);SDL_ReleaseGPUTransferBuffer(device_,transfer);SDL_ReleaseGPUBuffer(device_,r.vertices);SDL_ReleaseGPUBuffer(device_,r.indices);return nullptr;}
SDL_GPUTransferBufferLocation from{transfer,0};SDL_GPUBufferRegion to{r.vertices,0,vb};SDL_UploadToGPUBuffer(copy,&from,&to,false);
from.offset=vb;to={r.indices,0,ib};SDL_UploadToGPUBuffer(copy,&from,&to,false);SDL_EndGPUCopyPass(copy);
bool ok=SDL_SubmitGPUCommandBuffer(command);SDL_ReleaseGPUTransferBuffer(device_,transfer);
if(!ok){SDL_ReleaseGPUBuffer(device_,r.vertices);SDL_ReleaseGPUBuffer(device_,r.indices);return nullptr;}
r.count=mesh.indices.size();r.bytes=vb+ib;r.lastUsed=frame_;residentBytes_+=r.bytes;++residentUploads_;
return &resident_.emplace(geometry.get(),std::move(r)).first->second;
}
bool HardwareScene::Render(SDL_Renderer* renderer,int width,int height,const std::vector<HardwareVertex>& vertices,const std::vector<uint32_t>& indices,const std::vector<HardwareBatch>& batches) {
if(batches.empty())return true;
const auto tick=SDL_GetPerformanceCounter();++frame_;lastDrawCalls_=0;
if(!Initialize(renderer,width,height))return false;
if(textureBytes_>textureBudget_) {
std::unordered_set<SDL_GPUTexture*> activeTextures{white_};
for(const auto& b:batches)if(b.texture)activeTextures.insert(b.texture);
for(auto& [key,entry]:textures_)if(activeTextures.count(entry.texture))entry.lastUsed=frame_;
while(textureBytes_>textureBudget_) {
auto oldest=textures_.end();
for(auto it=textures_.begin();it!=textures_.end();++it) {
if(it->second.lastUsed>=frame_ || it->second.texture==white_)continue;
if(oldest==textures_.end() || it->second.lastUsed<oldest->second.lastUsed)oldest=it;
}
if(oldest==textures_.end())break; // active working set is protected, even above the soft budget
textureBytes_-=oldest->second.bytes;SDL_ReleaseGPUTexture(device_,oldest->second.texture);textures_.erase(oldest);
}
}
// Cached buffers can be released without waiting; SDL defers GPU destruction.
for(auto it=resident_.begin();it!=resident_.end();) {
if(residentBytes_>256u*1024u*1024u && it->second.lastUsed+2<frame_){
residentBytes_-=it->second.bytes;SDL_ReleaseGPUBuffer(device_,it->second.vertices);SDL_ReleaseGPUBuffer(device_,it->second.indices);it=resident_.erase(it);
}else ++it;
}
std::vector<ResidentMesh*> meshes;meshes.reserve(batches.size());
for(const auto& b:batches){if(!Pipeline(b))return false;auto* mesh=b.geometry ? Resident(b.geometry) : nullptr;if(b.geometry&&!mesh)return false;meshes.push_back(mesh);}
uint32_t vb=vertices.size()*sizeof(HardwareVertex),ib=indices.size()*sizeof(uint32_t);
lastDynamicBytes_=vb+ib;
if(vb>vertexBytes_||ib>indexBytes_) {
if(vertices_)SDL_ReleaseGPUBuffer(device_,vertices_);if(indices_)SDL_ReleaseGPUBuffer(device_,indices_);if(transfer_)SDL_ReleaseGPUTransferBuffer(device_,transfer_);
vertexBytes_=std::max(vb,vertexBytes_)*2;indexBytes_=std::max(ib,indexBytes_)*2;
SDL_GPUBufferCreateInfo bi{};bi.usage=SDL_GPU_BUFFERUSAGE_VERTEX;bi.size=vertexBytes_;vertices_=SDL_CreateGPUBuffer(device_,&bi);
bi.usage=SDL_GPU_BUFFERUSAGE_INDEX;bi.size=indexBytes_;indices_=SDL_CreateGPUBuffer(device_,&bi);
SDL_GPUTransferBufferCreateInfo ti{};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=vertexBytes_+indexBytes_;transfer_=SDL_CreateGPUTransferBuffer(device_,&ti);
}
if(vb || ib){
if(!vertices_||!indices_||!transfer_)return false;
auto* data=static_cast<Uint8*>(SDL_MapGPUTransferBuffer(device_,transfer_,true));if(!data)return false;
std::memcpy(data,vertices.data(),vb);std::memcpy(data+vb,indices.data(),ib);SDL_UnmapGPUTransferBuffer(device_,transfer_);
}
const uint32_t instanceSize=std::max<size_t>(1,batches.size())*sizeof(HardwareTransform);
if(instanceSize>instanceBytes_){
if(instances_)SDL_ReleaseGPUBuffer(device_,instances_);if(instanceTransfer_)SDL_ReleaseGPUTransferBuffer(device_,instanceTransfer_);
instanceBytes_=instanceSize*2;SDL_GPUBufferCreateInfo bi{};bi.usage=SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ;bi.size=instanceBytes_;instances_=SDL_CreateGPUBuffer(device_,&bi);
SDL_GPUTransferBufferCreateInfo ti{};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=instanceBytes_;instanceTransfer_=SDL_CreateGPUTransferBuffer(device_,&ti);
}
if(!instances_||!instanceTransfer_)return false;
auto* instData=static_cast<HardwareTransform*>(SDL_MapGPUTransferBuffer(device_,instanceTransfer_,true));if(!instData)return false;
for(size_t i=0;i<batches.size();++i)instData[i]=batches[i].transform;
SDL_UnmapGPUTransferBuffer(device_,instanceTransfer_);
if(!SDL_FlushRenderer(renderer))return false;
auto* cmd=SDL_AcquireGPUCommandBuffer(device_);if(!cmd)return false;
auto* copy=SDL_BeginGPUCopyPass(cmd);if(!copy){SDL_CancelGPUCommandBuffer(cmd);return false;}
SDL_GPUTransferBufferLocation source{};SDL_GPUBufferRegion dest{};
if(vb||ib){source={transfer_,0};dest={vertices_,0,vb};SDL_UploadToGPUBuffer(copy,&source,&dest,true);source.offset=vb;dest={indices_,0,ib};SDL_UploadToGPUBuffer(copy,&source,&dest,true);}
source={instanceTransfer_,0};dest={instances_,0,instanceSize};SDL_UploadToGPUBuffer(copy,&source,&dest,true);SDL_EndGPUCopyPass(copy);
SDL_GPUColorTargetInfo color{};color.texture=color_;color.clear_color={0,0,0,0};color.load_op=SDL_GPU_LOADOP_CLEAR;color.store_op=SDL_GPU_STOREOP_STORE;
SDL_GPUDepthStencilTargetInfo depth{};depth.texture=depth_;depth.clear_depth=1;depth.load_op=SDL_GPU_LOADOP_CLEAR;depth.store_op=SDL_GPU_STOREOP_DONT_CARE;depth.stencil_load_op=SDL_GPU_LOADOP_DONT_CARE;depth.stencil_store_op=SDL_GPU_STOREOP_DONT_CARE;
auto* pass=SDL_BeginGPURenderPass(cmd,&color,1,&depth);if(!pass){SDL_CancelGPUCommandBuffer(cmd);return false;}
SDL_BindGPUVertexStorageBuffers(pass,0,&instances_,1);
float palette[128*16]{};SDL_PushGPUVertexUniformData(cmd,1,palette,sizeof(palette));
for(size_t i=0;i<batches.size();) {
const auto& batch=batches[i];auto* mesh=meshes[i];
size_t count=1;
// Instance only compatible opaque resident meshes; preserve all translucent ordering.
if(mesh && !batch.blend && !batch.additive && batch.depthWrite && batch.transform.skin[0]==0 && batch.transform.modes[0]>0.5f)
while(i+count<batches.size()) {
const auto& next=batches[i+count];
if(meshes[i+count]!=mesh || next.texture!=batch.texture || next.cull!=batch.cull || next.depth!=batch.depth || next.depthWrite!=batch.depthWrite || next.blend || next.additive || next.alphaRef!=batch.alphaRef || next.transform.skin[0]!=0 || next.transform.modes[0]<.5f)break;
++count;
}
SDL_GPUBufferBinding binding{mesh ? mesh->vertices : vertices_,0};SDL_BindGPUVertexBuffers(pass,0,&binding,1);
binding.buffer=mesh ? mesh->indices : indices_;SDL_BindGPUIndexBuffer(pass,&binding,SDL_GPU_INDEXELEMENTSIZE_32BIT);
SDL_BindGPUGraphicsPipeline(pass,Pipeline(batch));
SDL_GPUTextureSamplerBinding texture{batch.texture ? batch.texture : white_,sampler_};SDL_BindGPUFragmentSamplers(pass,0,&texture,1);
float params[4]={batch.alphaRef,(!batch.blend&&!batch.additive)?1.f:0.f,0,0};SDL_PushGPUFragmentUniformData(cmd,0,params,sizeof(params));
auto transform=batch.transform;if(count>1)transform.modes[0]=2;
SDL_PushGPUVertexUniformData(cmd,0,&transform,sizeof(transform));
if(transform.skin[0]>0){std::fill(std::begin(palette),std::end(palette),0);std::copy_n(batch.palette.data(),std::min(batch.palette.size(),size_t(128*16)),palette);SDL_PushGPUVertexUniformData(cmd,1,palette,sizeof(palette));}
SDL_DrawGPUIndexedPrimitives(pass,batch.indexCount,count,mesh ? 0 : batch.firstIndex,0,count>1 ? i : 0);++lastDrawCalls_;i+=count;
}
SDL_EndGPURenderPass(pass);const auto beforeSubmit=SDL_GetPerformanceCounter();
if(!SDL_SubmitGPUCommandBuffer(cmd))return false;
static unsigned count=0;if(++count%120==0)SDL_Log("Resident GPU batches=%zu calls=%zu dynamic=%zu resident=%zu uploads=%zu encode=%.2f submit=%.2f ms",batches.size(),lastDrawCalls_,lastDynamicBytes_,residentBytes_,residentUploads_,1000.0*(beforeSubmit-tick)/SDL_GetPerformanceFrequency(),1000.0*(SDL_GetPerformanceCounter()-beforeSubmit)/SDL_GetPerformanceFrequency());
float w,h;SDL_Texture* target=SDL_GetRenderTarget(renderer);
if(target)SDL_GetTextureSize(target,&w,&h);else {int lw,lh;SDL_RendererLogicalPresentation lp;SDL_GetRenderLogicalPresentation(renderer,&lw,&lh,&lp);w=lw;h=lh;if(w<=0||h<=0){int pw,ph;SDL_GetRenderOutputSize(renderer,&pw,&ph);w=pw;h=ph;}}
SDL_FRect rect{0,0,w,h};return SDL_RenderTexture(renderer,output_,nullptr,&rect);
}
}