From ae1c7c5fe4459ce9bacc59ec3229c4191be7c98e Mon Sep 17 00:00:00 2001 From: vis2k Date: Fri, 29 Apr 2022 09:59:52 +0800 Subject: [PATCH] fix: #3144 Reader/Writer Texture2D null support & test to guarantee it never happens again --- Assets/Mirror/Runtime/NetworkReaderExtensions.cs | 6 +++++- Assets/Mirror/Runtime/NetworkWriterExtensions.cs | 9 +++++++++ Assets/Mirror/Tests/Editor/NetworkWriterTest.cs | 14 ++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Assets/Mirror/Runtime/NetworkReaderExtensions.cs b/Assets/Mirror/Runtime/NetworkReaderExtensions.cs index 3edaabb2f..6a3d29c8b 100644 --- a/Assets/Mirror/Runtime/NetworkReaderExtensions.cs +++ b/Assets/Mirror/Runtime/NetworkReaderExtensions.cs @@ -274,8 +274,12 @@ public static Texture2D ReadTexture2D(this NetworkReader reader) // TODO allocation protection when sending textures to server. // currently can allocate 32k x 32k x 4 byte = 3.8 GB - // read width & height + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 short width = reader.ReadShort(); + if (width == -1) return null; + + // read height short height = reader.ReadShort(); Texture2D texture2D = new Texture2D(width, height); diff --git a/Assets/Mirror/Runtime/NetworkWriterExtensions.cs b/Assets/Mirror/Runtime/NetworkWriterExtensions.cs index 1d6434bc4..340cd13e0 100644 --- a/Assets/Mirror/Runtime/NetworkWriterExtensions.cs +++ b/Assets/Mirror/Runtime/NetworkWriterExtensions.cs @@ -294,6 +294,15 @@ public static void WriteTexture2D(this NetworkWriter writer, Texture2D texture2D // TODO allocation protection when sending textures to server. // currently can allocate 32k x 32k x 4 byte = 3.8 GB + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 + // simply send -1 for width. + if (texture2D == null) + { + writer.WriteShort(-1); + return; + } + // write dimensions first so reader can create the texture with size // 32k x 32k short is more than enough writer.WriteShort((short)texture2D.width); diff --git a/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs b/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs index 033dd0223..22b4d4bdf 100644 --- a/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs +++ b/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs @@ -1484,5 +1484,19 @@ public void WriteTexture2D_normal() Assert.That(texture.height, Is.EqualTo(Texture2D.normalTexture.height)); Assert.That(texture.GetPixels32().SequenceEqual(Texture2D.normalTexture.GetPixels32())); } + + // test to prevent https://github.com/vis2k/Mirror/issues/3144 + [Test] + public void WriteTexture2D_Null() + { + // write + NetworkWriter writer = new NetworkWriter(); + writer.WriteTexture2D(null); + + // read + NetworkReader reader = new NetworkReader(writer.ToArray()); + Texture2D texture = reader.ReadTexture2D(); + Assert.That(texture, Is.Null); + } } }