浏览代码

added run in USim window

/usim-randomization
Steven Leal 4 年前
当前提交
62e505d4
共有 12 个文件被更改,包括 333 次插入38 次删除
  1. 194
      com.unity.perception/Editor/Randomization/RunInUSimWindow.cs
  2. 15
      com.unity.perception/Editor/Randomization/Uxml/RunInUSimWindow.uxml
  3. 3
      com.unity.perception/Editor/Unity.Perception.Editor.asmdef
  4. 7
      com.unity.perception/Runtime/Randomization/Scenarios/Scenario.cs
  5. 10
      com.unity.perception/Runtime/Randomization/Scenarios/ScenarioBase.cs
  6. 1
      com.unity.perception/Tests/Runtime/Randomization/ScenarioTests.cs
  7. 59
      com.unity.perception/Editor/Randomization/PositiveIntegerField.cs
  8. 3
      com.unity.perception/Editor/Randomization/PositiveIntegerField.cs.meta
  9. 30
      com.unity.perception/Runtime/Randomization/Scenarios/FixedFrameCountScenario.cs
  10. 3
      com.unity.perception/Runtime/Randomization/Scenarios/FixedFrameCountScenario.cs.meta
  11. 43
      com.unity.perception/Runtime/Randomization/Scenarios/USimScenario.cs
  12. 3
      com.unity.perception/Runtime/Randomization/Scenarios/USimScenario.cs.meta

194
com.unity.perception/Editor/Randomization/RunInUSimWindow.cs


using System;
using System.Collections.Generic;
using System.Threading;
using Boo.Lang.Runtime;
using Unity.Simulation.Client;
using UnityEngine.SceneManagement;
using UnityEngine.Perception.Randomization.Scenarios;
using UnityEngine.UIElements;
using ZipUtility;

