浏览代码

Refactor the test framework to allow to run the tests in editor play mode :

- Add TestFrameworkPlayMode class
 - Move common functions to TestFrameworkTools class
 - Add a setting in SetupSceneforRenderPipelineTest to invoke custom actions before capturing
/main
Remy 7 年前
当前提交
d5dfa0d9
共有 18 个文件被更改,包括 786 次插入180 次删除
  1. 204
      Tests/GraphicsTests/Framework/Editor/TestFramework.cs
  2. 55
      Tests/GraphicsTests/Framework/SetupSceneForRenderPipelineTest.cs
  3. 44
      Tests/GraphicsTests/Framework/Editor/EditorPlayModeTests_Editor.cs
  4. 11
      Tests/GraphicsTests/Framework/Editor/EditorPlayModeTests_Editor.cs.meta
  5. 9
      Tests/GraphicsTests/Framework/EditorPlayModeTests.cs
  6. 11
      Tests/GraphicsTests/Framework/EditorPlayModeTests.cs.meta
  7. 21
      Tests/GraphicsTests/Framework/PlayModeTestable.cs
  8. 11
      Tests/GraphicsTests/Framework/PlayModeTestable.cs.meta
  9. 60
      Tests/GraphicsTests/Framework/TestFixture.cs
  10. 11
      Tests/GraphicsTests/Framework/TestFixture.cs.meta
  11. 148
      Tests/GraphicsTests/Framework/TestFrameworkPlayMode.cs
  12. 11
      Tests/GraphicsTests/Framework/TestFrameworkPlayMode.cs.meta
  13. 307
      Tests/GraphicsTests/Framework/TestFrameworkTools.cs
  14. 11
      Tests/GraphicsTests/Framework/TestFrameworkTools.cs.meta
  15. 18
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Scripts/DebugViewController.cs
  16. 11
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Scripts/DebugViewController.cs.meta
  17. 15
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/EditorPlayModeTests.asset
  18. 8
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/EditorPlayModeTests.asset.meta

204
Tests/GraphicsTests/Framework/Editor/TestFramework.cs


