浏览代码

Merge pull request #304 from Unity-Technologies/randomize-seed-in-usim-window

added uint field element for random seeds
/0.8.0.preview.4_staging
Aryan Mann 3 年前
当前提交
ea020460
共有 12 个文件被更改,包括 319 次插入4 次删除
  1. 2
      com.unity.perception/CHANGELOG.md
  2. 8
      com.unity.perception/Editor/Randomization/Uxml/RunInUnitySimulationWindow.uxml
  3. 32
      com.unity.perception/Editor/Randomization/Editors/RunInUnitySimulationWindow.cs
  4. 1
      com.unity.perception/Editor/Randomization/Editors/ScenarioBaseEditor.cs
  5. 8
      com.unity.perception/Editor/Randomization/VisualElements/Basic.meta
  6. 11
      com.unity.perception/Editor/Randomization/PropertyDrawers/UIntDrawer.cs.meta
  7. 51
      com.unity.perception/Editor/Randomization/PropertyDrawers/UIntDrawer.cs
  8. 136
      com.unity.perception/Editor/Randomization/VisualElements/Basic/UIntField.cs
  9. 11
      com.unity.perception/Editor/Randomization/VisualElements/Basic/UIntField.cs.meta
  10. 52
      com.unity.perception/Editor/Randomization/VisualElements/Basic/UxmlUIntAttributeDescription.cs
  11. 11
      com.unity.perception/Editor/Randomization/VisualElements/Basic/UxmlUIntAttributeDescription.cs.meta

2
com.unity.perception/CHANGELOG.md


### Added
Added support for 'step' button in editor.
Added random seed field to the Run in Unity Simulation Window
### Changed
### Deprecated

8
com.unity.perception/Editor/Randomization/Uxml/RunInUnitySimulationWindow.uxml


tooltip="The number of scenario iterations to execute"/>
<editor:IntegerField name="instance-count" label="Instance Count" max-value="10000"
tooltip="The number of instances to distribute the work load across"/>
<VisualElement style="flex-direction: row;">
<editor:UIntField name="random-seed" label="Random Seed" style="flex-grow: 1;"
tooltip="The initial random seed to use for the simulation"/>
<Button name="randomize-seed" text="Randomize"/>
</VisualElement>
<VisualElement class="unity-base-field"
tooltip="The compute resources configuration to execute the simulation with">
<Label text="Sys-Param" class="unity-base-field__label"/>

<Label name="prev-run-name" text="Run Name: " class="sim-window__label-prev-result"/>
<Label name="project-id" text="Project ID: " class="sim-window__label-prev-result"/>
<Label name="execution-id" text="Execution ID: " class="sim-window__label-prev-result"/>
<Label name="prev-random-seed" text="Random Seed: " class="sim-window__label-prev-result"/>
<Button name="copy-prev-random-seed" text="Copy Seed" style="flex-grow: 1; flex-shrink: 0;"/>
</VisualElement>
</VisualElement>
</VisualElement>

32
com.unity.perception/Editor/Randomization/Editors/RunInUnitySimulationWindow.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;

using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Perception.Randomization.Samplers;
using Random = System.Random;
namespace UnityEditor.Perception.Randomization
{

IntegerField m_InstanceCountField;
TextField m_RunNameField;
IntegerField m_TotalIterationsField;
UIntField m_RandomSeedField;
ToolbarMenu m_SysParamMenu;
int m_SysParamIndex;
ObjectField m_ScenarioConfigField;

Label m_PrevExecutionIdLabel;
Label m_PrevRandomSeedLabel;
const string m_SupportedGPUString = "NVIDIA";
[MenuItem("Window/Run in Unity Simulation")]
static void ShowWindow()

m_RunNameField = root.Q<TextField>("run-name");
m_TotalIterationsField = root.Q<IntegerField>("total-iterations");
m_InstanceCountField = root.Q<IntegerField>("instance-count");
m_RandomSeedField = root.Q<UIntField>("random-seed");
var randomizeSeedButton = root.Q<Button>("randomize-seed");
randomizeSeedButton.clicked += () =>
{
var bytes = new byte[4];
new Random().NextBytes(bytes);
m_RandomSeedField.value = BitConverter.ToUInt32(bytes, 0);
};
m_SysParamDefinitions = API.GetSysParams();
m_SysParamMenu = root.Q<ToolbarMenu>("sys-param");

m_PrevRunNameLabel = root.Q<Label>("prev-run-name");
m_ProjectIdLabel = root.Q<Label>("project-id");
m_PrevExecutionIdLabel = root.Q<Label>("execution-id");
m_PrevRandomSeedLabel = root.Q<Label>("prev-random-seed");
var copyExecutionIdButton = root.Q<Button>("copy-execution-id");
copyExecutionIdButton.clicked += () =>

copyProjectIdButton.clicked += () =>
EditorGUIUtility.systemCopyBuffer = CloudProjectSettings.projectId;
var copyPrevRandomSeedButton = root.Q<Button>("copy-prev-random-seed");
copyPrevRandomSeedButton.clicked += () =>
EditorGUIUtility.systemCopyBuffer = PlayerPrefs.GetString("SimWindow/prevRandomSeed");
SetFieldsFromPlayerPreferences();
}

