浏览代码

Parameters are no longer MonoBehaviours

/usim-randomization
Steven Leal 4 年前
当前提交
23943522
共有 33 个文件被更改,包括 339 次插入293 次删除
  1. 25
      com.unity.perception/Editor/Randomization/CategoricalOptionElement.cs
  2. 72
      com.unity.perception/Editor/Randomization/ParameterConfigurationEditor.cs
  3. 4
      com.unity.perception/Editor/Randomization/ParameterDrawer.cs
  4. 4
      com.unity.perception/Editor/Randomization/ParameterDrawerElement.cs
  5. 126
      com.unity.perception/Editor/Randomization/ParameterElement.cs
  6. 16
      com.unity.perception/Editor/Randomization/SamplerElement.cs
  7. 6
      com.unity.perception/Editor/Randomization/Uxml/ParameterElement.uxml
  8. 50
      com.unity.perception/Runtime/Randomization/Configuration/ParameterConfiguration.cs
  9. 74
      com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameter.cs
  10. 9
      com.unity.perception/Runtime/Randomization/Parameters/Parameter.cs
  11. 7
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/BooleanParameter.cs
  12. 4
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorHsvaParameter.cs
  13. 4
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/FloatParameter.cs
  14. 7
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/IntegerParameter.cs
  15. 2
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/MaterialParameter.cs
  16. 5
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/StringParameter.cs
  17. 4
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector2Parameter.cs
  18. 4
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector3Parameter.cs
  19. 4
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector4Parameter.cs
  20. 21
      com.unity.perception/Tests/Runtime/Randomization/CategoricalParameterTests.cs
  21. 4
      com.unity.perception/Tests/Runtime/Randomization/ParameterConfigurationTests.cs
  22. 18
      com.unity.perception/Tests/Runtime/Randomization/ParameterTests.cs
  23. 2
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests.cs
  24. 20
      com.unity.perception/Tests/Runtime/Randomization/StructParameterTests.cs
  25. 15
      com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameterBase.cs
  26. 3
      com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameterBase.cs.meta
  27. 49
      com.unity.perception/Runtime/Randomization/Parameters/NumericParameter.cs
  28. 12
      com.unity.perception/Runtime/Randomization/Parameters/ICategoricalParameter.cs
  29. 3
      com.unity.perception/Runtime/Randomization/Parameters/ICategoricalParameter.cs.meta
  30. 18
      com.unity.perception/Runtime/Randomization/Parameters/StructParameter.cs
  31. 3
      com.unity.perception/Runtime/Randomization/Parameters/StructParameter.cs.meta
  32. 37
      com.unity.perception/Runtime/Randomization/Parameters/TypedParameter.cs
  33. 0
      /com.unity.perception/Runtime/Randomization/Parameters/NumericParameter.cs.meta

25
com.unity.perception/Editor/Randomization/CategoricalOptionElement.cs


SerializedProperty m_OptionsProperty;
SerializedProperty m_ProbabilitiesProperty;
public CategoricalOptionElement(SerializedProperty optionsProperty, SerializedProperty probabilitiesProperty, ListView view)
public CategoricalOptionElement(
SerializedProperty optionsProperty,
SerializedProperty probabilitiesProperty)
{
m_OptionsProperty = optionsProperty;
m_ProbabilitiesProperty = probabilitiesProperty;

template.CloneTree(this);
var removeButton = this.Q<Button>("remove");
removeButton.clicked += () =>
{
optionsProperty.DeleteArrayElementAtIndex(m_Index);
probabilitiesProperty.DeleteArrayElementAtIndex(m_Index);
optionsProperty.serializedObject.ApplyModifiedProperties();
view.Refresh();
};
}
// Called from categorical parameter

var indexLabel = this.Q<Label>("index-label");
indexLabel.text = $"[{m_Index}]";
var optionProperty = m_OptionsProperty.GetArrayElementAtIndex(i);
var option = this.Q<PropertyField>("option");
option.BindProperty(optionProperty);
var label = option.Q<Label>();
label.parent.Remove(label);
var probabilityProperty = m_ProbabilitiesProperty.GetArrayElementAtIndex(i);
var probability = this.Q<FloatField>("probability");
probability.RegisterValueChangedCallback((evt) =>

probability.labelElement.style.minWidth = 0;
probability.labelElement.style.marginRight = 4;
probability.BindProperty(probabilityProperty);
var optionProperty = m_OptionsProperty.GetArrayElementAtIndex(i);
var option = this.Q<PropertyField>("option");
option.BindProperty(optionProperty);
var label = option.Q<Label>();
label.parent.Remove(label);
}
}
}

72
com.unity.perception/Editor/Randomization/ParameterConfigurationEditor.cs