{
public class GraphicsTests
{
static readonly string s_RootPath = Directory.GetParent(Directory.GetFiles(Application.dataPath, "SRPMARKER", SearchOption.AllDirectories).First()).ToString();
// path where the tests live
private static readonly string[] s_Path =
{
"Tests",
"GraphicsTests",
"RenderPipeline"
};
// info that gets generated for use
// in a dod way
public struct TestInfo
{
public string name;
public float threshold;
public string relativePath;
public int frameWait;
public override string ToString()
{
return name;
}
}
// Renderpipeline assets used for the tests
public static Dictionary<string, string> renderPipelineAssets = new Dictionary<string, string>()
{
{ "HDRP", "HDRenderPipeline/CommonAssets/HDRP_GraphicTests_Asset.asset" },
{ "LWRP", "LightweightPipeline/LightweightPipelineAsset.asset" }
};
// Renderpipeline assets used for the tests
public static Dictionary<string, string> renderPipelineScenesFolder = new Dictionary<string, string>()
{
{ "HDRP", "HDRenderPipeline/Scenes" },
{ "LWRP", "LightweightPipeline" }
};
// collect the scenes that we can use
public static class CollectScenes
{
public static IEnumerable HDRP
{
get
{
return GetScenesForPipelineID("HDRP");
}
}
public static IEnumerable LWRP
{
get
{
return GetScenesForPipelineID("LWRP");
}
}
public static IEnumerable GetScenesForPipelineID( string _pipelineID )
{
return GetScenesForPipeline( renderPipelineScenesFolder[_pipelineID] );
}
public static IEnumerable GetScenesForPipeline(string _pipelinePath)
{
var absoluteScenesPath = s_Path.Aggregate(s_RootPath, Path.Combine);
var filesPath = Path.Combine(absoluteScenesPath, _pipelinePath);
// find all the scenes
var allPaths = Directory.GetFiles(filesPath, "*.unity", SearchOption.AllDirectories);
// Convert to List for easy sorting in alphabetical ordre
List<string> allPaths_List = new List<string>(allPaths);
allPaths_List.Sort();
// construct all the needed test infos
for (int i=0; i<allPaths_List.Count; ++i)
{
var path = allPaths_List[i];
var p = new FileInfo(path);
var split = s_Path.Aggregate("", Path.Combine);
split = string.Format("{0}{1}", split, Path.DirectorySeparatorChar);
var splitPaths = p.FullName.Split(new[] { split }, StringSplitOptions.RemoveEmptyEntries);
yield return new TestInfo
{
name = p.Name,
relativePath = splitPaths.Last(),
threshold = 0.02f,
frameWait = 100
};
}
}
}
// Change the SRP before a full batch of tests
public virtual string _SRP_ID { get { return "NONE"; } }

public static RenderPipelineAsset GetRenderPipelineAsset(string _SRP_ID)
{
string absolutePath = s_Path.Aggregate(s_RootPath, Path.Combine);
string absolutePath = TestFrameworkTools.s_Path.Aggregate(TestFrameworkTools.s_RootPath, Path.Combine);
string filePath = Path.Combine(absolutePath, renderPipelineAssets[_SRP_ID] );
string filePath = Path.Combine(absolutePath, TestFrameworkTools.renderPipelineAssets[_SRP_ID] );
return (RenderPipelineAsset)AssetDatabase.LoadAssetAtPath(filePath, typeof(RenderPipelineAsset));
}

// the actual test
public static IEnumerator TestScene(TestInfo testInfo)
public static IEnumerator TestScene(TestFrameworkTools.TestInfo testInfo)
var prjRelativeGraphsPath = s_Path.Aggregate(s_RootPath, Path.Combine);
var prjRelativeGraphsPath = TestFrameworkTools.s_Path.Aggregate(TestFrameworkTools.s_RootPath, Path.Combine);
var filePath = Path.Combine(prjRelativeGraphsPath, testInfo.relativePath);
// open the scene

yield return null;
}
Camera testCamera = testSetup.cameraToUse;
var rtDesc = new RenderTextureDescriptor (
testSetup.width,
testSetup.height,
(testSetup.hdr && testCamera.allowHDR) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32,
24);
rtDesc.sRGB = PlayerSettings.colorSpace == ColorSpace.Linear;
rtDesc.msaaSamples = testSetup.msaaSamples;
// render the scene
var tempTarget = RenderTexture.GetTemporary (rtDesc);
var oldTarget = testSetup.cameraToUse.targetTexture;
testSetup.cameraToUse.targetTexture = tempTarget;
testSetup.cameraToUse.Render ();
testSetup.cameraToUse.targetTexture = oldTarget;
// Readback the rendered texture
var oldActive = RenderTexture.active;
RenderTexture.active = tempTarget;
var captured = new Texture2D(tempTarget.width, tempTarget.height, TextureFormat.RGB24, false);
captured.ReadPixels(new Rect(0, 0, testSetup.width, testSetup.height), 0, 0);
RenderTexture.active = oldActive;
var templatePath = Path.Combine(s_RootPath, "ImageTemplates");
// find the reference image
var dumpFileLocation = Path.Combine(templatePath, string.Format("{0}.{1}", testInfo.relativePath, "png"));
if (!File.Exists(dumpFileLocation))
// Handle play mode and things to do before
if (testSetup.testInPlayMode)
{
//if (!testSetup.invokeAtStart) testSetup.thingToDoBeforeTest.Invoke();
//EditorApplication.isPlaying = true;
}
else
// no reference exists, create it
var fileInfo = new FileInfo (dumpFileLocation);
fileInfo.Directory.Create();
var generated = captured.EncodeToPNG();
File.WriteAllBytes(dumpFileLocation, generated);
Assert.Fail("Template file not found for {0}, creating it at {1}.", testInfo.name, dumpFileLocation);
testSetup.thingToDoBeforeTest.Invoke();
var template = File.ReadAllBytes(dumpFileLocation);
var fromDisk = new Texture2D(2, 2);
fromDisk.LoadImage(template, false);
// Render the camera
Texture2D captured = TestFrameworkTools.RenderSetupToTexture(testSetup);
var areEqual = CompareTextures(fromDisk, captured, testInfo.threshold);
// Load the template
Texture2D fromDisk = new Texture2D(2, 2);
string dumpFileLocation = "";
if ( !TestFrameworkTools.FindReferenceImage( testInfo, ref fromDisk, captured, ref dumpFileLocation) )
Assert.Fail("Template file not found for {0}, creating it at {1}.", testInfo.name, dumpFileLocation);
// Compare
var areEqual = TestFrameworkTools.CompareTextures(fromDisk, captured, testInfo.threshold);
if (!areEqual)
{

var misMatchLocationTemplate = Path.Combine(failedPath, string.Format("{0}.template.{1}", testInfo.name, "png"));
var generated = captured.EncodeToPNG();
File.WriteAllBytes(misMatchLocationResult, generated);
File.WriteAllBytes(misMatchLocationTemplate, template);
File.Copy(dumpFileLocation, misMatchLocationTemplate);
}
Assert.IsTrue(areEqual, "Scene from {0}, did not match .template file.", testInfo.relativePath);

// compare textures, use RMS for this
private static bool CompareTextures(Texture2D fromDisk, Texture2D captured, float threshold)
{
if (fromDisk == null || captured == null)
return false;
if (fromDisk.width != captured.width
|| fromDisk.height != captured.height)
return false;
var pixels1 = fromDisk.GetPixels();
var pixels2 = captured.GetPixels();
if (pixels1.Length != pixels2.Length)
return false;
int numberOfPixels = pixels1.Length;
float sumOfSquaredColorDistances = 0;
for (int i = 0; i < numberOfPixels; i++)
{
Color p1 = pixels1[i];
Color p2 = pixels2[i];
Color diff = p1 - p2;
diff = diff * diff;
sumOfSquaredColorDistances += (diff.r + diff.g + diff.b) / 3.0f;
}
float rmse = Mathf.Sqrt(sumOfSquaredColorDistances / numberOfPixels);
return rmse < threshold;
}
// Graphic Tests Subclasses that inherit the functions bot provide different SRP_ID
public class HDRP : GraphicsTests
{

public IEnumerator HDRP_Test([ValueSource(typeof(CollectScenes), "HDRP")]TestInfo testInfo)
public IEnumerator HDRP_Test([ValueSource(typeof(TestFrameworkTools.CollectScenes), "HDRP")]TestFrameworkTools.TestInfo testInfo)
public class LTRP : GraphicsTests
public class LWRP : GraphicsTests
public IEnumerator LWRP_Test([ValueSource(typeof(CollectScenes), "LWRP")]TestInfo testInfo)
public IEnumerator LWRP_Test([ValueSource(typeof(TestFrameworkTools.CollectScenes), "LWRP")]TestFrameworkTools.TestInfo testInfo)
{
return TestScene(testInfo);
}

55
Tests/GraphicsTests/Framework/SetupSceneForRenderPipelineTest.cs


using UnityEngine.Rendering;
using UnityEngine.Events;
using UnityEditor;
using UnityEngine;
using System.Collections;
using UnityEngine.TestTools;
public class SetupSceneForRenderPipelineTest : MonoBehaviour
public class SetupSceneForRenderPipelineTest : MonoBehaviour, IMonoBehaviourTest
{
private RenderPipelineAsset m_OriginalAsset;
public RenderPipelineAsset renderPipeline;

public int width = 1280;
public int height = 720;
public void Setup()
public UnityEvent thingToDoBeforeTest;
[Header("Run Play Mode for test")]
public bool testInPlayMode = false;
public bool invokeAtStart = true;
public int forcedFrameRate = 60;
public int waitForFrames = 30;
int waitedFrames = 0;
bool _readyForCapture = false;
public bool readyForCapture { get { return _readyForCapture; } }
public IEnumerator Start()
{
// Wait for other things to happend, in particular allow for the render pipeline to reset
yield return new WaitForEndOfFrame();
if (invokeAtStart) thingToDoBeforeTest.Invoke();
if (!testInPlayMode) _readyForCapture = true;
Time.captureFramerate = forcedFrameRate;
}
public void Update()
{
if ( waitedFrames < waitForFrames )
{
++waitedFrames;
}
else if (!_readyForCapture)
{
_readyForCapture = true;
}
}
public void Setup()
{
m_OriginalAsset = GraphicsSettings.renderPipelineAsset;
if (m_OriginalAsset != renderPipeline) GraphicsSettings.renderPipelineAsset = renderPipeline;

{
if ( GraphicsSettings.renderPipelineAsset != m_OriginalAsset ) GraphicsSettings.renderPipelineAsset = m_OriginalAsset;
//EditorApplication.isPaused = false;
//EditorApplication.isPlaying = false;
public bool IsTestFinished
{
get
{
return _readyForCapture;
}
}
}
}

44
Tests/GraphicsTests/Framework/Editor/EditorPlayModeTests_Editor.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using Object = UnityEngine.Object;
[CustomEditor(typeof(EditorPlayModeTests))]
class EditorPlayModeTests_Editor : Editor
{
EditorPlayModeTests typedTarget;
private void OnEnable()
{
typedTarget = (EditorPlayModeTests)target;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
Object newScene = EditorGUILayout.ObjectField("Add Scene", null, typeof(Object), false);
if (newScene != null)
{
string newPath = AssetDatabase.GetAssetPath(newScene);
Debug.Log("New Path : " + newPath);
if (newPath.EndsWith("unity"))
{
Debug.Log("Add the scene to the list");
//int i = p_scenesPath.arraySize;
//p_scenesPath.InsertArrayElementAtIndex(i);
//p_scenesPath.GetArrayElementAtIndex(i).stringValue = newPath;
if (typedTarget.scenesPath == null) typedTarget.scenesPath = new string[] { newPath };
else
{
Array.Resize(ref typedTarget.scenesPath, typedTarget.scenesPath.Length + 1);
typedTarget.scenesPath[typedTarget.scenesPath.Length - 1] = newPath;
}
EditorUtility.SetDirty(typedTarget);
}
}
}
}

11
Tests/GraphicsTests/Framework/Editor/EditorPlayModeTests_Editor.cs.meta


fileFormatVersion: 2
guid: 4effbdd65bef75144b533ae00f0beceb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

9
Tests/GraphicsTests/Framework/EditorPlayModeTests.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "EditorPlayModeTests", menuName = "Render Pipeline/Tests/Editor Play Mode Tests List", order = 20)]
public class EditorPlayModeTests : ScriptableObject
{
public string[] scenesPath;
}

11
Tests/GraphicsTests/Framework/EditorPlayModeTests.cs.meta


fileFormatVersion: 2
guid: 0baa057a399734241b8f30441a73b429
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

21
Tests/GraphicsTests/Framework/PlayModeTestable.cs


using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Events;
using System.Collections;
public class PlayModeTestable : SetupSceneForRenderPipelineTest, IMonoBehaviourTest
{
float t = 0f;
public float testDuration = 1f;
public bool IsTestFinished
{
get
{
t += Time.deltaTime;
return (t > testDuration);
}
}
}

11
Tests/GraphicsTests/Framework/PlayModeTestable.cs.meta


fileFormatVersion: 2
guid: 868dc35db36e4fa489cf58cc866e719d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

60
Tests/GraphicsTests/Framework/TestFixture.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NUnit.Framework;
using UnityEngine.TestTools;
[TestFixtureSource(typeof(MyFixtureData), "FixtureParms")]
public class ParameterizedTestFixture
{
private string eq1;
private string eq2;
private string neq;
public ParameterizedTestFixture(string eq1, string eq2, string neq)
{
this.eq1 = eq1;
this.eq2 = eq2;
this.neq = neq;
}
public ParameterizedTestFixture(string eq1, string eq2)
: this(eq1, eq2, null) { }
public ParameterizedTestFixture(int eq1, int eq2, int neq)
{
this.eq1 = eq1.ToString();
this.eq2 = eq2.ToString();
this.neq = neq.ToString();
}
[Test]
public void TestEquality()
{
Assert.AreEqual(eq1, eq2);
if (eq1 != null && eq2 != null)
Assert.AreEqual(eq1.GetHashCode(), eq2.GetHashCode());
}
[Test]
public void TestInequality()
{
Assert.AreNotEqual(eq1, neq);
if (eq1 != null && neq != null)
Assert.AreNotEqual(eq1.GetHashCode(), neq.GetHashCode());
}
}
public class MyFixtureData
{
public static IEnumerable FixtureParms
{
get
{
yield return new TestFixtureData("hello", "hello", "goodbye");
yield return new TestFixtureData("zip", "zip");
yield return new TestFixtureData(42, 42, 99);
}
}
}

11
Tests/GraphicsTests/Framework/TestFixture.cs.meta


fileFormatVersion: 2
guid: 03feffdb44a44f34b9671302212430f3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

148
Tests/GraphicsTests/Framework/TestFrameworkPlayMode.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NUnit.Framework;
using UnityEngine.TestTools;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Events;
using System.IO;
using System.Linq;
public class GraphicTestsPlayMode : IPrebuildSetup, IPostBuildCleanup
{
public virtual string pipelineID { get { return "NoPipeline"; } }
#if UNITY_EDITOR
UnityEditor.EditorBuildSettingsScene[] oldScenes;
public void Setup()
{
Debug.Log("Setup for the test");
oldScenes = UnityEditor.EditorBuildSettings.scenes;
List<UnityEditor.EditorBuildSettingsScene> sceneSetups = new List<UnityEditor.EditorBuildSettingsScene>();
foreach ( TestFrameworkTools.TestInfo testInfo in TestFrameworkTools.CollectScenesPlayMode.GetScenesForPipelineID(pipelineID))
{
sceneSetups.Add(new UnityEditor.EditorBuildSettingsScene {
path = testInfo.relativePath,
enabled = true
});
}
UnityEditor.EditorBuildSettings.scenes = sceneSetups.ToArray();
}
public void Cleanup()
{
//UnityEditor.EditorBuildSettings.scenes = oldScenes;
}
#endif
//public IEnumerator TestScene([ValueSource(typeof(TestFrameworkTools.CollectScenesPlayMode), "HDRP")]TestFrameworkTools.TestInfo testInfo)
public IEnumerator TestScene(TestFrameworkTools.TestInfo testInfo)
{
var prjRelativeGraphsPath = TestFrameworkTools.s_Path.Aggregate(TestFrameworkTools.s_RootPath, Path.Combine);
var filePath = Path.Combine(prjRelativeGraphsPath, testInfo.relativePath);
// open the scene
UnityEngine.SceneManagement.SceneManager.LoadScene( testInfo.relativePath , UnityEngine.SceneManagement.LoadSceneMode.Single);
yield return null; // wait one "frame" to let the scene load
SetupSceneForRenderPipelineTest testSetup = GameObject.FindObjectOfType<SetupSceneForRenderPipelineTest>();
Assert.IsNotNull(testSetup, "No SetupSceneForRenderPipelineTest in scene " + testInfo.name);
Assert.IsNotNull(testSetup.cameraToUse, "No configured camera in <SetupSceneForRenderPipelineTest>");
// Initialize
testSetup.Setup();
yield return null; // Wait one frame in case we changed the render pipeline
testSetup.thingToDoBeforeTest.Invoke();
// Setup Render Target
Camera testCamera = testSetup.cameraToUse;
var rtDesc = new RenderTextureDescriptor(
testSetup.width,
testSetup.height,
(testSetup.hdr && testCamera.allowHDR) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32,
24);
//rtDesc.sRGB = PlayerSettings.colorSpace == ColorSpace.Linear;
rtDesc.msaaSamples = testSetup.msaaSamples;
var tempTarget = RenderTexture.GetTemporary(rtDesc);
var oldTarget = testSetup.cameraToUse.targetTexture;
testSetup.cameraToUse.targetTexture = tempTarget;
while (!testSetup.IsTestFinished) yield return null;
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPaused = true;
#endif
// render the scene
testSetup.cameraToUse.Render();
testSetup.cameraToUse.targetTexture = oldTarget;
// Readback the rendered texture
var oldActive = RenderTexture.active;
RenderTexture.active = tempTarget;
var captured = new Texture2D(tempTarget.width, tempTarget.height, TextureFormat.RGB24, false);
captured.ReadPixels(new Rect(0, 0, testSetup.width, testSetup.height), 0, 0);
RenderTexture.active = oldActive;
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPaused = false;
#endif
// Load the template
Texture2D fromDisk = new Texture2D(2, 2);
string dumpFileLocation = "";
if (!TestFrameworkTools.FindReferenceImage(testInfo, ref fromDisk, captured, ref dumpFileLocation))
{
throw new System.Exception(string.Format("Template file not found for {0}, creating it at {1}.", testInfo.name, dumpFileLocation));
}
// Compare
var areEqual = TestFrameworkTools.CompareTextures(fromDisk, captured, testInfo.threshold);
if (!areEqual)
{
Debug.Log("Test Fail");
var failedPath = Path.Combine(Directory.GetParent(Application.dataPath).ToString(), "SRP_Failed");
Directory.CreateDirectory(failedPath);
var misMatchLocationResult = Path.Combine(failedPath, string.Format("{0}.{1}", testInfo.name, "png"));
var misMatchLocationTemplate = Path.Combine(failedPath, string.Format("{0}.template.{1}", testInfo.name, "png"));
var generated = captured.EncodeToPNG();
File.WriteAllBytes(misMatchLocationResult, generated);
File.Copy(dumpFileLocation, misMatchLocationTemplate, true);
throw new System.Exception(string.Format("Scene from {0}, did not match .template file.", testInfo.relativePath));
}
else
{
Debug.Log("Test Pass");
Assert.IsTrue(true);
}
testSetup.TearDown();
yield return null;
}
public class HDRP : GraphicTestsPlayMode
{
public override string pipelineID { get { return "HDRP"; } }
[UnityTest]
new public IEnumerator TestScene([ValueSource(typeof(TestFrameworkTools.CollectScenesPlayMode), "HDRP")]TestFrameworkTools.TestInfo testInfo)
{
return base.TestScene(testInfo);
}
}
}

11
Tests/GraphicsTests/Framework/TestFrameworkPlayMode.cs.meta


fileFormatVersion: 2
guid: ceda45e385c271c4f8f687b3fa5f0ce9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

307
Tests/GraphicsTests/Framework/TestFrameworkTools.cs


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System.IO;
using UnityEditor;
using NUnit.Framework;
using UnityEngine.TestTools;
using UnityEditor.TestTools;
namespace UnityEngine.Experimental.Rendering
{
public class TestFrameworkTools
{
public static readonly string s_RootPath = Directory.GetParent(Directory.GetFiles(Application.dataPath, "SRPMARKER", SearchOption.AllDirectories).First()).ToString();
// path where the tests live
public static string[] s_Path =
{
"Tests",
"GraphicsTests",
"RenderPipeline"
};
public static Dictionary<string, string> renderPipelineAssets = new Dictionary<string, string>()
{
{ "HDRP", "Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/HDRP_GraphicTests_Asset.asset" },
{ "LWRP", "Tests/GraphicsTests/RenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset" }
};
// Renderpipeline assets used for the tests
public static Dictionary<string, string> renderPipelineScenesFolder = new Dictionary<string, string>()
{
{ "HDRP", "HDRenderPipeline/Scenes" },
{ "LWRP", "LightweightPipeline" }
};
// info that gets generated for use
// in a dod way
public struct TestInfo
{
public string name;
public float threshold;
public string relativePath;
public string templatePath;
public int frameWait;
public override string ToString()
{
return name;
}
}
// collect the scenes that we can use
public static class CollectScenes
{
public static IEnumerable HDRP
{
get
{
return GetScenesForPipelineID("HDRP");
}
}
public static IEnumerable HDRP_Params
{
get
{
return GetScenesForPipelineID("HDRP", true);
}
}
public static IEnumerable LWRP
{
get
{
return GetScenesForPipelineID("LWRP");
}
}
public static IEnumerable GetScenesForPipelineID(string _pipelineID, bool fixtureParam = false)
{
return GetScenesForPipeline(renderPipelineScenesFolder[_pipelineID]);
}
public static IEnumerable GetScenesForPipeline(string _pipelinePath, bool fixtureParam = false)
{
var absoluteScenesPath = s_Path.Aggregate(s_RootPath, Path.Combine);
var filesPath = Path.Combine(absoluteScenesPath, _pipelinePath);
// find all the scenes
var allPaths = Directory.GetFiles(filesPath, "*.unity", SearchOption.AllDirectories);
// Convert to List for easy sorting in alphabetical order
List<string> allPaths_List = new List<string>(allPaths);
allPaths_List.Sort();
// construct all the needed test infos
for (int i = 0; i < allPaths_List.Count; ++i)
{
var path = allPaths_List[i];
var p = new FileInfo(path);
var split = s_Path.Aggregate("", Path.Combine);
split = string.Format("{0}{1}", split, Path.DirectorySeparatorChar);
var splitPaths = p.FullName.Split(new[] { split }, StringSplitOptions.RemoveEmptyEntries);
TestInfo testInfo = new TestInfo()
{
name = p.Name,
relativePath = splitPaths.Last(),
templatePath = splitPaths.Last(),
threshold = 0.02f,
frameWait = 100
};
if (fixtureParam)
yield return new TestFixtureData(testInfo);
else
yield return testInfo;
}
}
}
public static class CollectScenesPlayMode
{
public static IEnumerable HDRP
{
get
{
return GetScenesForPipelineID("HDRP");
}
}
public static IEnumerable HDRP_Param
{
get
{
return GetScenesForPipelineID("HDRP", true);
}
}
public static IEnumerable LWRP
{
get
{
return GetScenesForPipelineID("LWRP");
}
}
public static IEnumerable GetScenesForPipelineID(string _pipelineID, bool fixtureParam = false)
{
return GetScenesForPipeline(renderPipelineScenesFolder[_pipelineID]);
}
public static IEnumerable GetScenesForPipeline(string _pipelinePath, bool fixtureParam = false)
{
var absoluteScenesPath = s_Path.Aggregate("Assets", Path.Combine);
var filesPath = Path.Combine(absoluteScenesPath, _pipelinePath);
string listFilePath = Path.Combine(filesPath, "EditorPlayModeTests.asset");
EditorPlayModeTests listFile = (EditorPlayModeTests) AssetDatabase.LoadMainAssetAtPath(listFilePath);
if ( listFile == null)
{
yield return null;
}
else
{
foreach (string path in listFile.scenesPath)
{
var p = new FileInfo(path);
var split = s_Path.Aggregate("", Path.Combine);
split = string.Format("{0}{1}", split, Path.DirectorySeparatorChar);
var splitPaths = p.FullName.Split(new[] { split }, StringSplitOptions.RemoveEmptyEntries);
TestInfo testInfo = new TestInfo
{
name = p.Name,
relativePath = path,
templatePath = splitPaths.Last(),
threshold = 0.02f,
frameWait = 100
};
if (fixtureParam)
yield return new TestFixtureData(testInfo);
else
yield return testInfo;
}
}
}
}
// compare textures, use RMS for this
public static bool CompareTextures(Texture2D fromDisk, Texture2D captured, float threshold)
{
if (fromDisk == null || captured == null)
return false;
if (fromDisk.width != captured.width
|| fromDisk.height != captured.height)
return false;
var pixels1 = fromDisk.GetPixels();
var pixels2 = captured.GetPixels();
if (pixels1.Length != pixels2.Length)
return false;
int numberOfPixels = pixels1.Length;
float sumOfSquaredColorDistances = 0;
for (int i = 0; i < numberOfPixels; i++)
{
Color p1 = pixels1[i];
Color p2 = pixels2[i];
Color diff = p1 - p2;
diff = diff * diff;
sumOfSquaredColorDistances += (diff.r + diff.g + diff.b) / 3.0f;
}
float rmse = Mathf.Sqrt(sumOfSquaredColorDistances / numberOfPixels);
return rmse < threshold;
}
public static Texture2D RenderSetupToTexture( SetupSceneForRenderPipelineTest _testSetup)
{
// Setup Render Target
Camera testCamera = _testSetup.cameraToUse;
var rtDesc = new RenderTextureDescriptor(
_testSetup.width,
_testSetup.height,
(_testSetup.hdr && testCamera.allowHDR) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32,
24);
rtDesc.sRGB = PlayerSettings.colorSpace == ColorSpace.Linear;
rtDesc.msaaSamples = _testSetup.msaaSamples;
// render the scene
var tempTarget = RenderTexture.GetTemporary(rtDesc);
var oldTarget = _testSetup.cameraToUse.targetTexture;
_testSetup.cameraToUse.targetTexture = tempTarget;
_testSetup.cameraToUse.Render();
_testSetup.cameraToUse.targetTexture = oldTarget;
// Readback the rendered texture
var oldActive = RenderTexture.active;
RenderTexture.active = tempTarget;
var captured = new Texture2D(tempTarget.width, tempTarget.height, TextureFormat.RGB24, false);
captured.ReadPixels(new Rect(0, 0, _testSetup.width, _testSetup.height), 0, 0);
RenderTexture.active = oldActive;
return captured;
}
public static bool FindReferenceImage(TestInfo _testInfo, ref Texture2D _fromDisk, Texture2D _captured, ref string _dumpFileLocation)
{
var templatePath = Path.Combine(s_RootPath, "ImageTemplates");
// find the reference image
_dumpFileLocation = Path.Combine(templatePath, string.Format("{0}.{1}", _testInfo.templatePath, "png"));
Debug.Log("Template file at: " + _dumpFileLocation);
if (!File.Exists(_dumpFileLocation))
{
// no reference exists, create it
var fileInfo = new FileInfo(_dumpFileLocation);
fileInfo.Directory.Create();
var generated = _captured.EncodeToPNG();
File.WriteAllBytes(_dumpFileLocation, generated);
return false;
}
var template = File.ReadAllBytes(_dumpFileLocation);
_fromDisk.LoadImage(template, false);
return true;
}
public static class AssertFix
{
public static void TestWithMessages( bool? _comparison, string _pass, string _fail)
{
if (_comparison.HasValue)
{
if (_comparison.Value)
NUnit.Framework.Assert.IsTrue(true, _pass);
else
throw new System.Exception(_fail);
}
else
throw new System.Exception("Test comparison is null.");
}
public static void TestWithMessages(bool? _comparison)
{
TestWithMessages(_comparison, "Test passed.", "Test failed");
}
}
}
}

11
Tests/GraphicsTests/Framework/TestFrameworkTools.cs.meta


fileFormatVersion: 2
guid: dedd006681411204b867443efb1134e5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

18
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Scripts/DebugViewController.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
public class DebugViewController : MonoBehaviour
{
[SerializeField] FullScreenDebugMode fullScreenDebugMode = FullScreenDebugMode.None;
[ContextMenu("Set Debug View")]
public void SetDebugView()
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
hdPipeline.debugDisplaySettings.fullScreenDebugMode = fullScreenDebugMode;
}
}

11
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Scripts/DebugViewController.cs.meta


fileFormatVersion: 2
guid: a9ad82d3a5300af40a7a6a9927907436
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

15
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/EditorPlayModeTests.asset


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 0baa057a399734241b8f30441a73b429, type: 3}
m_Name: EditorPlayModeTests
m_EditorClassIdentifier:
scenesPath:
- Assets/Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/3xxx_DebugView/3002_ObjectMotionVector.unity

8
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/EditorPlayModeTests.asset.meta


fileFormatVersion: 2
guid: 4ebd64f3ce5398c4197b68e6182e066f
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存