{
SceneAsset m_MainScene;
USimScenario m_Scenario;
SysParamDefinition m_SysParam;
string m_RunName;
string m_BuildZipPath;
int m_TotalIterations;
int m_InstanceCount;
[MenuItem("Window/Run in USim")]
public static void ShowWindow()

}
void OnEnable()
{
Project.Activate();
Project.clientReadyStateChanged += CreateEstablishingConnectionUI;
CreateEstablishingConnectionUI(Project.projectIdState);
}
void CreateEstablishingConnectionUI(Project.State state)
{
rootVisualElement.Clear();
if (Project.projectIdState == Project.State.Pending)
{
var waitingText = new TextElement();
waitingText.text = "Waiting for connection to Unity Cloud...";
rootVisualElement.Add(waitingText);
}
else if (Project.projectIdState == Project.State.Invalid)
{
var waitingText = new TextElement();
waitingText.text = "The current project must be associated with a valid Unity Cloud project " +
"to run in Unity Simulation";
rootVisualElement.Add(waitingText);
}
else
{
CreateRunInUSimUI();
}
}
/// <summary>
/// Enables a visual element to remember values between editor sessions
/// </summary>
static void SetViewDataKey(VisualElement element)
{
element.viewDataKey = $"RunInUSim_{element.name}";
}
void CreateRunInUSimUI()
// root.Bind(this);
var runNameField = root.Q<TextField>("run-name");
runNameField.RegisterCallback<ChangeEvent<string>>(evt => { m_RunName = evt.newValue; });
SetViewDataKey(runNameField);
var totalIterationsField = root.Q<IntegerField>("total-iterations");
totalIterationsField.RegisterCallback<ChangeEvent<int>>(evt => { m_TotalIterations = evt.newValue; });
SetViewDataKey(totalIterationsField);
var instanceCountField = root.Q<IntegerField>("instance-count");
instanceCountField.RegisterCallback<ChangeEvent<int>>(evt => { m_InstanceCount = evt.newValue; });
instanceCountField.viewDataKey = "RunInUSim_instanceCount";
SetViewDataKey(instanceCountField);
var mainSceneField = root.Q<ObjectField>("main-scene");
mainSceneField.objectType = typeof(SceneAsset);
mainSceneField.RegisterCallback<ChangeEvent<Object>>(evt => { m_MainScene = (SceneAsset)evt.newValue; });
var scenarioField = root.Q<ObjectField>("scenario");
scenarioField.objectType = typeof(ScenarioBase);
scenarioField.RegisterCallback<ChangeEvent<Object>>(evt => { m_Scenario = (USimScenario)evt.newValue; });
var sysParamDefinitions = API.GetSysParams();
var sysParamMenu = root.Q<ToolbarMenu>("sys-param");
foreach (var definition in sysParamDefinitions)
sysParamMenu.menu.AppendAction(definition.description, action => m_SysParam = definition);
sysParamMenu.text = sysParamDefinitions[0].description;
m_SysParam = sysParamDefinitions[0];
var runButton = root.Q<Button>("run-button");
runButton.clicked += RunInUSim;
bool CreateLinuxBuildAndZip(string buildName)
void RunInUSim()
var pathToZip = string.Empty;
ValidateSettings();
CreateLinuxBuildAndZip();
StartUSimRun();
}
void ValidateSettings()
{
if (string.IsNullOrEmpty(m_RunName))
throw new RuntimeException("Invalid run name");
if (m_Scenario == null)
throw new RuntimeException("Null scenario");
if (m_MainScene == null)
throw new RankException("Null main scene");
}
void CreateLinuxBuildAndZip()
{
// Create build directory
if (!Directory.Exists(pathToProjectBuild + buildName))
Directory.CreateDirectory(pathToProjectBuild + buildName);
if (!Directory.Exists(pathToProjectBuild + m_RunName))
Directory.CreateDirectory(pathToProjectBuild + m_RunName);
pathToProjectBuild = pathToProjectBuild + buildName + "/";
pathToProjectBuild = pathToProjectBuild + m_RunName + "/";
Debug.Log("Creating Linux build...");
scenes = new[] { "Assets/Scenes/MainScene.unity" },
locationPathName = Path.Combine(pathToProjectBuild,buildName + ".x86_64"),
scenes = new[] { AssetDatabase.GetAssetPath(m_MainScene) },
locationPathName = Path.Combine(pathToProjectBuild, m_RunName + ".x86_64"),
if (summary.result != BuildResult.Succeeded)
throw new RuntimeException($"Build did not succeed: status = {summary.result}");
Debug.Log("Created Linux build");
if (summary.result == BuildResult.Succeeded)
// Zip the build
Debug.Log("Starting to zip...");
var buildFolder = Application.dataPath + "/../" + "Build/" + m_RunName;
Zip.DirectoryContents(buildFolder, m_RunName);
m_BuildZipPath = buildFolder + ".zip";
Debug.Log("Created build zip");
}
List<AppParam> GenerateAppParamIds(CancellationToken token)
{
var appParamIds = new List<AppParam>();
for (var i = 0; i < m_InstanceCount; i++)
Debug.Log("Build succeeded.");
EditorUtility.DisplayProgressBar("Compress Project", "Compressing Project Build...", 0);
ulong totalSize = summary.totalSize;
if (token.IsCancellationRequested)
return null;
var appParamName = $"{m_RunName}_{i}";
var appParamId = API.UploadAppParam(appParamName, new USimConstants
{
totalIterations = m_TotalIterations,
instanceCount = m_InstanceCount,
instanceIndex = i
});
appParamIds.Add(new AppParam()
{
id = appParamId,
name = appParamName,
num_instances = 1
});
}
return appParamIds;
}
// Zip the build
pathToZip = Application.dataPath + "/../" + "Build/" + buildName;
async void StartUSimRun()
{
var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
Zip.DirectoryContents(pathToZip, buildName);
Debug.Log("Uploading build...");
var buildId = await API.UploadBuildAsync(
m_RunName,
m_BuildZipPath,
cancellationTokenSource: cancellationTokenSource);
EditorUtility.ClearProgressBar();
Debug.Log($"Build upload complete: build id {buildId}");
// Return path to .zip file
string[] st = Directory.GetFiles(pathToZip + "/../", buildName + ".zip");
if (st.Length != 0)
pathToZip = Path.GetFullPath(st[0]);
else
return false;
}
else
var appParams = GenerateAppParamIds(token);
if (token.IsCancellationRequested)
return;
Debug.Log($"Generated app-param ids: {appParams.Count}");
var runDefinitionId = API.UploadRunDefinition(new RunDefinition
// m_BuildZipPathField.value = null;
return false;
}
// m_BuildZipPathField.value = pathToZip;
app_params = appParams.ToArray(),
name = m_RunName,
sys_param_id = m_SysParam.id,
build_id = buildId
});
Debug.Log($"Run definition upload complete: run definition id {runDefinitionId}");
return true;
var run = Run.CreateFromDefinitionId(runDefinitionId);
run.Execute();
cancellationTokenSource.Dispose();
Debug.Log("Executed run");
}
}
}

