Compare commits
17
Commits
ff8667e3b9
...
b5a15871f4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5a15871f4 | ||
|
|
121f1a6307 | ||
|
|
699ac058f5 | ||
|
|
989f356c2e | ||
|
|
45644183b0 | ||
|
|
5079c71f2e | ||
|
|
aaee4c8f70 | ||
|
|
545cbb1e5d | ||
|
|
f03f63e700 | ||
|
|
d5333745c5 | ||
|
|
c85f9d815d | ||
|
|
4662e06b35 | ||
|
|
33552b9eeb | ||
|
|
837ccc2f31 | ||
|
|
1eccdc87d7 | ||
|
|
66955ef6ad | ||
|
|
a34b9c5a49 |
@@ -999,3 +999,48 @@ groups, independent reduced branch/leaf/frond LOD meshes, exact frond smoothing,
|
||||
billboard dimensions/component fades, newer SPT extension semantics, gameplay
|
||||
collision integration and GPU wind rendering. No DLL runtime or rendered visual
|
||||
parity comparison was performed. Original AVA2 data and server remain unchanged.
|
||||
|
||||
|
||||
### 2026-10-12 Per-frame CPU/GPU optimization pass
|
||||
|
||||
Implemented the prioritized per-frame findings, one commit per item (client
|
||||
1eccdc87..121f1a63, shared sdk a1b3938..53115d9):
|
||||
|
||||
- Render3D mesh cache sweeps only on growth; one shared GPU skinning palette per
|
||||
instance (pushed once per change); cached part->parent bone maps.
|
||||
- Text tails/labels: no per-frame codepoint vectors, show-state flag instead of
|
||||
list search, memoized widths, reused painter text instance.
|
||||
- Off-screen actor shadows culled; draw lists reserve last frame's peak.
|
||||
- Full mip chains for GPU scene textures (visible change: distant terrain/props
|
||||
no longer shimmer; sampler max_lod was zero before).
|
||||
- GPU tri-groups share one resident mesh and draw index sub-ranges.
|
||||
- Skins resolved once per skin change on the GPU draw cache; RenderSceneGPU
|
||||
resolves each texture once and sorts opaque draws by texture handle.
|
||||
- HardwareVertex packed 88 -> 48 bytes (UBYTE4_NORM colour, SHORT4_NORM normal,
|
||||
UBYTE4 bones, USHORT4_NORM weights); shaders unchanged.
|
||||
- Texture/mesh uploads staged and copied in the frame command buffer (one
|
||||
transfer buffer and copy pass per frame).
|
||||
- Every draw reads its transform from the instance storage buffer
|
||||
(firstInstance = batch index); the 288-byte uniform is pushed once per frame.
|
||||
Texture eviction sorts candidates once.
|
||||
- Bone lookup by a cached name index; attachments cache their bone index.
|
||||
- Python member-function names interned for PyCallClassMemberFunc (cache dropped
|
||||
by Py_AtExit across Py_Finalize/Py_Initialize).
|
||||
- Preview minimap radar redrawn only when its inputs change.
|
||||
|
||||
Verified: Debug macOS/Metal build, 50/50 CTests (including new regressions for
|
||||
resident index sub-ranges and GPU-cache skin changes). The current origin/main
|
||||
SpeedTree forest test needs SDK APIs not present in any pushed sdk revision, so
|
||||
verification used a local SDK shim; speedtree_forest_test was not built.
|
||||
|
||||
Not done, by decision: removing the offscreen colour target + blit (the 3D layer
|
||||
must composite premultiplied over SDL_Renderer 2D layers); baking text outlines
|
||||
(SDL already batches the five quads; colour would enter the cache key); partial
|
||||
palette pushes (risky on Vulkan/SPIR-V); sharing streams on the CPU-skinning
|
||||
tri-group path (would churn resident buffers); a per-frame light/fog uniform
|
||||
(light is per draw; fog is 32 bytes and nothing is pushed per draw any more).
|
||||
|
||||
Outstanding: no Vulkan/Android device run or frame-time capture for this pass;
|
||||
`frames*0.033f` / `frames/60` animation clocks are frame-based rather than real
|
||||
time; translucent depth sorting uses each draw's first vertex. Original AVA2
|
||||
data and the server are unchanged.
|
||||
|
||||
+1
-1
Submodule sdk updated: 86759bb726...53115d9ea2
@@ -3,6 +3,8 @@
|
||||
#include <Python.h>
|
||||
#include "PortPythonPointer.h"
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
|
||||
@@ -216,6 +218,52 @@ inline bool PyTuple_GetBoolean(PyObject* poArgs, int pos, bool* ret)
|
||||
return true;
|
||||
}
|
||||
|
||||
// Interned method-name strings: UI windows call OnUpdate/OnRender/... every frame, and
|
||||
// PyObject_GetAttrString would build a fresh PyString per call. The cache is dropped through
|
||||
// Py_AtExit, so a Py_Finalize/Py_Initialize cycle never sees stale objects.
|
||||
struct __PyNameHash
|
||||
{
|
||||
using is_transparent = void;
|
||||
size_t operator()(std::string_view s) const noexcept { return std::hash<std::string_view>{}(s); }
|
||||
};
|
||||
inline std::unordered_map<std::string, PyObject*, __PyNameHash, std::equal_to<>>& __PyNameCache()
|
||||
{
|
||||
static std::unordered_map<std::string, PyObject*, __PyNameHash, std::equal_to<>> cache;
|
||||
return cache;
|
||||
}
|
||||
inline bool& __PyNameCacheRegistered()
|
||||
{
|
||||
static bool registered = false;
|
||||
return registered;
|
||||
}
|
||||
inline void __PyClearNameCache()
|
||||
{
|
||||
// Runs inside Py_Finalize after the interpreter released its objects; only forget the pointers.
|
||||
__PyNameCache().clear();
|
||||
__PyNameCacheRegistered() = false;
|
||||
}
|
||||
inline PyObject* __PyInternedName(const char* c_szName)
|
||||
{
|
||||
auto& cache = __PyNameCache();
|
||||
auto it = cache.find(std::string_view(c_szName));
|
||||
if (it != cache.end())
|
||||
return it->second;
|
||||
if (!__PyNameCacheRegistered())
|
||||
{
|
||||
if (Py_AtExit(__PyClearNameCache) != 0)
|
||||
return nullptr;
|
||||
__PyNameCacheRegistered() = true;
|
||||
}
|
||||
PyObject* poName = PyString_InternFromString(c_szName);
|
||||
if (!poName)
|
||||
{
|
||||
PyErr_Clear();
|
||||
return nullptr;
|
||||
}
|
||||
cache.emplace(c_szName, poName); // the cache owns this reference
|
||||
return poName;
|
||||
}
|
||||
|
||||
inline bool __PyCallClassMemberFunc_ByCString(PyObject* poClass, const char* c_szFunc, PyObject* poArgs, PyObject** ppoRet)
|
||||
{
|
||||
if (!poClass)
|
||||
@@ -224,7 +272,8 @@ inline bool __PyCallClassMemberFunc_ByCString(PyObject* poClass, const char* c_s
|
||||
return false;
|
||||
}
|
||||
|
||||
PyObject * poFunc = PyObject_GetAttrString(poClass, (char *)c_szFunc);
|
||||
PyObject * poName = __PyInternedName(c_szFunc);
|
||||
PyObject * poFunc = poName ? PyObject_GetAttr(poClass, poName) : PyObject_GetAttrString(poClass, (char *)c_szFunc);
|
||||
if (!poFunc)
|
||||
{
|
||||
PyErr_Clear();
|
||||
|
||||
+39
-11
@@ -78,7 +78,20 @@ ava2::Render3DDraw BuildGroundShadowDraw(float x, float y, float z, float radius
|
||||
draw.lighting = false;
|
||||
draw.fog = false;
|
||||
|
||||
const int SEGMENTS = 16;
|
||||
constexpr int SEGMENTS = 16;
|
||||
static const auto ring = [] {
|
||||
std::array<std::array<float, 2>, SEGMENTS> r{};
|
||||
for (int i = 0; i < SEGMENTS; ++i) {
|
||||
float angle = (2.0f * 3.14159265358979323846f * static_cast<float>(i)) / static_cast<float>(SEGMENTS);
|
||||
r[i] = {std::cos(angle), std::sin(angle)};
|
||||
}
|
||||
return r;
|
||||
}();
|
||||
draw.positions.reserve((SEGMENTS + 1) * 3);
|
||||
draw.normals.reserve((SEGMENTS + 1) * 3);
|
||||
draw.uv0.reserve((SEGMENTS + 1) * 2);
|
||||
draw.diffuse.reserve(SEGMENTS + 1);
|
||||
draw.indices.reserve(SEGMENTS * 3);
|
||||
float center_y = terrain ? (terrain->GetHeightAtWorld(x, z) + 2.0f) : (y + 2.0f);
|
||||
|
||||
// Center vertex (index 0)
|
||||
@@ -93,9 +106,9 @@ ava2::Render3DDraw BuildGroundShadowDraw(float x, float y, float z, float radius
|
||||
draw.diffuse.push_back(0x90000000); // semi-transparent black center
|
||||
|
||||
for (int i = 0; i < SEGMENTS; ++i) {
|
||||
float angle = (2.0f * 3.14159265358979323846f * static_cast<float>(i)) / static_cast<float>(SEGMENTS);
|
||||
float px = x + std::cos(angle) * radius;
|
||||
float pz = z + std::sin(angle) * radius;
|
||||
const float c = ring[i][0], s = ring[i][1];
|
||||
float px = x + c * radius;
|
||||
float pz = z + s * radius;
|
||||
float py = terrain ? (terrain->GetHeightAtWorld(px, pz) + 2.0f) : (y + 2.0f);
|
||||
|
||||
draw.positions.push_back(px);
|
||||
@@ -104,8 +117,8 @@ ava2::Render3DDraw BuildGroundShadowDraw(float x, float y, float z, float radius
|
||||
draw.normals.push_back(0.0f);
|
||||
draw.normals.push_back(1.0f);
|
||||
draw.normals.push_back(0.0f);
|
||||
draw.uv0.push_back(0.5f + 0.5f * std::cos(angle));
|
||||
draw.uv0.push_back(0.5f + 0.5f * std::sin(angle));
|
||||
draw.uv0.push_back(0.5f + 0.5f * c);
|
||||
draw.uv0.push_back(0.5f + 0.5f * s);
|
||||
draw.diffuse.push_back(0x00000000); // fully transparent edge
|
||||
}
|
||||
|
||||
@@ -467,6 +480,7 @@ int main(int argc, char** argv) {
|
||||
std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)> gpu_scene_texture(nullptr, SDL_DestroyTexture);
|
||||
std::unique_ptr<SDL_Surface, decltype(&SDL_DestroySurface)> minimap_surface(nullptr, SDL_DestroySurface);
|
||||
std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)> minimap_texture(nullptr, SDL_DestroyTexture);
|
||||
std::array<float, 9> minimap_last_radar{};bool minimap_radar_valid = false; // redraw only when inputs move
|
||||
|
||||
ava2::TerrainHeightmap outdoor_terrain;
|
||||
std::string raw_path = "map/metin2_map_a1/001003/height.raw";
|
||||
@@ -1948,6 +1962,9 @@ const auto profileActiveStart = std::chrono::steady_clock::now();
|
||||
#else
|
||||
std::vector<ava2::Render3DDraw> draws;
|
||||
#endif
|
||||
// Draw count is stable frame to frame; reserve last frame's peak up front.
|
||||
static size_t draw_reserve = 0;
|
||||
draws.reserve(draw_reserve);
|
||||
const auto profileBuildStart = std::chrono::steady_clock::now();
|
||||
if (last_phase == "game") {
|
||||
// Update outdoor SkyBox, Clouds UV scrolling & dynamic environment
|
||||
@@ -2079,7 +2096,9 @@ const auto profileActiveStart = std::chrono::steady_clock::now();
|
||||
}
|
||||
}
|
||||
for (const auto& [vid, actorData] : ava2::NetworkActorManager::Instance().GetActorDict()) {
|
||||
if (actorData.m_pActorInstance && !actorData.m_isHidden) {
|
||||
// Same frustum test the actor's own draws use; its bounds cover the shadow.
|
||||
if (actorData.m_pActorInstance && !actorData.m_isHidden &&
|
||||
actorData.m_pActorInstance->IsVisible(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix())) {
|
||||
draws.push_back(BuildGroundShadowDraw(
|
||||
actorData.m_pActorInstance->GetX(),
|
||||
actorData.m_pActorInstance->GetY(),
|
||||
@@ -2138,7 +2157,7 @@ const auto profileActiveStart = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
apply_char_lighting(net_draws);
|
||||
for (auto& nd : net_draws) draws.push_back(std::move(nd));
|
||||
draws.insert(draws.end(), std::make_move_iterator(net_draws.begin()), std::make_move_iterator(net_draws.end()));
|
||||
|
||||
// Add Particle effects, projectiles, and weapon ribbon trails
|
||||
float camPos[3] = {eyeX, eyeY, eyeZ};
|
||||
@@ -2164,6 +2183,7 @@ const auto profileActiveStart = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
profileBuildMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now()-profileBuildStart).count();
|
||||
draw_reserve = std::max(draw_reserve, draws.size());
|
||||
if (!draws.empty()) {
|
||||
const auto profileRasterStart = std::chrono::steady_clock::now();
|
||||
uint32_t clear_col = (last_phase == "game") ? current_env.fog.GetColorUint() : 0x00000000;
|
||||
@@ -2210,14 +2230,22 @@ const auto profileActiveStart = std::chrono::steady_clock::now();
|
||||
if (!minimap_surface) {
|
||||
minimap_surface.reset(SDL_CreateSurface(128, 128, SDL_PIXELFORMAT_ARGB8888));
|
||||
minimap_texture.reset(SDL_CreateTexture(renderer.get(), SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 128, 128));
|
||||
minimap_radar_valid = false;
|
||||
if (minimap_texture) {
|
||||
SDL_SetTextureBlendMode(minimap_texture.get(), SDL_BLENDMODE_BLEND);
|
||||
}
|
||||
}
|
||||
if (minimap_surface && minimap_texture) {
|
||||
SDL_FillSurfaceRect(minimap_surface.get(), nullptr, 0x00000000);
|
||||
minimap_mgr.RenderRadar(minimap_surface.get(), 0, 0, 128, player_world_x, player_world_z, player_world_yaw);
|
||||
SDL_UpdateTexture(minimap_texture.get(), nullptr, minimap_surface->pixels, minimap_surface->pitch);
|
||||
// Redraw/upload only when the radar inputs move; a standing player re-presents the texture.
|
||||
const std::array<float, 9> radar{player_world_x, player_world_z, player_world_yaw,
|
||||
mob_dog.GetX(), mob_dog.GetZ(), mob_dog.IsDead() ? 1.f : 0.f,
|
||||
mob_metin.GetX(), mob_metin.GetZ(), mob_metin.IsDead() ? 1.f : 0.f};
|
||||
if (!minimap_radar_valid || radar != minimap_last_radar) {
|
||||
SDL_FillSurfaceRect(minimap_surface.get(), nullptr, 0x00000000);
|
||||
minimap_mgr.RenderRadar(minimap_surface.get(), 0, 0, 128, player_world_x, player_world_z, player_world_yaw);
|
||||
SDL_UpdateTexture(minimap_texture.get(), nullptr, minimap_surface->pixels, minimap_surface->pitch);
|
||||
minimap_last_radar = radar;minimap_radar_valid = true;
|
||||
}
|
||||
SDL_FRect dst = { static_cast<float>(screen_width - 132), 5.0f, 128.0f, 128.0f };
|
||||
SDL_RenderTexture(renderer.get(), minimap_texture.get(), nullptr, &dst);
|
||||
}
|
||||
|
||||
@@ -896,6 +896,8 @@ std::shared_ptr<ActorInstance> NetworkActorManager::GetActorInstance(uint32_t vi
|
||||
std::vector<Render3DDraw> NetworkActorManager::BuildDrawCommands(float animTime, const float* view, const float* proj) {
|
||||
(void)animTime;
|
||||
std::vector<Render3DDraw> allDraws;
|
||||
static size_t reserveHint = 0; // stable frame to frame
|
||||
allDraws.reserve(reserveHint);
|
||||
for (auto& [vid, actorData] : m_actors) {
|
||||
if (!actorData.m_pActorInstance || actorData.m_isHidden) continue;
|
||||
if (!IsMainActorVID(vid) && !actorData.m_pActorInstance->IsVisible(view,proj)
|
||||
@@ -920,6 +922,7 @@ std::vector<Render3DDraw> NetworkActorManager::BuildDrawCommands(float animTime,
|
||||
allDraws.push_back(std::move(d));
|
||||
}
|
||||
}
|
||||
reserveHint = std::max(reserveHint, allDraws.size());
|
||||
return allDraws;
|
||||
}
|
||||
|
||||
|
||||
@@ -280,6 +280,7 @@ bool ActorInstance::PlayMotion(MotionType type, bool loop) {
|
||||
m_animTime = 0.0f;
|
||||
m_motionDuration = std::max(0.1f, m_model->GetAnimationDuration());
|
||||
m_loopMotion = loop;
|
||||
m_model->SetAnimationLoop(loop, loop);
|
||||
|
||||
if (type == MotionType::Attack || type == MotionType::ComboAttack1 ||
|
||||
type == MotionType::ComboAttack2 || type == MotionType::ComboAttack3 ||
|
||||
|
||||
@@ -46,13 +46,16 @@ Render3DDraw ToRender3DDraw(gr2_render::Gr2MeshDraw&& mesh) {
|
||||
// Source owns immutable streams; converted geometry lives with frame/resident references.
|
||||
struct Entry {std::weak_ptr<const gr2_render::Gr2MeshDraw> source;std::weak_ptr<const Render3DDraw> converted;};
|
||||
static std::unordered_map<const gr2_render::Gr2MeshDraw*,Entry> cache;
|
||||
static size_t sweepAt=1024;
|
||||
auto& entry=cache[mesh.geometry.get()];
|
||||
if(entry.source.lock()==mesh.geometry)draw.geometry=entry.converted.lock();
|
||||
if(!draw.geometry){auto source=*mesh.geometry;draw.geometry=std::make_shared<const Render3DDraw>(ToRender3DDraw(std::move(source)));entry={mesh.geometry,draw.geometry};}
|
||||
if(cache.size()>1024) {
|
||||
// Sweep on growth only: with >1024 live meshes a fixed threshold rescans every call.
|
||||
if(cache.size()>sweepAt) {
|
||||
for(auto it=cache.begin();it!=cache.end();) {
|
||||
if(it->second.source.expired())it=cache.erase(it);else ++it;
|
||||
}
|
||||
sweepAt=std::max<size_t>(1024,cache.size()*2);
|
||||
}
|
||||
}
|
||||
draw.texture0 = std::move(mesh.texture0);
|
||||
@@ -62,9 +65,11 @@ Render3DDraw ToRender3DDraw(gr2_render::Gr2MeshDraw&& mesh) {
|
||||
draw.uv0 = std::move(mesh.uv0);
|
||||
draw.diffuse = std::move(mesh.diffuse);
|
||||
draw.indices = std::move(mesh.indices);
|
||||
draw.first_index = mesh.first_index;
|
||||
draw.index_count = mesh.index_count;
|
||||
draw.bone_indices = std::move(mesh.bone_indices);
|
||||
draw.bone_weights = std::move(mesh.bone_weights);
|
||||
draw.bone_matrices = std::move(mesh.bone_matrices);
|
||||
draw.palette = std::move(mesh.palette);
|
||||
draw.alpha_test = mesh.alpha_test;
|
||||
draw.alpha_ref = mesh.alpha_ref;
|
||||
draw.cull_mode = mesh.double_sided ? 1 : 2;
|
||||
@@ -99,6 +104,10 @@ float Gr2ModelInstance::GetAnimationDuration() const {
|
||||
return m_impl ? m_impl->GetAnimationDuration() : 0.0f;
|
||||
}
|
||||
|
||||
void Gr2ModelInstance::SetAnimationLoop(bool underflow_loop, bool overflow_loop) {
|
||||
if (m_impl) m_impl->SetAnimationLoop(underflow_loop, overflow_loop);
|
||||
}
|
||||
|
||||
bool Gr2ModelInstance::GetBoneWorldTransform(const std::string& bone_name, float* out_matrix, float animation_time) const {
|
||||
return m_impl ? m_impl->GetBoneWorldTransform(bone_name, out_matrix, animation_time) : false;
|
||||
}
|
||||
@@ -357,7 +366,8 @@ void Gr2SceneRenderer::SetFog(bool enable, uint32_t color, float density, float
|
||||
|
||||
void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw& draw) {
|
||||
const auto& mesh = draw.Mesh();
|
||||
if (!targetSurface || mesh.indices.size() < 3 || mesh.positions.size() < 9) return;
|
||||
const auto drawIndices = draw.Indices();
|
||||
if (!targetSurface || drawIndices.size < 3 || mesh.positions.size() < 9) return;
|
||||
|
||||
int vpWidth = m_viewport[2];
|
||||
int vpHeight = m_viewport[3];
|
||||
@@ -450,7 +460,7 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw
|
||||
diffuse_tex = GetTexture(draw.texture0);
|
||||
}
|
||||
|
||||
std::size_t num_tris = mesh.indices.size() / 3;
|
||||
std::size_t num_tris = drawIndices.size / 3;
|
||||
|
||||
auto make_screen_vertex = [&](TransformedVertex& v) {
|
||||
if (v.w_clip > 1e-5f) {
|
||||
@@ -670,9 +680,9 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw
|
||||
|
||||
constexpr float W_NEAR = 0.1f;
|
||||
for (std::size_t t = 0; t < num_tris; ++t) {
|
||||
uint32_t i0 = mesh.indices[t * 3 + 0];
|
||||
uint32_t i1 = mesh.indices[t * 3 + 1];
|
||||
uint32_t i2 = mesh.indices[t * 3 + 2];
|
||||
uint32_t i0 = drawIndices.data[t * 3 + 0];
|
||||
uint32_t i1 = drawIndices.data[t * 3 + 1];
|
||||
uint32_t i2 = drawIndices.data[t * 3 + 2];
|
||||
if (i0 >= num_verts || i1 >= num_verts || i2 >= num_verts) continue;
|
||||
|
||||
const auto& v0 = xverts[i0];
|
||||
@@ -819,7 +829,15 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
|
||||
DrawOrder ord;
|
||||
ord.draw = &d;
|
||||
const auto& sortedMesh = d.Mesh();
|
||||
if (!sortedMesh.positions.empty()) {
|
||||
if (d.Indices().size < 3 || sortedMesh.positions.size() < 9) continue;
|
||||
if (d.texture0.empty() && sortedMesh.diffuse.empty()) continue;
|
||||
if (m_hardware && !d.texture0.empty()) {
|
||||
ord.texture=m_hardware->FindTexture(d.texture0);
|
||||
if(!ord.texture){const auto* data=GetTexture(d.texture0);if(!data)continue;
|
||||
ord.texture=m_hardware->Texture(d.texture0,data->width,data->height,data->rgba.data());}
|
||||
if(!ord.texture)continue;
|
||||
}
|
||||
{
|
||||
float cx = sortedMesh.positions[0], cy = sortedMesh.positions[1], cz = sortedMesh.positions[2];
|
||||
float wx = cx * d.world[0] + cy * d.world[4] + cz * d.world[8] + d.world[12];
|
||||
float wy = cx * d.world[1] + cy * d.world[5] + cz * d.world[9] + d.world[13];
|
||||
@@ -849,7 +867,7 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
|
||||
if(m_hardware && a.priority==1) {
|
||||
if(a.draw->alpha_blend!=b.draw->alpha_blend)return !a.draw->alpha_blend;
|
||||
if(!a.draw->alpha_blend) {
|
||||
if(a.draw->texture0!=b.draw->texture0)return a.draw->texture0<b.draw->texture0;
|
||||
if(a.texture!=b.texture)return std::less<SDL_GPUTexture*>{}(a.texture,b.texture);
|
||||
if(a.draw->geometry.get()!=b.draw->geometry.get())return std::less<const Render3DDraw*>{}(a.draw->geometry.get(),b.draw->geometry.get());
|
||||
return a.depth<b.depth;
|
||||
}
|
||||
@@ -866,7 +884,8 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
|
||||
for (const auto& ord : m_scratchSortedDraws) {
|
||||
const auto& draw = *ord.draw;
|
||||
const auto& mesh = draw.Mesh();
|
||||
if (mesh.indices.size() < 3 || mesh.positions.size() < 9) continue;
|
||||
const auto drawIndices = draw.Indices();
|
||||
if (drawIndices.size < 3 || mesh.positions.size() < 9) continue;
|
||||
if (draw.texture0.empty() && mesh.diffuse.empty()) continue;
|
||||
|
||||
float mv[16];
|
||||
@@ -887,13 +906,7 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
|
||||
|
||||
size_t num_verts = mesh.positions.size() / 3;
|
||||
if (m_hardware) {
|
||||
SDL_GPUTexture* texture=nullptr;
|
||||
if (!draw.texture0.empty()) {
|
||||
texture=m_hardware->FindTexture(draw.texture0);
|
||||
if(!texture){const auto* data=GetTexture(draw.texture0);if(!data)continue;
|
||||
texture=m_hardware->Texture(draw.texture0,data->width,data->height,data->rgba.data());}
|
||||
if(!texture)continue;
|
||||
}
|
||||
SDL_GPUTexture* texture=ord.texture;
|
||||
HardwareBatch batch{};batch.texture=texture;batch.cull=draw.cull_mode;
|
||||
batch.depth=draw.z_enable;batch.depthWrite=draw.z_enable&&draw.z_write;
|
||||
batch.blend=draw.alpha_blend;batch.additive=draw.blend_mode==1;
|
||||
@@ -907,13 +920,15 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
|
||||
t.fogColor[0]=fog_r;t.fogColor[1]=fog_g;t.fogColor[2]=fog_b;
|
||||
t.fogParams[0]=m_fog_density;t.fogParams[1]=m_fog_near;t.fogParams[2]=m_fog_far;
|
||||
t.modes[0]=1;t.modes[1]=draw.lighting ? 1.f : 0.f;t.modes[2]=m_fog_enabled&&draw.fog ? (m_fog_exp ? 2.f : 1.f) : 0.f;t.modes[3]=draw.z_enable ? 0.f : 1.f;
|
||||
if(draw.gpu_skinning){batch.palette=draw.bone_matrices;t.skin[0]=batch.palette.size()/16;}
|
||||
batch.indexCount=mesh.indices.size();
|
||||
if(draw.gpu_skinning && draw.palette){batch.palette=draw.palette;t.skin[0]=batch.palette->size()/16;}
|
||||
batch.indexCount=drawIndices.size;
|
||||
batch.firstIndex=drawIndices.data-mesh.indices.data(); // resident buffers hold the whole mesh
|
||||
if(!batch.geometry) {
|
||||
const uint32_t base=m_hardwareVertices.size();batch.firstIndex=m_hardwareIndices.size();
|
||||
bool valid=true;for(auto index:mesh.indices)if(index>=num_verts){valid=false;break;}if(!valid)continue;
|
||||
const auto* first=drawIndices.data;const auto* last=first+drawIndices.size;
|
||||
if(std::any_of(first,last,[&](uint32_t index){return index>=num_verts;}))continue;
|
||||
for(size_t i=0;i<num_verts;++i)m_hardwareVertices.push_back(MakeHardwareVertex(mesh,i));
|
||||
for(auto index:mesh.indices)m_hardwareIndices.push_back(base+index);
|
||||
for(const auto* index=first;index!=last;++index)m_hardwareIndices.push_back(base+*index);
|
||||
}
|
||||
m_hardwareBatches.push_back(std::move(batch));continue;
|
||||
}
|
||||
@@ -997,8 +1012,8 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
|
||||
|
||||
m_scratchSdlVertices.clear();
|
||||
m_scratchSdlIndices.clear();
|
||||
m_scratchSdlVertices.reserve(mesh.indices.size());
|
||||
m_scratchSdlIndices.reserve(mesh.indices.size());
|
||||
m_scratchSdlVertices.reserve(drawIndices.size);
|
||||
m_scratchSdlIndices.reserve(drawIndices.size);
|
||||
auto& vertices = m_scratchSdlVertices;
|
||||
auto& indices = m_scratchSdlIndices;
|
||||
|
||||
@@ -1042,11 +1057,11 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
|
||||
return out;
|
||||
};
|
||||
|
||||
size_t num_tris = mesh.indices.size() / 3;
|
||||
size_t num_tris = drawIndices.size / 3;
|
||||
for (size_t t = 0; t < num_tris; ++t) {
|
||||
uint32_t i0 = mesh.indices[t * 3 + 0];
|
||||
uint32_t i1 = mesh.indices[t * 3 + 1];
|
||||
uint32_t i2 = mesh.indices[t * 3 + 2];
|
||||
uint32_t i0 = drawIndices.data[t * 3 + 0];
|
||||
uint32_t i1 = drawIndices.data[t * 3 + 1];
|
||||
uint32_t i2 = drawIndices.data[t * 3 + 2];
|
||||
if (i0 >= num_verts || i1 >= num_verts || i2 >= num_verts) continue;
|
||||
|
||||
const auto& v0 = xverts[i0];
|
||||
|
||||
@@ -25,6 +25,8 @@ public:
|
||||
// Load external animation (.gr2) to animate this model
|
||||
bool LoadExternalAnimation(const std::string& anim_filepath);
|
||||
float GetAnimationDuration() const;
|
||||
// Granny loop window: looping motions pass (true, true) so the seam samples across loops.
|
||||
void SetAnimationLoop(bool underflow_loop, bool overflow_loop);
|
||||
|
||||
// Bone queries & attachments
|
||||
bool GetBoneWorldTransform(const std::string& bone_name, float* out_matrix, float animation_time = -1.0f) const;
|
||||
@@ -146,6 +148,7 @@ private:
|
||||
int priority = 1;
|
||||
float depth = 0.0f;
|
||||
const Render3DDraw* draw = nullptr;
|
||||
SDL_GPUTexture* texture = nullptr; // resolved once per draw; also the opaque sort key
|
||||
};
|
||||
|
||||
float m_eye[3] = {0.0f, 0.0f, 0.0f};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "HardwareScene.h"
|
||||
#include "shaders/SceneSpirv.h"
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <algorithm>
|
||||
#include <unordered_set>
|
||||
@@ -13,7 +15,7 @@ struct Transform { float4 world[4]; float4 mvp[4]; float4 diffuse,ambient,emissi
|
||||
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;
|
||||
Transform t=header;if(header.modes.x>1.5)t=instances[instance]; // ?: across address spaces is ambiguous in MSL
|
||||
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)){
|
||||
@@ -65,29 +67,18 @@ SDL_GPUTexture* HardwareScene::FindTexture(const std::string& key) {
|
||||
}
|
||||
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.
|
||||
// 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); copied at the start of Render.
|
||||
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;
|
||||
// Full mip chain: minified terrain/props otherwise shimmer and read the whole level-0 texel footprint.
|
||||
// SDL_GenerateMipmapsForGPUTexture needs COLOR_TARGET usage.
|
||||
Uint32 levels=1;for(int extent=std::max(width,height);extent>1;extent>>=1)++levels;
|
||||
ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER|(levels>1 ? SDL_GPU_TEXTUREUSAGE_COLOR_TARGET : 0);ti.width=width;ti.height=height;ti.layer_count_or_depth=1;ti.num_levels=levels;
|
||||
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;
|
||||
const uint32_t size=uint32_t(width)*height*4;uint32_t offset=0;
|
||||
std::memcpy(Stage(size,offset),rgba,size);
|
||||
pending_.push_back({texture,nullptr,offset,size,uint32_t(width),uint32_t(height),levels>1});
|
||||
const size_t imageBytes=size_t(width)*height*4*(levels>1 ? 4 : 3)/3; // mip chain adds ~1/3
|
||||
textures_.emplace(key,TextureEntry{texture,imageBytes,frame_+1});textureBytes_+=imageBytes;++textureUploads_;return texture;
|
||||
}
|
||||
bool HardwareScene::Initialize(SDL_Renderer* renderer,int width,int height) {
|
||||
@@ -108,6 +99,7 @@ bool HardwareScene::Initialize(SDL_Renderer* renderer,int width,int height) {
|
||||
SDL_GPUSamplerCreateInfo si{};
|
||||
si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
|
||||
si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;
|
||||
si.max_lod=1000.f; // zero-initialized max_lod would clamp sampling to level 0
|
||||
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;
|
||||
@@ -147,11 +139,11 @@ SDL_GPUGraphicsPipeline* HardwareScene::Pipeline(const HardwareBatch& b) {
|
||||
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};
|
||||
attributes[1]={1,0,SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM,offsetof(HardwareVertex,color)};
|
||||
attributes[2]={2,0,SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2,offsetof(HardwareVertex,uv)};
|
||||
attributes[3]={3,0,SDL_GPU_VERTEXELEMENTFORMAT_SHORT4_NORM,offsetof(HardwareVertex,normal)};
|
||||
attributes[4]={4,0,SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4,offsetof(HardwareVertex,bones)};
|
||||
attributes[5]={5,0,SDL_GPU_VERTEXELEMENTFORMAT_USHORT4_NORM,offsetof(HardwareVertex,weights)};
|
||||
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;
|
||||
@@ -173,12 +165,52 @@ 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;
|
||||
v.color[0]=uint8_t(color>>16);v.color[1]=uint8_t(color>>8);v.color[2]=uint8_t(color);v.color[3]=uint8_t(color>>24);
|
||||
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];}
|
||||
if(i*3+2<mesh.normals.size()){
|
||||
// The shader renormalises after the (linear) skin/world transform, so storing the unit
|
||||
// direction keeps lighting identical while fitting SNORM.
|
||||
const float* n=&mesh.normals[i*3];const float len=std::sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);
|
||||
if(len>1e-12f)for(int k=0;k<3;++k)v.normal[k]=int16_t(std::lround(std::clamp(n[k]/len,-1.f,1.f)*32767.f));
|
||||
v.normal[3]=32767;
|
||||
}
|
||||
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]=uint16_t(std::lround(std::clamp(mesh.bone_weights[i*4+k],0.f,1.f)*65535.f));}
|
||||
return v;
|
||||
}
|
||||
uint8_t* HardwareScene::Stage(uint32_t size,uint32_t& offset) {
|
||||
offset=uint32_t((pendingBytes_.size()+15)&~size_t(15)); // texel/placement-friendly offsets
|
||||
pendingBytes_.resize(offset+size);return pendingBytes_.data()+offset;
|
||||
}
|
||||
void HardwareScene::DropPending(const void* resource) {
|
||||
pending_.erase(std::remove_if(pending_.begin(),pending_.end(),[&](const PendingUpload& upload){
|
||||
return upload.texture==resource || upload.buffer==resource;}),pending_.end());
|
||||
}
|
||||
bool HardwareScene::FlushUploads(SDL_GPUCommandBuffer* command) {
|
||||
if(pending_.empty())return true;
|
||||
SDL_GPUTransferBufferCreateInfo ti{};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=uint32_t(pendingBytes_.size());
|
||||
auto* transfer=SDL_CreateGPUTransferBuffer(device_,&ti);
|
||||
auto* bytes=transfer ? SDL_MapGPUTransferBuffer(device_,transfer,false) : nullptr;
|
||||
if(!bytes){if(transfer)SDL_ReleaseGPUTransferBuffer(device_,transfer);return false;}
|
||||
std::memcpy(bytes,pendingBytes_.data(),pendingBytes_.size());SDL_UnmapGPUTransferBuffer(device_,transfer);
|
||||
auto* copy=SDL_BeginGPUCopyPass(command);if(!copy){SDL_ReleaseGPUTransferBuffer(device_,transfer);return false;}
|
||||
for(const auto& upload:pending_) {
|
||||
if(upload.texture) {
|
||||
SDL_GPUTextureTransferInfo source{};source.transfer_buffer=transfer;source.offset=upload.offset;source.pixels_per_row=upload.width;source.rows_per_layer=upload.height;
|
||||
SDL_GPUTextureRegion dest{};dest.texture=upload.texture;dest.w=upload.width;dest.h=upload.height;dest.d=1;
|
||||
SDL_UploadToGPUTexture(copy,&source,&dest,false);
|
||||
} else {
|
||||
SDL_GPUTransferBufferLocation from{transfer,upload.offset};SDL_GPUBufferRegion to{upload.buffer,0,upload.size};
|
||||
SDL_UploadToGPUBuffer(copy,&from,&to,false);
|
||||
}
|
||||
}
|
||||
SDL_EndGPUCopyPass(copy);
|
||||
for(const auto& upload:pending_)if(upload.texture && upload.mipmaps)SDL_GenerateMipmapsForGPUTexture(command,upload.texture);
|
||||
SDL_ReleaseGPUTransferBuffer(device_,transfer); // released once the command buffer completes
|
||||
pending_.clear();pendingBytes_.clear();
|
||||
if(pendingBytes_.capacity()>64u*1024u*1024u)pendingBytes_.shrink_to_fit(); // drop a map-load burst
|
||||
return true;
|
||||
}
|
||||
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;}
|
||||
@@ -186,24 +218,16 @@ HardwareScene::ResidentMesh* HardwareScene::Resident(const std::shared_ptr<const
|
||||
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);
|
||||
const uint32_t vb=count*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;}
|
||||
if(!r.vertices || !r.indices){if(r.vertices)SDL_ReleaseGPUBuffer(device_,r.vertices);if(r.indices)SDL_ReleaseGPUBuffer(device_,r.indices);return nullptr;}
|
||||
uint32_t offset=0;auto* packed=Stage(vb,offset);
|
||||
for(size_t i=0;i<count;++i){const auto vertex=MakeHardwareVertex(mesh,i);std::memcpy(packed+i*sizeof(vertex),&vertex,sizeof(vertex));}
|
||||
pending_.push_back({nullptr,r.vertices,offset,vb});
|
||||
std::memcpy(Stage(ib,offset),mesh.indices.data(),ib);
|
||||
pending_.push_back({nullptr,r.indices,offset,ib});
|
||||
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;
|
||||
}
|
||||
@@ -215,20 +239,20 @@ bool HardwareScene::Render(SDL_Renderer* renderer,int width,int height,const std
|
||||
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);
|
||||
// Oldest inactive images first; the active working set is protected, even above the soft budget.
|
||||
std::vector<decltype(textures_)::iterator> candidates;
|
||||
for(auto it=textures_.begin();it!=textures_.end();++it)
|
||||
if(it->second.lastUsed<frame_ && it->second.texture!=white_)candidates.push_back(it);
|
||||
std::sort(candidates.begin(),candidates.end(),[](const auto& a,const auto& b){return a->second.lastUsed<b->second.lastUsed;});
|
||||
for(auto oldest:candidates) {
|
||||
if(textureBytes_<=textureBudget_)break;
|
||||
textureBytes_-=oldest->second.bytes;DropPending(oldest->second.texture);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);
|
||||
residentBytes_-=it->second.bytes;DropPending(it->second.vertices);DropPending(it->second.indices);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());
|
||||
@@ -259,15 +283,22 @@ bool HardwareScene::Render(SDL_Renderer* renderer,int width,int height,const std
|
||||
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;}
|
||||
if(!FlushUploads(cmd)){SDL_CancelGPUCommandBuffer(cmd);return false;}
|
||||
// Resource uploads are recorded now; on failure submit rather than cancel so they still land.
|
||||
auto* copy=SDL_BeginGPUCopyPass(cmd);if(!copy){SDL_SubmitGPUCommandBuffer(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;}
|
||||
auto* pass=SDL_BeginGPURenderPass(cmd,&color,1,&depth);if(!pass){SDL_SubmitGPUCommandBuffer(cmd);return false;}
|
||||
SDL_BindGPUVertexStorageBuffers(pass,0,&instances_,1);
|
||||
float palette[128*16]{};SDL_PushGPUVertexUniformData(cmd,1,palette,sizeof(palette));
|
||||
// Every draw reads its transform from the instance storage buffer (firstInstance = batch index),
|
||||
// so the uniform header is pushed once per frame instead of 288 bytes per draw.
|
||||
HardwareTransform header{};header.modes[0]=2;SDL_PushGPUVertexUniformData(cmd,0,&header,sizeof(header));
|
||||
float pushedParams[4]={-2,-1,0,0}; // never a real alphaRef/opaque pair
|
||||
const std::vector<float>* pushedPalette=nullptr; // draws of one instance share a palette; push once
|
||||
for(size_t i=0;i<batches.size();) {
|
||||
const auto& batch=batches[i];auto* mesh=meshes[i];
|
||||
size_t count=1;
|
||||
@@ -275,18 +306,18 @@ bool HardwareScene::Render(SDL_Renderer* renderer,int width,int height,const std
|
||||
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;
|
||||
if(meshes[i+count]!=mesh || next.firstIndex!=batch.firstIndex || next.indexCount!=batch.indexCount || 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;
|
||||
float params[4]={batch.alphaRef,(!batch.blend&&!batch.additive)?1.f:0.f,0,0};
|
||||
if(std::memcmp(params,pushedParams,sizeof(params))!=0){std::memcpy(pushedParams,params,sizeof(params));SDL_PushGPUFragmentUniformData(cmd,0,params,sizeof(params));}
|
||||
const auto& transform=batch.transform;
|
||||
if(transform.skin[0]>0 && batch.palette && batch.palette.get()!=pushedPalette){pushedPalette=batch.palette.get();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,batch.firstIndex,0,i);++lastDrawCalls_;i+=count;
|
||||
}
|
||||
SDL_EndGPURenderPass(pass);const auto beforeSubmit=SDL_GetPerformanceCounter();
|
||||
if(!SDL_SubmitGPUCommandBuffer(cmd))return false;
|
||||
|
||||
@@ -7,12 +7,16 @@
|
||||
#include <memory>
|
||||
#include "RenderCommands3D.h"
|
||||
namespace ava2 {
|
||||
// 48-byte vertex; the GPU expands the packed fields to the same float/uint shader inputs.
|
||||
struct HardwareVertex {
|
||||
float position[4], color[4], uv[2];
|
||||
float normal[4]{};
|
||||
uint32_t bones[4]{};
|
||||
float weights[4]{};
|
||||
float position[4]; // FLOAT4 (raw-vertex batches may carry w != 1)
|
||||
uint8_t color[4]; // UBYTE4_NORM, RGBA
|
||||
float uv[2]; // FLOAT2
|
||||
int16_t normal[4]{}; // SHORT4_NORM, unit xyz; w=1 when the vertex has a normal
|
||||
uint8_t bones[4]{}; // UBYTE4 (palette holds at most 128 bones)
|
||||
uint16_t weights[4]{}; // USHORT4_NORM
|
||||
};
|
||||
static_assert(sizeof(HardwareVertex)==48);
|
||||
struct HardwareTransform {
|
||||
float world[16]{}, mvp[16]{};
|
||||
float diffuse[4]{}, ambient[4]{}, emissive[4]{};
|
||||
@@ -31,7 +35,7 @@ struct HardwareBatch {
|
||||
float alphaRef;
|
||||
HardwareTransform transform{};
|
||||
std::shared_ptr<const Render3DDraw> geometry;
|
||||
std::vector<float> palette;
|
||||
std::shared_ptr<const std::vector<float>> palette;
|
||||
|
||||
};
|
||||
class HardwareScene {
|
||||
@@ -58,6 +62,17 @@ private:
|
||||
uint64_t lastUsed=0;
|
||||
};
|
||||
ResidentMesh* Resident(const std::shared_ptr<const Render3DDraw>& geometry);
|
||||
// New textures/meshes are staged on the CPU and copied in the next Render command buffer,
|
||||
// one transfer buffer and copy pass per frame instead of one submit per resource.
|
||||
struct PendingUpload {
|
||||
SDL_GPUTexture* texture=nullptr; SDL_GPUBuffer* buffer=nullptr;
|
||||
uint32_t offset=0, size=0, width=0, height=0; bool mipmaps=false;
|
||||
};
|
||||
uint8_t* Stage(uint32_t size, uint32_t& offset);
|
||||
void DropPending(const void* resource);
|
||||
bool FlushUploads(SDL_GPUCommandBuffer* command);
|
||||
std::vector<uint8_t> pendingBytes_;
|
||||
std::vector<PendingUpload> pending_;
|
||||
std::unordered_map<const Render3DDraw*,ResidentMesh> resident_;
|
||||
uint64_t frame_=0;
|
||||
size_t residentBytes_=0, residentUploads_=0, lastDrawCalls_=0, lastDynamicBytes_=0;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -52,7 +53,6 @@ struct Render3DDraw {
|
||||
command.indices.clear(); command.indices.shrink_to_fit();
|
||||
command.bone_indices.clear(); command.bone_indices.shrink_to_fit();
|
||||
command.bone_weights.clear(); command.bone_weights.shrink_to_fit();
|
||||
command.bone_matrices.clear(); command.bone_matrices.shrink_to_fit();
|
||||
command.geometry = std::make_shared<const Render3DDraw>(std::move(source));
|
||||
return command;
|
||||
}
|
||||
@@ -79,11 +79,20 @@ struct Render3DDraw {
|
||||
std::vector<float> uv1; // 2 floats (u, v) per vertex
|
||||
std::vector<std::uint32_t> diffuse; // 0xAARRGGBB per vertex
|
||||
std::vector<std::uint32_t> indices; // Triangle list indices (3 per triangle)
|
||||
// Sub-range of Mesh().indices this draw covers; tri-groups of one mesh share geometry.
|
||||
std::uint32_t first_index = 0;
|
||||
std::uint32_t index_count = UINT32_MAX; // UINT32_MAX = through the end
|
||||
struct IndexSpan { const std::uint32_t* data; std::size_t size; };
|
||||
IndexSpan Indices() const {
|
||||
const auto& all = Mesh().indices;
|
||||
const std::size_t first = std::min<std::size_t>(first_index, all.size());
|
||||
return {all.data() + first, std::min<std::size_t>(index_count, all.size() - first)};
|
||||
}
|
||||
|
||||
// Skeletal skinning streams
|
||||
std::vector<std::uint8_t> bone_indices; // 4 uint8 per vertex
|
||||
std::vector<float> bone_weights; // 4 floats per vertex
|
||||
std::vector<float> bone_matrices; // 16 floats per bone (palette)
|
||||
std::shared_ptr<const std::vector<float>> palette; // GPU skinning, 16 floats per bone; shared per instance
|
||||
|
||||
// Render states
|
||||
bool z_enable = true;
|
||||
|
||||
@@ -132,7 +132,7 @@ void TextTailManager::ShowCharacterTextTail(uint32_t vid) {
|
||||
if (it == m_characterMap.end()) return;
|
||||
|
||||
auto tail = it->second;
|
||||
if (std::find(m_characterList.begin(), m_characterList.end(), tail) == m_characterList.end()) {
|
||||
if (!tail->isShowing) { // isShowing <=> in m_characterList
|
||||
tail->isShowing = true;
|
||||
m_characterList.push_back(tail);
|
||||
}
|
||||
@@ -200,7 +200,7 @@ void TextTailManager::ShowItemTextTail(uint32_t vid) {
|
||||
if (it == m_itemMap.end()) return;
|
||||
|
||||
auto tail = it->second;
|
||||
if (std::find(m_itemList.begin(), m_itemList.end(), tail) == m_itemList.end()) {
|
||||
if (!tail->isShowing) { // isShowing <=> in m_itemList
|
||||
tail->isShowing = true;
|
||||
m_itemList.push_back(tail);
|
||||
}
|
||||
@@ -237,13 +237,13 @@ bool TextTailManager::IsChatTextTail(uint32_t vid) const {
|
||||
|
||||
void TextTailManager::ShowAllTextTail() {
|
||||
for (auto& [vid, tail] : m_characterMap) {
|
||||
if (std::find(m_characterList.begin(), m_characterList.end(), tail) == m_characterList.end()) {
|
||||
if (!tail->isShowing) { // isShowing <=> in m_characterList
|
||||
tail->isShowing = true;
|
||||
m_characterList.push_back(tail);
|
||||
}
|
||||
}
|
||||
for (auto& [vid, tail] : m_itemMap) {
|
||||
if (std::find(m_itemList.begin(), m_itemList.end(), tail) == m_itemList.end()) {
|
||||
if (!tail->isShowing) { // isShowing <=> in m_itemList
|
||||
tail->isShowing = true;
|
||||
m_itemList.push_back(tail);
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ public:
|
||||
void Render(SDL_Renderer* renderer, const Gr2SceneRenderer* sceneRenderer = nullptr);
|
||||
using TextPainter = std::function<void(float,float,const std::string&,uint32_t,float,bool)>;
|
||||
using TextMeasure = std::function<float(const std::string&,float)>;
|
||||
void SetTextPainter(TextPainter painter, TextMeasure measure) { m_textPainter = std::move(painter); m_textMeasure = std::move(measure); }
|
||||
void SetTextPainter(TextPainter painter, TextMeasure measure) { m_textPainter = std::move(painter); m_textMeasure = std::move(measure); m_widths.clear(); }
|
||||
|
||||
// Queries & Getters
|
||||
size_t GetCharacterCount() const { return m_characterMap.size(); }
|
||||
@@ -148,9 +148,16 @@ public:
|
||||
private:
|
||||
TextPainter m_textPainter;
|
||||
TextMeasure m_textMeasure;
|
||||
// Names are measured by Arrange and again by Render every frame; memoize per scale.
|
||||
float TextWidth(const std::string& text, float scale = 1.0f) const {
|
||||
return m_textMeasure ? m_textMeasure(text, scale) : float(text.size()) * 8.0f * scale;
|
||||
if (!m_textMeasure) return float(text.size()) * 8.0f * scale;
|
||||
auto& widths = m_widths[scale];
|
||||
auto it = widths.find(text);
|
||||
if (it != widths.end()) return it->second;
|
||||
if (widths.size() >= 4096) widths.clear();
|
||||
return widths.emplace(text, m_textMeasure(text, scale)).first->second;
|
||||
}
|
||||
mutable std::unordered_map<float, std::unordered_map<std::string, float>> m_widths;
|
||||
bool isIn(const TextTailItem& src, const TextTailItem& tgt) const;
|
||||
void RenderTextTailBox(SDL_Renderer* renderer, const TextTailItem& tail);
|
||||
void RenderText(SDL_Renderer* renderer, float x, float y, const std::string& text, uint32_t color, float scale = 1.0f, bool shadow = true);
|
||||
|
||||
+15
-10
@@ -1,6 +1,7 @@
|
||||
#include "Font.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <list>
|
||||
@@ -13,8 +14,9 @@
|
||||
|
||||
namespace UI {
|
||||
namespace {
|
||||
std::vector<unsigned> Codepoints(const std::string& text) {
|
||||
std::vector<unsigned> out;
|
||||
// Visits codepoints in place; measuring/drawing runs per label per frame, so no vector.
|
||||
template <class Visit>
|
||||
void ForEachCodepoint(const std::string& text, Visit&& visit) {
|
||||
for (size_t i = 0; i < text.size();) {
|
||||
unsigned c = static_cast<unsigned char>(text[i++]);
|
||||
int n = c >= 0xf0 && c <= 0xf4 ? 3 : c >= 0xe0 && c < 0xf0 ? 2 : c >= 0xc2 && c < 0xe0 ? 1 : 0;
|
||||
@@ -24,9 +26,8 @@ std::vector<unsigned> Codepoints(const std::string& text) {
|
||||
value = (value << 6) | (static_cast<unsigned char>(text[end++]) & 0x3f);
|
||||
if (end - i == static_cast<size_t>(n)) { i = end; c = value; }
|
||||
// Some legacy labels include a trailing NUL; SDL's debug font hid it.
|
||||
if (c >= 32 && c != 127) out.push_back(c);
|
||||
if (c >= 32 && c != 127) visit(c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
#ifdef AVA2_HAS_FREETYPE
|
||||
struct Glyph {
|
||||
@@ -108,12 +109,12 @@ int TextFontSize(const std::string& name) {
|
||||
|
||||
float MeasureText(const std::string& text, int size) {
|
||||
float width = 0;
|
||||
for (unsigned code : Codepoints(text)) {
|
||||
ForEachCodepoint(text, [&](unsigned code) {
|
||||
#ifdef AVA2_HAS_FREETYPE
|
||||
if (Cache().face) { width += Cache().Get(size, code).advance; continue; }
|
||||
if (Cache().face) { width += Cache().Get(size, code).advance; return; }
|
||||
#endif
|
||||
width += size * 0.5f;
|
||||
}
|
||||
});
|
||||
return width;
|
||||
}
|
||||
|
||||
@@ -122,7 +123,11 @@ void DrawText(SDL_Renderer* renderer, const std::string& text, int size, float x
|
||||
#ifdef AVA2_HAS_FREETYPE
|
||||
if (Cache().face) {
|
||||
auto& cache = TextureCache(renderer);
|
||||
const std::string key = std::to_string(size) + ":" + text;
|
||||
// Reused buffer: the hit path runs for every label every frame.
|
||||
static std::string key;
|
||||
char prefix[16];
|
||||
key.assign(prefix, std::snprintf(prefix, sizeof(prefix), "%d:", size));
|
||||
key += text;
|
||||
auto found = cache.entries.find(key);
|
||||
if (found != cache.entries.end()) {
|
||||
cache.recent.splice(cache.recent.begin(), cache.recent, found->second.recent);
|
||||
@@ -139,7 +144,7 @@ void DrawText(SDL_Renderer* renderer, const std::string& text, int size, float x
|
||||
if (!surface) return;
|
||||
SDL_FillSurfaceRect(surface, nullptr, 0);
|
||||
float pen = 0;
|
||||
for (unsigned code : Codepoints(text)) {
|
||||
ForEachCodepoint(text, [&](unsigned code) {
|
||||
const auto& glyph = Cache().Get(size, code);
|
||||
const int gx = int(std::round(pen * 2)) + glyph.left;
|
||||
const int gy = size * 2 - glyph.top;
|
||||
@@ -155,7 +160,7 @@ void DrawText(SDL_Renderer* renderer, const std::string& text, int size, float x
|
||||
}
|
||||
}
|
||||
pen += glyph.advance;
|
||||
}
|
||||
});
|
||||
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
|
||||
SDL_DestroySurface(surface);
|
||||
if (texture) {
|
||||
|
||||
@@ -782,15 +782,16 @@ namespace UI
|
||||
SDL_Renderer* renderer = pDevice->GetRenderer();
|
||||
if (!renderer) return;
|
||||
|
||||
std::string displayText = m_text;
|
||||
std::string secretText;
|
||||
if (m_secret)
|
||||
displayText.assign(m_text.length(), '*');
|
||||
secretText.assign(m_text.length(), '*');
|
||||
const std::string& displayText = m_secret ? secretText : m_text;
|
||||
|
||||
if (displayText.empty() && !m_showCursor)
|
||||
return;
|
||||
|
||||
const int fontSize = TextFontSize(m_font);
|
||||
const float charWidth = MeasureText("*", fontSize);
|
||||
const float charWidth = m_showCursor ? MeasureText("*", fontSize) : 0.0f;
|
||||
const float charHeight = float(fontSize);
|
||||
float textWidth = MeasureText(displayText, fontSize);
|
||||
float textHeight = charHeight;
|
||||
|
||||
@@ -615,16 +615,21 @@ static PyObject* texttail_register_item(PyObject*, PyObject* args) {
|
||||
void initTextTail() {
|
||||
// Use the same FreeType font path as UI text, preserving the Retina render
|
||||
// scale. SDL_RenderDebugText's fixed bitmap font is only a host fallback.
|
||||
// One reused instance per callback: text tails paint several labels per actor per frame.
|
||||
static auto fontFor=[](UI::CGraphicTextInstance& text,int& lastSize,float scale) {
|
||||
const int size=int(12 * scale);
|
||||
if(size!=lastSize){lastSize=size;text.SetFontName(("Tahoma:" + std::to_string(size)).c_str());}
|
||||
};
|
||||
TextTailManager::Instance().SetTextPainter(
|
||||
[](float x,float y,const std::string& value,uint32_t color,float scale,bool outline) {
|
||||
UI::CGraphicTextInstance text;
|
||||
text.SetFontName(("Tahoma:" + std::to_string(int(12 * scale))).c_str());
|
||||
static UI::CGraphicTextInstance text;static int lastSize=-1;
|
||||
fontFor(text,lastSize,scale);
|
||||
text.SetValue(value.c_str()); text.SetFontColor(color);
|
||||
text.SetPosition(x,y); text.SetOutline(outline); text.Render();
|
||||
},
|
||||
[](const std::string& value,float scale) {
|
||||
UI::CGraphicTextInstance text;
|
||||
text.SetFontName(("Tahoma:" + std::to_string(int(12 * scale))).c_str());
|
||||
static UI::CGraphicTextInstance text;static int lastSize=-1;
|
||||
fontFor(text,lastSize,scale);
|
||||
text.SetValue(value.c_str()); int width=0; text.GetTextSize(&width,nullptr); return float(width);
|
||||
});
|
||||
static PyMethodDef methods[] = {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <iostream>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <fstream>
|
||||
#include <chrono>
|
||||
#include "test_rundir.h"
|
||||
@@ -116,6 +117,21 @@ int main(int argc, char** argv) {
|
||||
std::cout << "Draw " << i << " texture0: '" << draws[i].texture0 << "'" << std::endl;
|
||||
}
|
||||
assert(!draws.empty() && "Must produce at least one 3D draw command");
|
||||
{
|
||||
// GPU draw caches keep skinned texture names; skin changes after the cache is built must apply.
|
||||
auto skinned = ava2::Gr2ModelInstance::Load(model_path);assert(skinned);
|
||||
const auto base = skinned->BuildDrawCommands(-1.0f, nullptr, true);assert(!base.empty());
|
||||
assert(skinned->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == base[0].texture0);
|
||||
std::string upper = base[0].texture0;for (auto& c : upper) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
|
||||
skinned->SetSkin(upper, "skin-test.dds");
|
||||
assert(skinned->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == "skin-test.dds");
|
||||
assert(skinned->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == "skin-test.dds");
|
||||
skinned->ClearSkins();
|
||||
assert(skinned->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == base[0].texture0);
|
||||
auto fresh = ava2::Gr2ModelInstance::Load(model_path);assert(fresh);fresh->SetSkin(base[0].texture0, "skin-test.dds");
|
||||
assert(fresh->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == "skin-test.dds");
|
||||
assert(fresh->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == "skin-test.dds");
|
||||
}
|
||||
|
||||
// Setup 3D Scene Renderer
|
||||
const int width = 1024;
|
||||
@@ -716,17 +732,25 @@ int main(int argc, char** argv) {
|
||||
assert(cpu.size()==gpu.size());
|
||||
auto again=instance.GetImpl()->BuildDrawCommands(time+.1f,nullptr,true);
|
||||
assert(again.size()==gpu.size());
|
||||
// One palette per instance per frame: draws of a mesh/part share it instead of copying.
|
||||
std::set<const void*> palettes;size_t skinned=0;
|
||||
for(const auto& g:gpu)if(g.gpu_skinning){palettes.insert(g.palette.get());++skinned;}
|
||||
assert(skinned<2 || palettes.size()<skinned);
|
||||
for(size_t d=0;d<cpu.size();++d) {
|
||||
const auto& g=gpu[d];assert(g.geometry && again[d].geometry==g.geometry);
|
||||
assert(!g.gpu_skinning || g.palette);
|
||||
const auto& mesh=*g.geometry;
|
||||
assert(cpu[d].positions.size()==mesh.positions.size());
|
||||
assert(cpu[d].indices==mesh.indices);
|
||||
// Tri-groups share one geometry per mesh; each GPU draw covers its own index range.
|
||||
assert(g.first_index+size_t(cpu[d].indices.size())<=mesh.indices.size() || g.index_count==0);
|
||||
assert(std::equal(cpu[d].indices.begin(),cpu[d].indices.end(),mesh.indices.begin()+std::min<size_t>(g.first_index,mesh.indices.size())));
|
||||
assert(g.index_count==UINT32_MAX ? cpu[d].indices.size()==mesh.indices.size() : cpu[d].indices.size()==g.index_count);
|
||||
for(size_t v=0;v<mesh.positions.size()/3;++v) {
|
||||
float p[3]{},n[3]{},total=0;
|
||||
if(g.gpu_skinning)for(int b=0;b<4;++b) {
|
||||
const auto bone=mesh.bone_indices[v*4+b];const float w=mesh.bone_weights[v*4+b];
|
||||
if(w<=0 || size_t(bone)*16+15>=g.bone_matrices.size())continue;
|
||||
const auto* m=g.bone_matrices.data()+bone*16;
|
||||
if(w<=0 || size_t(bone)*16+15>=g.palette->size())continue;
|
||||
const auto* m=g.palette->data()+bone*16;
|
||||
for(int k=0;k<3;++k){p[k]+=(mesh.positions[v*3]*m[k]+mesh.positions[v*3+1]*m[k+4]+mesh.positions[v*3+2]*m[k+8]+m[k+12])*w;
|
||||
n[k]+=(mesh.normals[v*3]*m[k]+mesh.normals[v*3+1]*m[k+4]+mesh.normals[v*3+2]*m[k+8])*w;}
|
||||
total+=w;
|
||||
|
||||
@@ -29,7 +29,7 @@ int main() {
|
||||
std::vector<ava2::HardwareVertex> vertices;
|
||||
auto triangle=[&](float z,float r,float g,float b,float alpha) {
|
||||
for(auto p: {std::pair{-0.9f,-0.9f},std::pair{0.9f,-0.9f},std::pair{0.f,0.9f}})
|
||||
vertices.push_back({{p.first,p.second,z,1},{r,g,b,alpha},{0,0}});
|
||||
vertices.push_back({{p.first,p.second,z,1},{uint8_t(r*255),uint8_t(g*255),uint8_t(b*255),uint8_t(alpha*255)},{0,0}});
|
||||
};
|
||||
triangle(.2,1,0,0,1);triangle(.8,0,1,0,1);triangle(.1,0,0,1,.2);
|
||||
std::vector<uint32_t> indices{0,1,2,3,4,5,6,7,8};
|
||||
@@ -59,7 +59,7 @@ int main() {
|
||||
// Perspective-correct color interpolation: top W=2 doubles its reciprocal denominator.
|
||||
auto saved=vertices;
|
||||
vertices[2].position[1]*=2;vertices[2].position[2]*=2;vertices[2].position[3]=2;
|
||||
vertices[0].color[0]=vertices[1].color[0]=0;vertices[2].color[0]=1;
|
||||
vertices[0].color[0]=vertices[1].color[0]=0;vertices[2].color[0]=255;
|
||||
near.cull=1;color=center({near});assert(color[0]>65&&color[0]<100);
|
||||
vertices=saved;
|
||||
// Newly uploaded textures must be usable on their first frame, even
|
||||
@@ -138,21 +138,36 @@ int main() {
|
||||
pixels=frame({offscreen,left,right});
|
||||
assert(resident.GetLastDrawCallCount()==2 && redAt(16)>245 && redAt(48)>120 && redAt(48)<135);
|
||||
SDL_DestroySurface(pixels);
|
||||
// Tri-group sub-ranges share one resident buffer; firstIndex selects the right-hand triangle only.
|
||||
{
|
||||
auto groups=std::make_shared<ava2::Render3DDraw>(*mesh);
|
||||
groups->positions={-.65f,-.2f,.5f,-.35f,-.2f,.5f,-.5f,.2f,.5f, .35f,-.2f,.5f,.65f,-.2f,.5f,.5f,.2f,.5f};
|
||||
groups->indices={0,1,2,3,4,5};groups->diffuse=std::vector<uint32_t>(6,0xffff0000);
|
||||
auto second=left;second.geometry=groups;second.transform.mvp[12]=0;second.firstIndex=3;second.indexCount=3;
|
||||
const auto uploads=resident.GetResidentUploadCount();
|
||||
pixels=frame({second});
|
||||
assert(resident.GetResidentUploadCount()==uploads+1 && resident.GetLastDynamicUploadBytes()==0);
|
||||
assert(redAt(48)>245 && redAt(16)<5);SDL_DestroySurface(pixels);
|
||||
auto first=second;first.firstIndex=0;
|
||||
pixels=frame({first,second});
|
||||
assert(resident.GetResidentUploadCount()==uploads+1 && resident.GetLastDrawCallCount()==2);
|
||||
assert(redAt(16)>245 && redAt(48)>245);SDL_DestroySurface(pixels);
|
||||
}
|
||||
// Bone translation moves the raw triangle to the center; no CPU-deformed stream is uploaded.
|
||||
left.transform.skin[0]=1;left.palette={1,0,0,0,0,1,0,0,0,0,1,0,.5f,0,0,1};
|
||||
left.transform.skin[0]=1;left.palette=std::make_shared<std::vector<float>>(std::vector<float>{1,0,0,0,0,1,0,0,0,0,1,0,.5f,0,0,1});
|
||||
auto skinned=std::make_shared<ava2::Render3DDraw>(*mesh);skinned->bone_indices=std::vector<uint8_t>(12,0);skinned->bone_weights={1,0,0,0,1,0,0,0,1,0,0,0};left.geometry=skinned;
|
||||
pixels=frame({left});assert(redAt(32)>245 && redAt(16)<5);SDL_DestroySurface(pixels);
|
||||
// Two weighted, rotated bones: compare every rendered pixel to CPU-transformed vertices.
|
||||
left.transform.skin[0]=2;
|
||||
left.palette={1,0,0,0,0,1,0,0,0,0,1,0,.2f,0,0,1,
|
||||
0,1,0,0,-1,0,0,0,0,0,1,0,.7f,0,0,1};
|
||||
left.palette=std::make_shared<std::vector<float>>(std::vector<float>{1,0,0,0,0,1,0,0,0,0,1,0,.2f,0,0,1,
|
||||
0,1,0,0,-1,0,0,0,0,0,1,0,.7f,0,0,1});
|
||||
skinned=std::make_shared<ava2::Render3DDraw>(*mesh);
|
||||
skinned->bone_indices={0,1,0,0,0,1,0,0,0,1,0,0};
|
||||
skinned->bone_weights={.4f,.6f,0,0,.4f,.6f,0,0,.4f,.6f,0,0};
|
||||
left.geometry=skinned;pixels=frame({left});
|
||||
std::vector<ava2::HardwareVertex> reference;
|
||||
for(size_t v=0;v<3;++v){auto vertex=ava2::MakeHardwareVertex(*skinned,v);float pos[4]{};
|
||||
for(size_t b=0;b<2;++b){const auto* matrix=left.palette.data()+b*16;float w=vertex.weights[b];
|
||||
for(size_t b=0;b<2;++b){const auto* matrix=left.palette->data()+b*16;float w=vertex.weights[b]/65535.f;
|
||||
for(int k=0;k<4;++k)pos[k]+=(vertex.position[0]*matrix[k]+vertex.position[1]*matrix[k+4]+vertex.position[2]*matrix[k+8]+matrix[k+12])*w;}
|
||||
std::copy_n(pos,4,vertex.position);vertex.position[0]-=.5f;reference.push_back(vertex);}
|
||||
ava2::HardwareBatch cpu{};cpu.indexCount=3;cpu.cull=1;cpu.depth=true;cpu.depthWrite=true;cpu.alphaRef=-1;
|
||||
|
||||
Reference in New Issue
Block a user