using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.Perception.Randomization.Configuration;
using UnityEngine.Perception.Randomization.Parameters;
using UnityEngine.Perception.Randomization.Parameters.Attributes;
using UnityEngine.Perception.Randomization.Samplers;
using UnityEngine.UIElements;

[CustomEditor(typeof(ParameterConfiguration))]
public class ParameterConfigurationEditor : UnityEditor.Editor
{
ParameterConfiguration m_Config;
public ParameterConfiguration config;
string m_FilterString = string.Empty;
public string FilterString
{

foreach (var child in m_ParameterContainer.Children())
{
var paramIndex = m_ParameterContainer.IndexOf(child);
var param = m_Config.parameters[paramIndex];
((ParameterElement)child).Filtered = param.parameterName.ToLower().Contains(lowerFilter);
var param = config.parameters[paramIndex];
((ParameterElement)child).Filtered = param.name.ToLower().Contains(lowerFilter);
}
}
}

m_Config = (ParameterConfiguration)target;
config = (ParameterConfiguration)target;
foreach (var parameter in m_Config.parameters)
m_ParameterContainer.Add(new ParameterElement(parameter, this));
var filter = m_Root.Q<TextField>("filter-parameters");
filter.RegisterValueChangedCallback((e) => { FilterString = e.newValue; });
var collapseAllButton = m_Root.Q<Button>("collapse-all");
collapseAllButton.clicked += () => CollapseParameters(true);
var expandAllButton = m_Root.Q<Button>("expand-all");
expandAllButton.clicked += () => CollapseParameters(false);
var parameterTypeMenu = m_Root.Q<ToolbarMenu>("parameter-type-menu");
foreach (var parameterType in StaticData.parameterTypes)

a => DropdownMenuAction.Status.Normal);
}
var filter = m_Root.Q<TextField>("filter-parameters");
filter.RegisterValueChangedCallback((e) => { FilterString = e.newValue; });
var collapseAllButton = m_Root.Q<Button>("collapse-all");
collapseAllButton.clicked += () => CollapseParameters(true);
var expandAllButton = m_Root.Q<Button>("expand-all");
expandAllButton.clicked += () => CollapseParameters(false);
RefreshParameterElements();
void CollapseParameters(bool collapsed)
void RefreshParameterElements()
foreach (var child in m_ParameterContainer.Children())
((ParameterElement)child).Collapsed = collapsed;
m_ParameterContainer.Clear();
for (var i = 0; i < config.parameters.Count; i++)
m_ParameterContainer.Add(CreateParameterElement(i));
}
ParameterElement CreateParameterElement(int index)
{
return new ParameterElement(index, this);
var parameter = m_Config.AddParameter(parameterType);
var parameter = config.AddParameter(parameterType);
parameter.hideFlags = HideFlags.HideInInspector;
m_ParameterContainer.Add(new ParameterElement(parameter, this));
serializedObject.Update();
m_ParameterContainer.Add(CreateParameterElement(config.parameters.Count - 1));
}
public void RemoveParameter(VisualElement template)

var param = m_Config.parameters[paramIndex];
m_Config.parameters.RemoveAt(paramIndex);
DestroyImmediate(param);
config.parameters.RemoveAt(paramIndex);
serializedObject.Update();
RefreshParameterElements();
}
public void ReorderParameter(int currentIndex, int nextIndex)

nextIndex--;
var parameterElement = m_ParameterContainer[currentIndex];
var parameter = m_Config.parameters[currentIndex];
var parameter = config.parameters[currentIndex];
m_Config.parameters.RemoveAt(currentIndex);
config.parameters.RemoveAt(currentIndex);
m_Config.parameters.Insert(nextIndex, parameter);
config.parameters.Insert(nextIndex, parameter);
serializedObject.Update();
RefreshParameterElements();
}
void CollapseParameters(bool collapsed)
{
foreach (var child in m_ParameterContainer.Children())
((ParameterElement)child).Collapsed = collapsed;
}
}
}

4
com.unity.perception/Editor/Randomization/ParameterDrawer.cs


using System;
/*
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;

}
}
}
*/

4
com.unity.perception/Editor/Randomization/ParameterDrawerElement.cs


using System.Collections.Generic;
/*
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;

}
}
}
*/

126
com.unity.perception/Editor/Randomization/ParameterElement.cs


