From c457087612f34e8ce3f8b804b7f72a9b3fd52d11 Mon Sep 17 00:00:00 2001 From: Wojtek Figat Date: Tue, 17 Oct 2023 22:44:15 +0200 Subject: [PATCH] Optimize memory allocation when using `Sprite` size during 2D rendering --- Source/Engine/Render2D/SpriteAtlas.cpp | 8 +++++++- Source/Engine/Render2D/SpriteAtlas.cs | 11 +++++++++-- Source/Engine/Render2D/SpriteAtlas.h | 8 ++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/Source/Engine/Render2D/SpriteAtlas.cpp b/Source/Engine/Render2D/SpriteAtlas.cpp index 0e0aa071f..ac711b8b8 100644 --- a/Source/Engine/Render2D/SpriteAtlas.cpp +++ b/Source/Engine/Render2D/SpriteAtlas.cpp @@ -47,10 +47,16 @@ int32 SpriteAtlas::GetSpritesCount() const Sprite SpriteAtlas::GetSprite(int32 index) const { - CHECK_RETURN(index >= 0 && index < Sprites.Count(), Sprite()) + CHECK_RETURN(index >= 0 && index < Sprites.Count(), Sprite()); return Sprites.Get()[index]; } +void SpriteAtlas::GetSpriteArea(int32 index, Rectangle& result) const +{ + CHECK(index >= 0 && index < Sprites.Count()); + result = Sprites.Get()[index].Area; +} + void SpriteAtlas::SetSprite(int32 index, const Sprite& value) { CHECK(index >= 0 && index < Sprites.Count()); diff --git a/Source/Engine/Render2D/SpriteAtlas.cs b/Source/Engine/Render2D/SpriteAtlas.cs index b3796ffd3..93cdf68b2 100644 --- a/Source/Engine/Render2D/SpriteAtlas.cs +++ b/Source/Engine/Render2D/SpriteAtlas.cs @@ -70,7 +70,13 @@ namespace FlaxEngine [NoSerialize] public Float2 Size { - get => Area.Size * Atlas.Size; + get + { + if (Atlas == null) + throw new InvalidOperationException("Cannot use invalid sprite."); + Atlas.GetSpriteArea(Index, out var area); + return area.Size * Atlas.Size; + } set { var area = Area; @@ -89,7 +95,8 @@ namespace FlaxEngine { if (Atlas == null) throw new InvalidOperationException("Cannot use invalid sprite."); - return Atlas.GetSprite(Index).Area; + Atlas.GetSpriteArea(Index, out var area); + return area; } set { diff --git a/Source/Engine/Render2D/SpriteAtlas.h b/Source/Engine/Render2D/SpriteAtlas.h index 6fcda5162..533440c68 100644 --- a/Source/Engine/Render2D/SpriteAtlas.h +++ b/Source/Engine/Render2D/SpriteAtlas.h @@ -120,6 +120,14 @@ public: /// The sprite data. API_FUNCTION() Sprite GetSprite(int32 index) const; + /// + /// Gets the sprite area. + /// + /// The index. + /// The output sprite area. + /// The sprite data. + API_FUNCTION() void GetSpriteArea(int32 index, API_PARAM(Out) Rectangle& result) const; + /// /// Sets the sprite data. ///