15
com.unity.perception/Editor/Randomization/Uxml/RunInUSimWindow.uxml


<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements">
<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements" xmlns:randEditor="UnityEngine.Perception.Randomization.Editor">
<editor:ObjectField allow-scene-objects="false" bindingPath="m_MainScene"/>
<TextField name="run-name" label="Run Name"/>
<randEditor:PositiveIntegerField name="total-iterations" label="Total Iterations"/>
<randEditor:PositiveIntegerField name="instance-count" label="Instance Count" max-value="10000"/>
<editor:ObjectField name="main-scene" label="Main Scene" allow-scene-objects="false"/>
<editor:ObjectField name="scenario" label="Scenario"/>
<VisualElement class="unity-base-field">
<Label text="USim worker config" class="unity-base-field__label"/>
<editor:ToolbarMenu name="sys-param" class="unity-base-field__input" style="border-width: 1px;"/>
</VisualElement>
<VisualElement style="align-items: center;">
<Button name="run-button" text="Build and Run" style="margin-top: 20px; padding: 2 20; font-size: 13px;"/>
</VisualElement>
</VisualElement>
</UXML>

3
com.unity.perception/Editor/Unity.Perception.Editor.asmdef


"Unity.Perception.Runtime",
"PathCreatorEditor",
"PathCreator",
"UnityEngine.UI"
"UnityEngine.UI",
"Unity.Simulation.Client.Editor"
],
"includePlatforms": [
"Editor"

7
com.unity.perception/Runtime/Randomization/Scenarios/Scenario.cs


using System.IO;
using System;
using System.IO;
namespace UnityEngine.Perception.Randomization.Scenarios
{

/// <summary>
/// Serializes this scenario's constants to a json file in the Unity StreamingAssets folder
/// </summary>
public sealed override void Serialize()
public override void Serialize()
{
Directory.CreateDirectory(Application.dataPath + "/StreamingAssets/");
using (var writer = new StreamWriter(serializedConstantsFilePath, false))

/// Deserializes this scenario's constants from a json file in the Unity StreamingAssets folder
/// </summary>
/// <exception cref="ScenarioException"></exception>
public sealed override void Deserialize()
public override void Deserialize()
{
if (!File.Exists(serializedConstantsFilePath))
throw new ScenarioException($"JSON scenario constants file does not exist at path {serializedConstantsFilePath}");

10
com.unity.perception/Runtime/Randomization/Scenarios/ScenarioBase.cs


/// </summary>
public abstract void Deserialize();
/// <summary>
/// Increments the scenario's currentIteration. Can be overriden to increment by values other than 1.
/// </summary>
public virtual void IncrementIteration()
{
currentIteration++;
}
void OnEnable()
{
ActiveScenario = this;

framesSinceInitialization++;
if (isIterationComplete)
{
currentIteration++;
IncrementIteration();
currentIterationFrame = 0;
OnIterationTeardown();
}

1
com.unity.perception/Tests/Runtime/Randomization/ScenarioTests.cs


// TODO: update this function once the perception camera doesn't skip the first frame
IEnumerator CreateNewScenario(int totalIterations, int framesPerIteration)
{
m_Scenario = m_TestObject.AddComponent<FixedLengthScenario>();
m_Scenario.quitOnComplete = false;
m_Scenario.constants.totalIterations = totalIterations;

59
com.unity.perception/Editor/Randomization/PositiveIntegerField.cs


using System;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UnityEngine.Perception.Randomization.Editor
{
public class PositiveIntegerField : IntegerField
{
public int maxValue = int.MaxValue;
public PositiveIntegerField()
{
RegisterValueClamping();
}
public PositiveIntegerField(int maxValue)
{
this.maxValue = maxValue;
RegisterValueClamping();
}
public PositiveIntegerField(SerializedProperty property, int maxValue=int.MaxValue) : this(maxValue)
{
this.BindProperty(property);
}
void RegisterValueClamping()
{
this.RegisterValueChangedCallback(evt =>
{
value = math.clamp(evt.newValue, 0, maxValue);
evt.StopImmediatePropagation();
});
}
public new class UxmlFactory : UxmlFactory<PositiveIntegerField, UxmlTraits> { }
public new class UxmlTraits : IntegerField.UxmlTraits
{
UxmlIntAttributeDescription m_Int = new UxmlIntAttributeDescription { name = "max-value", defaultValue = int.MaxValue };
public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription
{
get { yield break; }
}
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
if (!(ve is PositiveIntegerField positiveIntegerField))
return;
positiveIntegerField.maxValue = m_Int.GetValueFromBag(bag, cc);
}
}
}
}

3
com.unity.perception/Editor/Randomization/PositiveIntegerField.cs.meta


fileFormatVersion: 2
guid: ddab76638f764bac9bd4b213e5cf8ebe
timeCreated: 1597168414

30
com.unity.perception/Runtime/Randomization/Scenarios/FixedFrameCountScenario.cs


using System;
namespace UnityEngine.Perception.Randomization.Scenarios
{
/// <summary>
/// An example scenario where each iteration runs for a fixed number of frames
/// </summary>
[AddComponentMenu("Randomization/Scenarios/Fixed Frame Count Scenario")]
public class FixedFrameCountScenario : USimScenario
{
public int framesPerIteration;
public override bool isIterationComplete => currentIterationFrame >= framesPerIteration;
public FixedFrameCountScenario()
{
constants = new USimConstants
{
instanceCount = 1,
instanceIndex = 0,
totalIterations = 1000
};
}
public override void OnInitialize()
{
currentIteration = constants.instanceIndex;
}
}
}

3
com.unity.perception/Runtime/Randomization/Scenarios/FixedFrameCountScenario.cs.meta


fileFormatVersion: 2
guid: a5fd9d0784580a747b3764afd636fc5f
timeCreated: 1589939921

43
com.unity.perception/Runtime/Randomization/Scenarios/USimScenario.cs


using System;
namespace UnityEngine.Perception.Randomization.Scenarios
{
public abstract class USimScenario : Scenario<USimConstants>
{
public override bool isScenarioComplete => currentIteration >= constants.totalIterations;
public override void OnInitialize()
{
currentIteration = constants.instanceIndex;
}
public override void IncrementIteration()
{
currentIteration += constants.instanceCount;
}
public override void OnFrameStart()
{
Debug.Log($"{currentIteration}: {currentIterationFrame}");
}
public override void Deserialize()
{
if (!string.IsNullOrEmpty(Unity.Simulation.Configuration.Instance.SimulationConfig.app_param_uri))
{
Debug.Log("Reading app-params");
constants = Unity.Simulation.Configuration.Instance.GetAppParams<USimConstants>();
}
else
base.Deserialize();
}
}
[Serializable]
public struct USimConstants
{
public int totalIterations;
public int instanceCount;
public int instanceIndex;
}
}

3
com.unity.perception/Runtime/Randomization/Scenarios/USimScenario.cs.meta


fileFormatVersion: 2
guid: 1ef5313c07934eeabb46b852ab57ed79
timeCreated: 1597102599
正在加载...
取消
保存