{
public class ParameterElement : VisualElement
{
int m_ParameterIndex;
Parameter m_Parameter;
SerializedObject m_SerializedObject;
SerializedProperty m_SerializedProperty;
public int ParameterIndex => parent.IndexOf(this);
Parameter parameter => ConfigEditor.config.parameters[m_ParameterIndex];
CategoricalParameterBase categoricalParameter => (CategoricalParameterBase)parameter;
public int ParameterIndex => parent.IndexOf(this);
get => ClassListContains(k_CollapsedParameterClass);
get => parameter.collapsed;
parameter.collapsed = value;
if (value)
AddToClassList(k_CollapsedParameterClass);
else

}
}
public ParameterElement(Parameter parameter, ParameterConfigurationEditor paramConfigEditor)
public ParameterElement(int index, ParameterConfigurationEditor paramConfigEditor)
m_Parameter = parameter;
m_SerializedObject = new SerializedObject(parameter);
this.Bind(m_SerializedObject);
m_ParameterIndex = index;
m_SerializedProperty =
ConfigEditor.serializedObject.FindProperty("parameters").GetArrayElementAtIndex(m_ParameterIndex);
Collapsed = parameter.collapsed;
var parameterNameField = this.Q<TextField>("name");
parameterNameField.BindProperty(m_SerializedProperty.FindPropertyRelative("name"));
var targetField = this.Q<PropertyField>("target-field");
var frequencyField = this.Q<PropertyField>("application-frequency");
frequencyField.BindProperty(m_SerializedProperty.FindPropertyRelative("target.applicationFrequency"));
var targetField = this.Q<PropertyField>("target");
targetField.BindProperty(m_SerializedProperty.FindPropertyRelative("target.gameObject"));
targetField.RegisterCallback<ChangeEvent<Object>>((evt) =>
{
ClearTarget();

void ToggleTargetContainer()
{
m_TargetContainer.style.display = m_Parameter.hasTarget
m_TargetContainer.style.display = parameter.hasTarget
? new StyleEnum<DisplayStyle>(DisplayStyle.Flex)
: new StyleEnum<DisplayStyle>(DisplayStyle.None);
}

m_SerializedObject.FindProperty("target.component").objectReferenceValue = null;
m_SerializedObject.FindProperty("target.propertyName").stringValue = string.Empty;
m_SerializedObject.ApplyModifiedProperties();
m_SerializedProperty.FindPropertyRelative("target.component").objectReferenceValue = null;
m_SerializedProperty.FindPropertyRelative("target.propertyName").stringValue = string.Empty;
m_SerializedProperty.serializedObject.ApplyModifiedProperties();
m_SerializedObject.FindProperty("target.gameObject").objectReferenceValue = newTarget.gameObject;
m_SerializedObject.FindProperty("target.component").objectReferenceValue = newTarget.component;
m_SerializedObject.FindProperty("target.propertyName").stringValue = newTarget.propertyName;
m_SerializedObject.FindProperty("target.fieldOrProperty").enumValueIndex = (int)newTarget.fieldOrProperty;
m_SerializedObject.ApplyModifiedProperties();
m_TargetPropertyMenu.text = TargetPropertyDisplayText(m_Parameter.target);
m_SerializedProperty.FindPropertyRelative("target.gameObject").objectReferenceValue = newTarget.gameObject;
m_SerializedProperty.FindPropertyRelative("target.component").objectReferenceValue = newTarget.component;
m_SerializedProperty.FindPropertyRelative("target.propertyName").stringValue = newTarget.propertyName;
m_SerializedProperty.FindPropertyRelative("target.fieldOrProperty").enumValueIndex = (int)newTarget.fieldOrProperty;
m_SerializedProperty.serializedObject.ApplyModifiedProperties();
m_TargetPropertyMenu.text = TargetPropertyDisplayText(parameter.target);
}
static string TargetPropertyDisplayText(ParameterTarget target)

void FillPropertySelectMenu()
{
if (!m_Parameter.hasTarget)
if (!parameter.hasTarget)
m_TargetPropertyMenu.text = m_Parameter.target.propertyName == string.Empty
m_TargetPropertyMenu.text = parameter.target.propertyName == string.Empty
: TargetPropertyDisplayText(m_Parameter.target);
: TargetPropertyDisplayText(parameter.target);
var options = GatherPropertyOptions(m_Parameter.target.gameObject, m_Parameter.OutputType);
var options = GatherPropertyOptions(parameter.target.gameObject, parameter.OutputType);
foreach (var option in options)
{
m_TargetPropertyMenu.menu.AppendAction(

{
m_ExtraProperties.Clear();
if (m_Parameter is ICategoricalParameter)
if (parameter is CategoricalParameterBase)
var iterator = m_SerializedObject.GetIterator();
if (iterator.NextVisible(true))
var currentProperty = m_SerializedProperty.Copy();
var nextSiblingProperty = m_SerializedProperty.Copy();
nextSiblingProperty.Next(false);
if (currentProperty.Next(true))
if (iterator.propertyPath == "m_Script" || iterator.propertyPath == "parameterName")
if (SerializedProperty.EqualContents(currentProperty, nextSiblingProperty))
break;
if (currentProperty.name == "name")
if (iterator.type.Contains("managedReference") &&
iterator.managedReferenceFieldTypename == StaticData.samplerSerializedFieldType)
m_ExtraProperties.Add(new SamplerElement(iterator.Copy()));
if (currentProperty.type.Contains("managedReference") &&
currentProperty.managedReferenceFieldTypename == StaticData.samplerSerializedFieldType)
m_ExtraProperties.Add(new SamplerElement(currentProperty.Copy(), parameter));
var propertyField = new PropertyField(iterator.Copy());
propertyField.Bind(m_SerializedObject);
var propertyField = new PropertyField(currentProperty.Copy());
propertyField.Bind(currentProperty.serializedObject);
} while (iterator.NextVisible(false));
} while (currentProperty.NextVisible(false));
var categoricalParameter = (ICategoricalParameter)m_Parameter;
var optionsProperty = m_SerializedObject.FindProperty("options");
var probabilitiesProperty = m_SerializedObject.FindProperty("probabilities");
var probabilities = categoricalParameter.Probabilities;
var optionsProperty = m_SerializedProperty.FindPropertyRelative("m_Options");
var probabilitiesProperty = m_SerializedProperty.FindPropertyRelative("probabilities");
var probabilities = categoricalParameter.probabilities;
var listView = categoricalParameterTemplate.Q<ListView>("options");
listView.itemsSource = probabilities;

listView.style.height = new StyleLength(listView.itemHeight * 4);
VisualElement MakeItem() => new CategoricalOptionElement(optionsProperty, probabilitiesProperty, listView);
VisualElement MakeItem() => new CategoricalOptionElement(
optionsProperty, probabilitiesProperty);
listView.makeItem = MakeItem;
void BindItem(VisualElement e, int i)

var removeButton = optionElement.Q<Button>("remove");
removeButton.clicked += () =>
{
probabilitiesProperty.DeleteArrayElementAtIndex(i);
optionsProperty.DeleteArrayElementAtIndex(i);
m_SerializedProperty.serializedObject.ApplyModifiedProperties();
listView.itemsSource = categoricalParameter.probabilities;
listView.Refresh();
};
var addOptionButton = categoricalParameterTemplate.Q<Button>("add-option");
addOptionButton.clicked += () =>
{
probabilitiesProperty.arraySize++;
optionsProperty.arraySize++;
m_SerializedProperty.serializedObject.ApplyModifiedProperties();
listView.itemsSource = categoricalParameter.probabilities;
listView.Refresh();
listView.ScrollToItem(probabilitiesProperty.arraySize);
};
var scrollView = listView.Q<ScrollView>();
listView.RegisterCallback<WheelEvent>(evt =>
{

evt.StopImmediatePropagation();
});
var addOptionButton = categoricalParameterTemplate.Q<Button>("add-option");
addOptionButton.clicked += () =>
{
optionsProperty.arraySize++;
probabilitiesProperty.arraySize++;
m_SerializedObject.ApplyModifiedProperties();
listView.Refresh();
listView.ScrollToItem(probabilitiesProperty.arraySize);
};
uniformToggle.BindProperty(m_SerializedObject.FindProperty("uniform"));
var uniformProperty = m_SerializedProperty.FindPropertyRelative("uniform");
uniformToggle.BindProperty(uniformProperty);
void ToggleProbabilityFields(bool toggle)
{
if (toggle)

16
com.unity.perception/Editor/Randomization/SamplerElement.cs


ISampler m_Sampler;
SerializedProperty m_Property;
SerializedProperty m_RangeProperty;
SerializedObject m_ParameterSo;
public SamplerElement(SerializedProperty property)
public SamplerElement(SerializedProperty property, Parameter parameter)
m_ParameterSo = property.serializedObject;
m_Parameter = (Parameter)m_ParameterSo.targetObject;
m_Parameter = parameter;
m_Sampler = GetSamplerFromSerializedObject();
if (m_Sampler == null)

samplerName.text = UppercaseFirstLetter(m_Property.propertyPath);
samplerName.text = UppercaseFirstLetter(m_Property.name);
m_Properties = this.Q<VisualElement>("fields-container");
m_SamplerTypeDropdown = this.Q<ToolbarMenu>("sampler-type-dropdown");

m_Sampler = newSampler;
m_Property.managedReferenceValue = newSampler;
m_ParameterSo.ApplyModifiedProperties();
m_Property.serializedObject.ApplyModifiedProperties();
}
void CreatePropertyFields()

ISampler GetSamplerFromSerializedObject()
{
var propertyPath = m_Property.propertyPath;
var parameterType = m_Parameter.GetType();
return (ISampler)parameterType.GetField(propertyPath).GetValue(m_Parameter);
var configType = m_Parameter.GetType();
var field = configType.GetField(m_Property.name);
return (ISampler)field.GetValue(m_Parameter);
}
}
}

6
com.unity.perception/Editor/Randomization/Uxml/ParameterElement.uxml


<Box class="parameter-type-label-box">
<VisualElement name="collapse" class="collapse-parameter-toggle foldout-open"/>
<Label name="parameter-type-label" text="Type:" class="parameter-type-label"/>
<TextField binding-path="parameterName" name="parameter-name" text="Parameter Name"/>
<TextField name="name" text="Parameter Name"/>
</Box>
<Button name="remove-parameter" class="remove-parameter-button"/>
</VisualElement>

<editor:PropertyField label="Target GameObject" binding-path="target.gameObject" name="target-field"/>
<editor:PropertyField label="Target GameObject" name="target"/>
<editor:PropertyField binding-path="target.applicationFrequency"/>
<editor:PropertyField name="application-frequency"/>
</VisualElement>
</Box>
<Box name="extra-properties" style="padding-left: 4px; border-top-width: 0px;"/>

50
com.unity.perception/Runtime/Randomization/Configuration/ParameterConfiguration.cs


{
foreach (var parameter in parameters)
{
if (parameter.parameterName == parameterName)
if (parameter.name == parameterName)
return parameter;
}
throw new ParameterConfigurationException(

{
foreach (var parameter in parameters)
{
if (parameter.parameterName == parameterName && parameter is T typedParameter)
if (parameter.name == parameterName && parameter is T typedParameter)
return typedParameter;
}
throw new ParameterConfigurationException(

void NameAndAddParameterToList(Parameter parameter)
{
parameter.parameterName = $"Parameter{parameters.Count}";
parameter.name = $"Parameter{parameters.Count}";
parameters.Add(parameter);
}

public T AddParameter<T>() where T : Parameter
public T AddParameter<T>() where T : Parameter, new()
var parameter = gameObject.AddComponent<T>();
var parameter = new T();
NameAndAddParameterToList(parameter);
return parameter;
}

{
if (!parameterType.IsSubclassOf(typeof(Parameter)))
throw new ParameterConfigurationException($"Cannot add non-parameter types ({parameterType})");
var parameter = (Parameter)gameObject.AddComponent(parameterType);
var parameter = (Parameter)Activator.CreateInstance(parameterType);
NameAndAddParameterToList(parameter);
return parameter;
}

var parameterNames = new HashSet<string>();
foreach (var parameter in parameters)
{
if (parameterNames.Contains(parameter.parameterName))
if (parameterNames.Contains(parameter.name))
$"(\"{parameter.parameterName}\")");
parameterNames.Add(parameter.parameterName);
$"(\"{parameter.name}\")");
parameterNames.Add(parameter.name);
parameter.Validate();
}
}

void OnDisable()
{
configurations.Remove(this);
}
void OnDestroy()
{
#if UNITY_EDITOR
// Cleaning up child parameters requires detecting if the scene is changing.
// A scene change causes all objects to be destroyed and destroying objects twice throws an error.
// Check if in play mode and not changing from play mode to edit mode
if (EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying)
{
foreach(var parameter in parameters)
if (parameter != null) Destroy(parameter);
}
// Check if in the editor and not changing from edit mode to play mode
else if (!EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
{
// Delaying the destroy call avoids the issue of destroying child parameters
// twice when the user changes scenes in the editor
EditorApplication.delayCall += () =>
{
foreach (var parameter in parameters)
{
var param = parameter;
if (param != null) DestroyImmediate(param);
}
};
}
#else
foreach(var parameter in parameters)
if (parameter != null) Destroy(parameter);
#endif
}
}
}