m_TotalIterationsField.value = PlayerPrefs.GetInt("SimWindow/totalIterations");
m_InstanceCountField.value = PlayerPrefs.GetInt("SimWindow/instanceCount");
m_SysParamIndex = PlayerPrefs.GetInt("SimWindow/sysParamIndex");
var prevRandomSeed = PlayerPrefs.GetString("SimWindow/prevRandomSeed");
m_RandomSeedField.value = string.IsNullOrEmpty(prevRandomSeed)
? SamplerUtility.largePrime : uint.Parse(prevRandomSeed);
m_PrevRandomSeedLabel.text = $"Random Seed: {PlayerPrefs.GetString("SimWindow/prevRandomSeed")}";
}
static string IncrementRunName(string runName)

runName = m_RunNameField.value,
totalIterations = m_TotalIterationsField.value,
instanceCount = m_InstanceCountField.value,
randomSeed = m_RandomSeedField.value,
sysParamIndex = m_SysParamIndex,
scenarioConfig = (TextAsset)m_ScenarioConfigField.value,
currentOpenScenePath = SceneManager.GetSceneAt(0).path,

var constants = configuration["constants"];
constants["totalIterations"] = m_RunParameters.totalIterations;
constants["instanceCount"] = m_RunParameters.instanceCount;
constants["randomSeed"] = m_RunParameters.randomSeed;
var appParamName = $"{m_RunParameters.runName}";
var appParamsString = JsonConvert.SerializeObject(configuration, Formatting.Indented);

PlayerPrefs.SetString("SimWindow/prevExecutionId", run.executionId);
PlayerPrefs.SetInt("SimWindow/totalIterations", m_RunParameters.totalIterations);
PlayerPrefs.SetInt("SimWindow/instanceCount", m_RunParameters.instanceCount);
PlayerPrefs.SetString("SimWindow/prevRandomSeed", m_RunParameters.randomSeed.ToString());
PlayerPrefs.SetInt("SimWindow/sysParamIndex", m_RunParameters.sysParamIndex);
PlayerPrefs.SetString("SimWindow/scenarioConfig",
m_RunParameters.scenarioConfig != null ? m_RunParameters.scenarioConfigAssetPath : string.Empty);

public string runName;
public int totalIterations;
public int instanceCount;
public uint randomSeed;
public int sysParamIndex;
public TextAsset scenarioConfig;
public string currentOpenScenePath;

1
com.unity.perception/Editor/Randomization/Editors/ScenarioBaseEditor.cs


using System.IO;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Perception.Randomization.Scenarios;
using UnityEngine.UIElements;

8
com.unity.perception/Editor/Randomization/VisualElements/Basic.meta


fileFormatVersion: 2
guid: 93e88a2d53dd88f42ae287310c2a6ca3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

11
com.unity.perception/Editor/Randomization/PropertyDrawers/UIntDrawer.cs.meta


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

51
com.unity.perception/Editor/Randomization/PropertyDrawers/UIntDrawer.cs


using System;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
namespace UnityEditor.Perception.Randomization.PropertyDrawers
{
[CustomPropertyDrawer(typeof(uint))]
class UIntDrawer : PropertyDrawer
{
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
var field = new UIntField
{
label = property.displayName,
value = (uint)property.longValue
};
//Binding does not work on this custom UI Element field that we have created, so we need to use the change event
field.RegisterValueChangedCallback(evt =>
{
field.value = evt.newValue;
property.longValue = evt.newValue;
property.serializedObject.ApplyModifiedProperties();
});
// Create a surrogate integer field to detect and pass along external change events (non UI event) on the underlying serialized property.
var surrogateField = new IntegerField();
field.Add(surrogateField);
surrogateField.style.display = DisplayStyle.Flex;
surrogateField.bindingPath = property.propertyPath;
surrogateField.RegisterValueChangedCallback(evt =>
{
evt.StopImmediatePropagation();
field.value = UIntField.ClampInput(property.longValue);
});
return field;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.PropertyField(position, property, label, true);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUI.GetPropertyHeight(property);
}
}
}

136
com.unity.perception/Editor/Randomization/VisualElements/Basic/UIntField.cs