74
com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameter.cs


/// <summary>
/// Generates samples by choosing one option from a weighted list of choices.
/// </summary>
public abstract class CategoricalParameter<T> : TypedParameter<T>, ICategoricalParameter
[Serializable]
public abstract class CategoricalParameter<T> : CategoricalParameterBase
[Min(0)] public uint seed;
public List<T> options = new List<T>();
public List<float> probabilities = new List<float>();
public uint seed;
[SerializeField]
List<T> m_Options = new List<T>();
public List<float> Probabilities => probabilities;
public sealed override Type OutputType => typeof(T);
public T GetOption(int index) => m_Options[index];
public float GetProbability(int index) => probabilities[index];
internal override void AddOption()
{
m_Options.Add(default);
probabilities.Add(0f);
}
public void AddOption(T option, float probability)
{
m_Options.Add(option);
probabilities.Add(probability);
}
public override void RemoveOption(int index)
{
m_Options.RemoveAt(index);
probabilities.RemoveAt(index);
}
public override void ClearOptions()
{
m_Options.Clear();
probabilities.Clear();
}
public IReadOnlyList<(T, float)> options
{
get
{
var catOptions = new List<(T, float)>(m_Options.Count);
for (var i = 0; i < catOptions.Count; i++)
catOptions.Add((m_Options[i], probabilities[i]));
return catOptions;
}
}
public override void Validate()
{

if (probabilities.Count != options.Count)
if (probabilities.Count != m_Options.Count)
throw new ParameterValidationException(
"Number of options must be equal to the number of probabilities");
NormalizeProbabilities();

{
var randomValue = rng.NextFloat();
return uniform
? options[(int)(randomValue * options.Count)]
: options[BinarySearch(randomValue)];
? m_Options[(int)(randomValue * m_Options.Count)]
: m_Options[BinarySearch(randomValue)];
public override T Sample(int index)
/// <summary>
/// Generates one parameter sample
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
public T Sample(int index)
{
NormalizeProbabilities();
var iteratedSeed = SamplerUtility.IterateSeed((uint)index, seed);

public override T[] Samples(int index, int sampleCount)
/// <summary>
/// Generates an array of parameter samples
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
/// <param name="sampleCount">Number of parameter samples to generate</param>
public T[] Samples(int index, int sampleCount)
{
NormalizeProbabilities();
var samples = new T[sampleCount];

samples[i] = Sample(ref rng);
return samples;
}
public sealed override void ApplyToTarget(int seedOffset)
{
if (!hasTarget)
return;
target.ApplyValueToTarget(Sample(seedOffset));
}
}
}

9
com.unity.perception/Runtime/Randomization/Parameters/Parameter.cs


/// randomizing simulations.
/// </summary>
[Serializable]
public abstract class Parameter : MonoBehaviour
public abstract class Parameter
public string parameterName = "Parameter";
internal bool collapsed;
public string name = "Parameter";
[HideInInspector] public ParameterTarget target = new ParameterTarget();
public bool hasTarget => target.gameObject != null;

if (hasTarget)
{
if (target.component == null)
throw new ParameterException($"Null component target on parameter \"{parameterName}\"");
throw new ParameterException($"Null component target on parameter \"{name}\"");
throw new ParameterException($"Invalid property target on parameter \"{parameterName}\"");
throw new ParameterException($"Invalid property target on parameter \"{name}\"");
}
}
}

7
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/BooleanParameter.cs


using Unity.Burst;
using System;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine.Perception.Randomization.Parameters.Attributes;

{
[AddComponentMenu("")]
[Serializable]
public class BooleanParameter : StructParameter<bool>
public class BooleanParameter : NumericParameter<bool>
{
[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);

4
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorHsvaParameter.cs


namespace UnityEngine.Perception.Randomization.Parameters
{
[AddComponentMenu("")]
[Serializable]
public class ColorHsvaParameter : StructParameter<Color>
public class ColorHsvaParameter : NumericParameter<Color>
{
[SerializeReference] public ISampler hue = new UniformSampler(0f, 1f);
[SerializeReference] public ISampler saturation = new UniformSampler(0f, 1f);

4
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/FloatParameter.cs


namespace UnityEngine.Perception.Randomization.Parameters
{
[AddComponentMenu("")]
[Serializable]
public class FloatParameter : StructParameter<float>
public class FloatParameter : NumericParameter<float>
{
[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);

7
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/IntegerParameter.cs


using Unity.Burst;
using System;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine.Perception.Randomization.Parameters.Attributes;

{
[AddComponentMenu("")]
[Serializable]
public class IntegerParameter : StructParameter<int>
public class IntegerParameter : NumericParameter<int>
{
[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);
public override ISampler[] Samplers => new[] { value };

2
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/MaterialParameter.cs


namespace UnityEngine.Perception.Randomization.Parameters
{
[AddComponentMenu("")]
[Serializable]
[ParameterMetaData("Material")]
public class MaterialParameter : CategoricalParameter<Material> {}
}

5
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/StringParameter.cs


using UnityEngine.Perception.Randomization.Parameters.Attributes;
using System;
using UnityEngine.Perception.Randomization.Parameters.Attributes;
[AddComponentMenu("")]
[Serializable]
[ParameterMetaData("String")]
public class StringParameter : CategoricalParameter<string> {}
}

4
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector2Parameter.cs


namespace UnityEngine.Perception.Randomization.Parameters
{
[AddComponentMenu("")]
[Serializable]
public class Vector2Parameter : StructParameter<Vector2>
public class Vector2Parameter : NumericParameter<Vector2>
{
[SerializeReference] public ISampler x = new UniformSampler(0f, 1f);
[SerializeReference] public ISampler y = new UniformSampler(0f, 1f);

4
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector3Parameter.cs


namespace UnityEngine.Perception.Randomization.Parameters
{
[AddComponentMenu("")]
[Serializable]
public class Vector3Parameter : StructParameter<Vector3>
public class Vector3Parameter : NumericParameter<Vector3>
{
[SerializeReference] public ISampler x = new UniformSampler(0f, 1f);
[SerializeReference] public ISampler y = new UniformSampler(0f, 1f);

4
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector4Parameter.cs


namespace UnityEngine.Perception.Randomization.Parameters
{
[AddComponentMenu("")]
[Serializable]
public class Vector4Parameter : StructParameter<Vector4>
public class Vector4Parameter : NumericParameter<Vector4>
{
[SerializeReference] public ISampler x = new UniformSampler(0f, 1f);
[SerializeReference] public ISampler y = new UniformSampler(0f, 1f);

21
com.unity.perception/Tests/Runtime/Randomization/CategoricalParameterTests.cs


[Test]
public void NegativeProbabilitiesTest()
{
var parameter = m_TestObject.AddComponent<StringParameter>();
parameter.options = new List<string> { "option1", "option2" };
parameter.probabilities = new List<float> { 1f, -1f };
Assert.Throws<ParameterValidationException>(() => parameter.Validate());
}
[Test]
public void DifferentOptionAndProbabilityCounts()
{
var parameter = m_TestObject.AddComponent<StringParameter>();
parameter.options = new List<string> { "option1" };
parameter.probabilities = new List<float> { 1f, 1f };
var parameter = new StringParameter();
parameter.AddOption("option1", 1f);
parameter.AddOption("option2", -1f);
Assert.Throws<ParameterValidationException>(() => parameter.Validate());
}

var parameter = m_TestObject.AddComponent<StringParameter>();
parameter.options = new List<string> { "option1", "option2" };
parameter.probabilities = new List<float> { 0f, 0f };
var parameter = new StringParameter();
parameter.AddOption("option1", 0f);
parameter.AddOption("option2", 0f);
Assert.Throws<ParameterValidationException>(() => parameter.Validate());
}
}

4
com.unity.perception/Tests/Runtime/Randomization/ParameterConfigurationTests.cs


var config = m_TestObject.AddComponent<ParameterConfiguration>();
var param1 = config.AddParameter<FloatParameter>();
var param2 = config.AddParameter<BooleanParameter>();
param1.parameterName = "SameName";
param2.parameterName = "SameName";
param1.name = "SameName";
param2.name = "SameName";
Assert.Throws<ParameterConfigurationException>(() => config.ValidateParameters());
}

18
com.unity.perception/Tests/Runtime/Randomization/ParameterTests.cs


m_TestObject = new GameObject();
m_Parameters = new Parameter[]
{
m_TestObject.AddComponent<BooleanParameter>(),
m_TestObject.AddComponent<IntegerParameter>(),
m_TestObject.AddComponent<FloatParameter>(),
m_TestObject.AddComponent<Vector2Parameter>(),
m_TestObject.AddComponent<Vector3Parameter>(),
m_TestObject.AddComponent<Vector4Parameter>(),
m_TestObject.AddComponent<ColorHsvaParameter>(),
m_TestObject.AddComponent<StringParameter>(),
m_TestObject.AddComponent<MaterialParameter>()
new BooleanParameter(),
new IntegerParameter(),
new FloatParameter(),
new Vector2Parameter(),
new Vector3Parameter(),
new Vector4Parameter(),
new ColorHsvaParameter(),
new StringParameter(),
new MaterialParameter()
};
}

2
com.unity.perception/Tests/Runtime/Randomization/SamplerTests.cs


using System;
using System.Collections;
using UnityEngine.TestTools;
namespace RandomizationTests
{

20
com.unity.perception/Tests/Runtime/Randomization/StructParameterTests.cs


m_TestObject = new GameObject();
m_Tests = new BaseStructParameterTest[]
{
new StructParameterTest<bool>(m_TestObject.AddComponent<BooleanParameter>()),
new StructParameterTest<int>(m_TestObject.AddComponent<IntegerParameter>()),
new StructParameterTest<float>(m_TestObject.AddComponent<FloatParameter>()),
new StructParameterTest<Vector2>(m_TestObject.AddComponent<Vector2Parameter>()),
new StructParameterTest<Vector3>(m_TestObject.AddComponent<Vector3Parameter>()),
new StructParameterTest<Vector4>(m_TestObject.AddComponent<Vector4Parameter>()),
new StructParameterTest<Color>(m_TestObject.AddComponent<ColorHsvaParameter>()),
new NumericParameterTest<bool>(new BooleanParameter()),
new NumericParameterTest<int>(new IntegerParameter()),
new NumericParameterTest<float>(new FloatParameter()),
new NumericParameterTest<Vector2>(new Vector2Parameter()),
new NumericParameterTest<Vector3>(new Vector3Parameter()),
new NumericParameterTest<Vector4>(new Vector4Parameter()),
new NumericParameterTest<Color>(new ColorHsvaParameter()),
};
}

public abstract void GeneratesNativeSamples();
}
public class StructParameterTest<T> : BaseStructParameterTest where T : struct
public class NumericParameterTest<T> : BaseStructParameterTest where T : struct
StructParameter<T> m_Parameter;
NumericParameter<T> m_Parameter;
public StructParameterTest(StructParameter<T> parameter)
public NumericParameterTest(NumericParameter<T> parameter)
{
m_Parameter = parameter;
}

15
com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameterBase.cs


using System;
using System.Collections.Generic;
namespace UnityEngine.Perception.Randomization.Parameters
{
[Serializable]
public abstract class CategoricalParameterBase : Parameter
{
[SerializeField] internal List<float> probabilities = new List<float>();
internal abstract void AddOption();
public abstract void RemoveOption(int index);
public abstract void ClearOptions();
}
}

3
com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameterBase.cs.meta


fileFormatVersion: 2
guid: dffac5e109d340beb8934d1070923c21
timeCreated: 1597346882

49
com.unity.perception/Runtime/Randomization/Parameters/NumericParameter.cs


using System;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine.Perception.Randomization.Samplers;
namespace UnityEngine.Perception.Randomization.Parameters
{
[Serializable]
public abstract class NumericParameter<T> : Parameter where T : struct
{
public sealed override Type OutputType => typeof(T);
/// <summary>
/// Generates one parameter sample
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
public abstract T Sample(int index);
/// <summary>
/// Generates an array of parameter samples
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
/// <param name="sampleCount">Number of parameter samples to generate</param>
public abstract T[] Samples(int index, int sampleCount);
/// <summary>
/// Schedules a job to generate an array of parameter samples.
/// Call Complete() on the JobHandle returned by this function to wait on the job generating the parameter samples.
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
/// <param name="sampleCount">Number of parameter samples to generate</param>
/// <param name="jobHandle">The JobHandle returned from scheduling the sampling job</param>
public abstract NativeArray<T> Samples(int index, int sampleCount, out JobHandle jobHandle);
public sealed override void ApplyToTarget(int seedOffset)
{
if (!hasTarget)
return;
target.ApplyValueToTarget(Sample(seedOffset));
}
public override void Validate()
{
base.Validate();
foreach (var sampler in Samplers)
SamplerUtility.ValidateRange(sampler.range);
}
}
}

12
com.unity.perception/Runtime/Randomization/Parameters/ICategoricalParameter.cs


using System.Collections.Generic;
namespace UnityEngine.Perception.Randomization.Parameters
{
/// <summary>
/// Exposes the probabilities property of categorical parameters for UI purposes
/// </summary>
public interface ICategoricalParameter
{
List<float> Probabilities { get; }
}
}

3
com.unity.perception/Runtime/Randomization/Parameters/ICategoricalParameter.cs.meta


fileFormatVersion: 2
guid: 747fbbdb7a6e4eae87ea193025685e5e
timeCreated: 1595536474

18
com.unity.perception/Runtime/Randomization/Parameters/StructParameter.cs


using System;
using Unity.Collections;
using Unity.Jobs;
namespace UnityEngine.Perception.Randomization.Parameters
{
public abstract class StructParameter<T> : TypedParameter<T> where T : struct
{
/// <summary>
/// Schedules a job to generate an array of parameter samples.
/// Call Complete() on the JobHandle returned by this function to wait on the job generating the parameter samples.
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
/// <param name="sampleCount">Number of parameter samples to generate</param>
/// <param name="jobHandle">The JobHandle returned from scheduling the sampling job</param>
public abstract NativeArray<T> Samples(int index, int sampleCount, out JobHandle jobHandle);
}
}

3
com.unity.perception/Runtime/Randomization/Parameters/StructParameter.cs.meta


fileFormatVersion: 2
guid: 0db409852a654ba4856c729c57bba332
timeCreated: 1595629954

37
com.unity.perception/Runtime/Randomization/Parameters/TypedParameter.cs


using System;
using UnityEngine.Perception.Randomization.Samplers;
namespace UnityEngine.Perception.Randomization.Parameters
{
public abstract class TypedParameter<T> : Parameter
{
public sealed override Type OutputType => typeof(T);
/// <summary>
/// Generates one parameter sample
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
public abstract T Sample(int index);
/// <summary>
/// Generates an array of parameter samples
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
/// <param name="sampleCount">Number of parameter samples to generate</param>
public abstract T[] Samples(int index, int sampleCount);
public sealed override void ApplyToTarget(int seedOffset)
{
if (!hasTarget)
return;
target.ApplyValueToTarget(Sample(seedOffset));
}
public override void Validate()
{
base.Validate();
foreach (var sampler in Samplers)
SamplerUtility.ValidateRange(sampler.range);
}
}
}

/com.unity.perception/Runtime/Randomization/Parameters/TypedParameter.cs.meta → /com.unity.perception/Runtime/Randomization/Parameters/NumericParameter.cs.meta

正在加载...
取消
保存