using System;
using System.Globalization;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.UIElements
{
/// <summary>
/// <para>Makes a text field for entering an unsigned integer.</para>
/// </summary>
public class UIntField : TextValueField<uint>
{
/// <summary>
/// <para>USS class name of elements of this type.</para>
/// </summary>
public new static readonly string ussClassName = "unity-uint-field";
/// <summary>
/// <para>USS class name of labels in elements of this type.</para>
/// </summary>
public new static readonly string labelUssClassName = ussClassName + "__label";
/// <summary>
/// <para>USS class name of input elements in elements of this type.</para>
/// </summary>
public new static readonly string inputUssClassName = ussClassName + "__input";
/// <summary>
/// <para>Constructor.</para>
/// </summary>
public UIntField()
: this(null) { }
/// <summary>
/// <para>Constructor.</para>
/// </summary>
/// <param name="maxLength">Maximum number of characters the field can take.</param>
public UIntField(int maxLength)
: this(null, maxLength) { }
public UIntField(string label, int maxLength = -1)
: base(label, maxLength, new UIntInput())
{
AddToClassList(ussClassName);
labelElement.AddToClassList(labelUssClassName);
labelElement.AddToClassList("unity-property-field__label");
AddLabelDragger<uint>();
}
UIntInput uIntInput => (UIntInput)textInputBase;
/// <summary>
/// <para>Converts the given uint to a string.</para>
/// </summary>
/// <param name="v">The uint to be converted to string.</param>
/// <returns>
/// <para>The uint as string.</para>
/// </returns>
protected override string ValueToString(uint v)
{
return v.ToString(formatString, CultureInfo.InvariantCulture.NumberFormat);
}
/// <summary>
/// <para>Converts a string to an uint.</para>
/// </summary>
/// <param name="str">The string to convert.</param>
/// <returns>
/// <para>The uint parsed from the string.</para>
/// </returns>
protected override uint StringToValue(string str)
{
long.TryParse(str, out var result);
return ClampInput(result);
}
/// <summary>
/// <para>Modify the value using a 3D delta and a speed, typically coming from an input device.</para>
/// </summary>
/// <param name="delta">A vector used to compute the value change.</param>
/// <param name="speed">A multiplier for the value change.</param>
/// <param name="startValue">The start value.</param>
public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, uint startValue)
{
uIntInput.ApplyInputDeviceDelta(delta, speed, startValue);
}
/// <summary>
/// <para>Instantiates an UIntField using the data read from a UXML file.</para>
/// </summary>
public new class UxmlFactory : UxmlFactory<UIntField, UxmlTraits> { }
/// <summary>
/// <para>Defines UxmlTraits for the UIntField.</para>
/// </summary>
public new class UxmlTraits : TextValueFieldTraits<uint, UxmlUIntAttributeDescription> { }
public static uint ClampInput(long input)
{
input = input > uint.MaxValue ? uint.MaxValue : input;
input = input < uint.MinValue ? uint.MinValue : input;
return (uint)input;
}
class UIntInput : TextValueInput
{
internal UIntInput()
{
formatString = "#######0";
}
UIntField parentUIntField => (UIntField)parent;
protected override string allowedCharacters => "0123456789";
public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, uint startValue)
{
var num = StringToValue(text) + (long)Math.Round(delta.x);
var value = ClampInput(num);
if (parentUIntField.isDelayed)
text = ValueToString(value);
else
parentUIntField.value = value;
}
protected override string ValueToString(uint v)
{
return v.ToString(formatString);
}
protected override uint StringToValue(string str)
{
long.TryParse(str, out var result);
return ClampInput(result);
}
}
}
}

11
com.unity.perception/Editor/Randomization/VisualElements/Basic/UIntField.cs.meta


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

52
com.unity.perception/Editor/Randomization/VisualElements/Basic/UxmlUIntAttributeDescription.cs


using System;
using System.Globalization;
namespace UnityEngine.UIElements
{
/// <summary>
/// <para>Describes a XML int attribute.</para>
/// </summary>
public class UxmlUIntAttributeDescription : TypedUxmlAttributeDescription<uint>
{
/// <summary>
/// <para>Constructor.</para>
/// </summary>
public UxmlUIntAttributeDescription()
{
type = "int";
typeNamespace = "http://www.w3.org/2001/XMLSchema";
defaultValue = 0;
}
/// <summary>
/// <para>The default value for the attribute, as a string.</para>
/// </summary>
public override string defaultValueAsString => defaultValue.ToString(CultureInfo.InvariantCulture.NumberFormat);
/// <summary>
/// <para>
/// Retrieves the value of this attribute from the attribute bag. Returns it if it is found, otherwise return
/// defaultValue.
/// </para>
/// </summary>
/// <param name="bag">The bag of attributes.</param>
/// <param name="cc">The context in which the values are retrieved.</param>
/// <returns>
/// <para>The value of the attribute.</para>
/// </returns>
public override uint GetValueFromBag(IUxmlAttributes bag, CreationContext cc)
{
return GetValueFromBag(bag, cc, (s, i) => ConvertValueToUInt(s, i), defaultValue);
}
public bool TryGetValueFromBag(IUxmlAttributes bag, CreationContext cc, ref uint value)
{
return TryGetValueFromBag(bag, cc, (s, i) => ConvertValueToUInt(s, i), defaultValue, ref value);
}
static uint ConvertValueToUInt(string v, uint defaultValue)
{
return v == null || !uint.TryParse(v, out uint result) ? defaultValue : result;
}
}
}

11
com.unity.perception/Editor/Randomization/VisualElements/Basic/UxmlUIntAttributeDescription.cs.meta


fileFormatVersion: 2
guid: 2e94e3964dd6654488e74ca218f23111
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存