浏览代码

Added Randomizers and RandomizerTags

/main
Steven Leal 4 年前
当前提交
b3ce9635
共有 131 个文件被更改,包括 2250 次插入549 次删除
  1. 53
      com.unity.perception/Editor/Randomization/StaticData.cs
  2. 2
      com.unity.perception/Editor/Randomization/Uxml/CategoricalOptionElement.uxml
  3. 33
      com.unity.perception/Editor/Randomization/Uxml/ParameterElement.uxml
  4. 1
      com.unity.perception/Editor/Randomization/Uxml/SamplerElement.uxml
  5. 15
      com.unity.perception/Editor/Randomization/Uxml/ScenarioBaseElement.uxml
  6. 5
      com.unity.perception/Runtime/GroundTruth/Labelers/Visualization/Materials/OutlineMaterial.mat
  7. 76
      com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameter.cs
  8. 4
      com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameterBase.cs
  9. 15
      com.unity.perception/Runtime/Randomization/Parameters/NumericParameter.cs
  10. 67
      com.unity.perception/Runtime/Randomization/Parameters/Parameter.cs
  11. 22
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/BooleanParameter.cs
  12. 8
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/FloatParameter.cs
  13. 8
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/IntegerParameter.cs
  14. 12
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector2Parameter.cs
  15. 13
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector3Parameter.cs
  16. 14
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector4Parameter.cs
  17. 2
      com.unity.perception/Runtime/Randomization/Samplers/FloatRange.cs
  18. 16
      com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/ConstantSampler.cs
  19. 21
      com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/NormalSampler.cs
  20. 21
      com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/UniformSampler.cs
  21. 2
      com.unity.perception/Runtime/Randomization/Samplers/SamplerUtility.cs
  22. 4
      com.unity.perception/Runtime/Randomization/Scenarios/FixedLengthScenario.cs
  23. 255
      com.unity.perception/Runtime/Randomization/Scenarios/ScenarioBase.cs
  24. 12
      com.unity.perception/Runtime/Randomization/Scenarios/ScenarioBase.cs.meta
  25. 10
      com.unity.perception/Tests/Runtime/Randomization/ParameterTests/CategoricalParameterTests.cs
  26. 60
      com.unity.perception/Tests/Runtime/Randomization/ScenarioTests.cs
  27. 2
      com.unity.perception/Editor/Randomization/VisualElements/DragToReorderManipulator.cs.meta
  28. 2
      com.unity.perception/Editor/Randomization/VisualElements/ParameterDragBar.cs
  29. 21
      com.unity.perception/Editor/Randomization/VisualElements/DragToReorderManipulator.cs
  30. 2
      com.unity.perception/Editor/Randomization/VisualElements/SamplerElement.cs
  31. 3
      com.unity.perception.meta
  32. 8
      com.unity.perception/Editor/Randomization/Editors.meta
  33. 8
      com.unity.perception/Editor/Randomization/PropertyDrawers.meta
  34. 109
      com.unity.perception/Editor/Randomization/Uss/ParameterStyles.uss
  35. 8
      com.unity.perception/Editor/Randomization/Uss/ParameterStyles.uss.meta
  36. 16
      com.unity.perception/Editor/Randomization/Uss/SamplerStyles.uss
  37. 8
      com.unity.perception/Editor/Randomization/Uss/SamplerStyles.uss.meta
  38. 21
      com.unity.perception/Editor/Randomization/Uss/ScenarioStyles.uss
  39. 3
      com.unity.perception/Editor/Randomization/Uss/ScenarioStyles.uss.meta
  40. 10
      com.unity.perception/Editor/Randomization/Uxml/ParameterDrawer.uxml
  41. 8
      com.unity.perception/Editor/Randomization/Uxml/ParameterDrawer.uxml.meta
  42. 19
      com.unity.perception/Editor/Randomization/Uxml/RandomizerElement.uxml
  43. 3
      com.unity.perception/Editor/Randomization/Uxml/RandomizerElement.uxml.meta
  44. 8
      com.unity.perception/Editor/Randomization/Uxml/RandomizerList.uxml
  45. 3
      com.unity.perception/Editor/Randomization/Uxml/RandomizerList.uxml.meta
  46. 8
      com.unity.perception/Editor/Randomization/VisualElements.meta
  47. 8
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters.meta
  48. 8
      com.unity.perception/Runtime/Randomization/Randomizers.meta
  49. 8
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests.meta
  50. 88
      com.unity.perception/Editor/Randomization/Editors/ScenarioBaseEditor.cs
  51. 8
      com.unity.perception/Editor/Randomization/Editors/ScenarioBaseEditor.cs.meta
  52. 25
      com.unity.perception/Editor/Randomization/PropertyDrawers/ColorHsvaDrawer.cs
  53. 8
      com.unity.perception/Editor/Randomization/PropertyDrawers/ColorHsvaDrawer.cs.meta
  54. 26
      com.unity.perception/Editor/Randomization/PropertyDrawers/ParameterDrawer.cs
  55. 8
      com.unity.perception/Editor/Randomization/PropertyDrawers/ParameterDrawer.cs.meta
  56. 8
      com.unity.perception/Editor/Randomization/VisualElements/CategoricalOptionElement.cs.meta
  57. 39
      com.unity.perception/Editor/Randomization/VisualElements/ColorHsvaField.cs
  58. 8
      com.unity.perception/Editor/Randomization/VisualElements/ColorHsvaField.cs.meta
  59. 48
      com.unity.perception/Editor/Randomization/VisualElements/DrawerParameterElement.cs
  60. 8
      com.unity.perception/Editor/Randomization/VisualElements/DrawerParameterElement.cs.meta
  61. 8
      com.unity.perception/Editor/Randomization/VisualElements/FloatRangeElement.cs.meta
  62. 22
      com.unity.perception/Editor/Randomization/VisualElements/ParameterDragBar.cs.meta
  63. 196
      com.unity.perception/Editor/Randomization/VisualElements/ParameterElement.cs
  64. 8
      com.unity.perception/Editor/Randomization/VisualElements/ParameterElement.cs.meta
  65. 8
      com.unity.perception/Editor/Randomization/VisualElements/RandomSeedField.cs.meta
  66. 93
      com.unity.perception/Editor/Randomization/VisualElements/RandomizerElement.cs
  67. 3
      com.unity.perception/Editor/Randomization/VisualElements/RandomizerElement.cs.meta
  68. 92
      com.unity.perception/Editor/Randomization/VisualElements/RandomizerList.cs
  69. 3
      com.unity.perception/Editor/Randomization/VisualElements/RandomizerList.cs.meta
  70. 8
      com.unity.perception/Editor/Randomization/VisualElements/SamplerElement.cs.meta
  71. 107
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsva.cs
  72. 3
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsva.cs.meta
  73. 10
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsvaCategoricalParameter.cs
  74. 3
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsvaCategoricalParameter.cs.meta
  75. 181
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsvaParameter.cs
  76. 10
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorRgbCategoricalParameter.cs
  77. 3
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorRgbCategoricalParameter.cs.meta
  78. 111
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorRgbParameter.cs
  79. 3
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorRgbParameter.cs.meta
  80. 140
      com.unity.perception/Runtime/Randomization/Randomizers/Randomizer.cs
  81. 3
      com.unity.perception/Runtime/Randomization/Randomizers/Randomizer.cs.meta
  82. 25
      com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTag.cs
  83. 3
      com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTag.cs.meta
  84. 44
      com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTagManager.cs
  85. 3
      com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTagManager.cs.meta
  86. 6
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/ExampleTag.cs
  87. 3
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/ExampleTag.cs.meta
  88. 30
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/ExampleTransformRandomizer.cs
  89. 3
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/ExampleTransformRandomizer.cs.meta
  90. 40
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTagTests.cs
  91. 3
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTagTests.cs.meta
  92. 89
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTests.cs
  93. 3
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTests.cs.meta
  94. 213
      com.unity.perception/Editor/Randomization/Uss/Styles.uss

53
com.unity.perception/Editor/Randomization/StaticData.cs


using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using UnityEngine.Experimental.Perception.Randomization.Randomizers;
using UnityEngine.Experimental.Perception.Randomization.Samplers;
namespace UnityEngine.Experimental.Perception.Randomization.Editor

internal static readonly string samplerSerializedFieldType;
internal static Type[] parameterTypes;
internal static Type[] randomizerTypes;
randomizerTypes = GetConstructableDerivedTypes<Randomizer>();
samplerTypes = GetConstructableDerivedTypes<ISampler>();
var samplerType = typeof(ISampler);
samplerSerializedFieldType = $"{samplerType.Assembly.GetName().Name} {samplerType.FullName}";

types.Add(type);
}
return types.ToArray();
}
internal static object GetManagedReferenceValue(SerializedProperty prop, bool parent=false)
{
var path = prop.propertyPath.Replace(".Array.data[", "[");
object obj = prop.serializedObject.targetObject;
var elements = path.Split('.');
if (parent)
elements = elements.Take(elements.Count() - 1).ToArray();
foreach (var element in elements)
{
if (element.Contains("["))
{
var elementName = element.Substring(0, element.IndexOf("["));
var index = Convert.ToInt32(element.Substring(element.IndexOf("[")).Replace("[","").Replace("]",""));
obj = GetArrayValue(obj, elementName, index);
}
else
obj = GetValue(obj, element);
}
return obj;
}
static object GetValue(object source, string name)
{
if (source == null)
return null;
var type = source.GetType();
var f = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (f == null)
{
var p = type.GetProperty(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
return p == null ? null : p.GetValue(source, null);
}
return f.GetValue(source);
}
static object GetArrayValue(object source, string name, int index)
{
var value = GetValue(source, name);
if (!(value is IEnumerable enumerable))
return null;
var enumerator = enumerable.GetEnumerator();
while (index-- >= 0)
enumerator.MoveNext();
return enumerator.Current;
}
}
}

2
com.unity.perception/Editor/Randomization/Uxml/CategoricalOptionElement.uxml


<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements">
<VisualElement class="categorical-option ">
<VisualElement class="categorical-option">
<Button name="remove" class="remove-option-button"/>
<Label name="index-label" text="[0]" style="min-width: 50px;"/>
<editor:PropertyField name="option" class="option-property-field"/>

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


<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements">
<Box name="parameter-container" class="parameter-container">
<VisualElement name="drag-handle" class="move-buttons-container">
<VisualElement class="drag-handle"/>
</VisualElement>
<VisualElement style="flex-grow: 1; justify-content: center; margin-right: 6px;">
<VisualElement class="parameter-type-label-container">
<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 name="name" text="Parameter Name"/>
</Box>
<Button name="remove-parameter" class="remove-parameter-button"/>
</VisualElement>
<VisualElement name="properties" class="parameter-properties-container" style="margin-bottom: 2px;">
<Box>
<editor:ObjectField label="Target GameObject" name="target"/>
<VisualElement name="target-container">
<VisualElement class="unity-base-field">
<Label text="Target Property" class="unity-base-field__label"/>
<editor:ToolbarMenu text="Select A Property" name="property-select-menu" class="property-select-menu"/>
</VisualElement>
<editor:EnumField label="Application Frequency" name="application-frequency"/>
</VisualElement>
</Box>
<Box name="extra-properties" style="padding-left: 4px; border-top-width: 0px;"/>
</VisualElement>
</VisualElement>
</Box>
<VisualElement>
<Style src="../Uss/ParameterStyles.uss"/>
<VisualElement name="properties"/>
</VisualElement>
</UXML>

1
com.unity.perception/Editor/Randomization/Uxml/SamplerElement.uxml


<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements">
<VisualElement name="sampler-template" style="margin-bottom: 4px;">
<Style src="../Uss/SamplerStyles.uss"/>
<VisualElement style="flex-direction: row; align-items: center;">
<Label name="sampler-name" text="Sampler Name" class="unity-base-field__label sampler-name"/>
<editor:ToolbarMenu name="sampler-type-dropdown" text="Placeholder Sampler Type" class="sampler-type-menu"/>

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


<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements">
<VisualElement>
<Style src="../Uss/Styles.uss"/>
<Label style="white-space: normal; margin-bottom: 5px; margin-top: 2px" text="Scenarios control the execution flow of your simulation by applying randomization parameters. Make sure to always have only one scenario active within your scene."/>
<VisualElement name="inspector-properties" style="margin-bottom: 20px;"/>
<Style src="../Uss/ScenarioStyles.uss"/>
<TextElement class="info-box" text="Scenarios control the execution flow of your simulation by applying randomization parameters. Make sure to always have only one scenario active within your scene."/>
<VisualElement name="inspector-properties" style="margin-bottom: 4px;"/>
<VisualElement name="configuration-container" class="dark-viewport">
<Toggle label="Quit On Complete" tooltip="Quit the application when the scenario completes" binding-path="quitOnComplete" style="margin-left: 3px"/>
<VisualElement name="configuration-container" class="dark-viewport" style="padding-left: 16px">
<Toggle label="Quit On Complete" tooltip="Quit the application when the scenario completes" binding-path="quitOnComplete"/>
<editor:PropertyField tooltip="Read constants from JSON when the application starts" name="deserialize-on-start" label="Deserialize On Start" binding-path="deserializeOnStart" style="padding-left: 4px;"/>
<editor:PropertyField tooltip="Read constants from JSON when the application starts" name="deserialize-on-start" label="Deserialize On Start" binding-path="deserializeOnStart"/>
<VisualElement style="flex-direction: row;">
<Button name="serialize-constants" text="Serialize Constants" style="flex-grow: 1;"/>
<Button name="deserialize-constants" text="Deserialize Constants" style="flex-grow: 1;"/>

<VisualElement name="randomizer-list-placeholder"/>
</VisualElement>
</UXML>

5
com.unity.perception/Runtime/GroundTruth/Labelers/Visualization/Materials/OutlineMaterial.mat


m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
m_Name:
m_EditorClassIdentifier:
version: 1
version: 2
--- !u!21 &2100000
Material:
serializedVersion: 6

m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: 3050
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
disabledShaderPasses:

- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}
m_BuildTextureStacks: []

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


[Serializable]
public abstract class CategoricalParameter<T> : CategoricalParameterBase
{
[SerializeField] internal bool uniform;
[SerializeField] internal bool uniform = true;
[SerializeReference] ISampler m_Sampler = new UniformSampler(0f, 1f);
[SerializeField] List<T> m_Categories = new List<T>();

/// Returns a list containing the samplers attached to this parameter
/// Returns an IEnumerable that iterates over each sampler field in this parameter
public override ISampler[] samplers => new [] { m_Sampler };
public override IEnumerable<ISampler> samplers
{
get { yield return m_Sampler; }
}
/// <summary>
/// The sample type generated by this parameter

public float GetProbability(int index) => probabilities[index];
/// <summary>
/// Constructs a new categorical parameter
/// </summary>
protected CategoricalParameter() { }
/// <summary>
/// Create a new categorical parameter from a list of categories with uniform probabilities
/// Updates this parameter's list of categorical options
/// <param name="categoricalOptions">List of categories</param>
/// <exception cref="ArgumentException"></exception>
protected CategoricalParameter(IEnumerable<T> categoricalOptions)
/// <param name="categoricalOptions">The categorical options to configure</param>
public void SetOptions(IEnumerable<T> categoricalOptions)
if (categories.Count == 0)
throw new ArgumentException("List of options is empty");
uniform = true;
foreach (var option in categoricalOptions)
AddOption(option, 1f);
m_Categories.Clear();
probabilities.Clear();
foreach (var category in categoricalOptions)
AddOption(category, 1f);
NormalizeProbabilities();
/// Creates a new categorical parameter from a list of categories and their associated probabilities
/// Updates this parameter's list of categorical options
/// <param name="categoricalOptions">List of categories and their associated probabilities</param>
/// <exception cref="ArgumentException"></exception>
protected CategoricalParameter(IEnumerable<(T, float)> categoricalOptions)
/// <param name="categoricalOptions">The categorical options to configure</param>
public void SetOptions(IEnumerable<(T, float)> categoricalOptions)
if (categories.Count == 0)
throw new ArgumentException("List of options is empty");
m_Categories.Clear();
probabilities.Clear();
internal override void AddOption()
{
m_Categories.Add(default);
probabilities.Add(0f);
}
internal void AddOption(T option, float probability)
void AddOption(T option, float probability)
internal override void RemoveOption(int index)
{
m_Categories.RemoveAt(index);
probabilities.RemoveAt(index);
}
internal override void ClearOptions()
{
m_Categories.Clear();
probabilities.Clear();
}
/// <summary>
/// Returns a list of the potential categories this parameter can generate
/// </summary>

/// Validates the categorical probabilities assigned to this parameter
/// </summary>
/// <exception cref="ParameterValidationException"></exception>
internal override void Validate()
public override void Validate()
{
base.Validate();
if (!uniform)

}
}
internal void NormalizeProbabilities()
void NormalizeProbabilities()
{
var totalProbability = 0f;
for (var i = 0; i < probabilities.Count; i++)

: m_Categories[BinarySearch(randomValue)];
}
internal sealed override void ApplyToTarget(int seedOffset)
/// <summary>
/// Generates a generic sample
/// </summary>
/// <returns>The generated sample</returns>
public override object GenericSample()
if (!hasTarget)
return;
target.ApplyValueToTarget(Sample());
return Sample();
}
}
}

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


public abstract class CategoricalParameterBase : Parameter
{
[SerializeField] internal List<float> probabilities = new List<float>();
internal abstract void AddOption();
internal abstract void RemoveOption(int index);
internal abstract void ClearOptions();
}
}

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


/// <returns>A NativeArray containing generated samples</returns>
public abstract NativeArray<T> Samples(int sampleCount, out JobHandle jobHandle);
internal sealed override void ApplyToTarget(int seedOffset)
/// <summary>
/// Generates a generic sample
/// </summary>
/// <returns>The generated sample</returns>
public override object GenericSample()
if (!hasTarget)
return;
target.ApplyValueToTarget(Sample());
return Sample();
internal override void Validate()
/// <summary>
/// Validate the settings of this parameter
/// </summary>
public override void Validate()
{
base.Validate();
foreach (var sampler in samplers)

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


using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Perception.Randomization.Samplers;

[HideInInspector, SerializeField] internal bool collapsed;
/// <summary>
/// The name of the parameter
/// </summary>
[HideInInspector] public string name = "Parameter";
/// <summary>
/// The target this parameter apply a sample to
/// </summary>
[HideInInspector, SerializeField] public ParameterTarget target = new ParameterTarget();
/// <summary>
/// Indicates whether this parameter has a target GameObject
/// </summary>
public bool hasTarget => target.gameObject != null;
// /// <summary>
// /// The name of the parameter
// /// </summary>
// [HideInInspector] public string name = "Parameter";
//
// /// <summary>
// /// The target this parameter apply a sample to
// /// </summary>
// [HideInInspector, SerializeField] public ParameterTarget target = new ParameterTarget();
//
// /// <summary>
// /// Indicates whether this parameter has a target GameObject
// /// </summary>
// public bool hasTarget => target.gameObject != null;
/// <summary>
/// The sample type generated by this parameter

/// <summary>
/// An array containing a reference to each sampler field in this parameter
/// Returns an IEnumerable that iterates over each sampler field in this parameter
public abstract ISampler[] samplers { get; }
public abstract IEnumerable<ISampler> samplers { get; }
/// <summary>
/// Constructs a new parameter

}
/// <summary>
/// Resets sampler states and then offsets those states using the current scenario iteration
/// Resets the state of each sampler employed by this parameter
/// <param name="scenarioIteration">The current scenario iteration</param>
public void ResetState(int scenarioIteration)
public void ResetState()
{
sampler.IterateState(scenarioIteration);
}
}
/// <summary>
/// Offsets the state of each sampler employed by this parameter
/// </summary>
/// <param name="offsetIndex">Often the current scenario iteration</param>
public void IterateState(int offsetIndex)
{
foreach (var sampler in samplers)
sampler.IterateState(offsetIndex);
/// Applies one sampled value to this parameters assigned target gameobject
/// Generates a generic sample
internal abstract void ApplyToTarget(int seedOffset);
/// <returns>The generated sample</returns>
public abstract object GenericSample();
internal virtual void Validate()
{
if (hasTarget)
{
if (target.component == null)
throw new ParameterValidationException($"Null component target on parameter \"{name}\"");
if (string.IsNullOrEmpty(target.propertyName))
throw new ParameterValidationException($"Invalid property target on parameter \"{name}\"");
}
}
public virtual void Validate() { }
}
}

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


using System;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;

[HideInInspector, SerializeReference] public ISampler value = new UniformSampler(0f, 1f);
/// <summary>
/// Returns the sampler employed by this parameter
/// A threshold value that transforms random values within the range [0, 1] to boolean values.
/// Values greater than the threshold are true, and values less than the threshold are false.
public override ISampler[] samplers => new[] { value };
[Range(0, 1)] public float threshold = 0.5f;
static bool Sample(float t) => t >= 0.5f;
/// <summary>
/// Returns an IEnumerable that iterates over each sampler field in this parameter
/// </summary>
public override IEnumerable<ISampler> samplers
{
get { yield return value; }
}
bool Sample(float t) => t >= threshold;
/// <summary>
/// Generates a boolean sample

jobHandle = new SamplesJob
{
rngSamples = rngSamples,
samples = samples
samples = samples,
threshold = threshold
}.Schedule(jobHandle);
return samples;
}

{
[DeallocateOnJobCompletion] public NativeArray<float> rngSamples;
public NativeArray<bool> samples;
public float threshold;
samples[i] = Sample(rngSamples[i]);
samples[i] = rngSamples[i] >= threshold;
}
}
}

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


using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine.Experimental.Perception.Randomization.Samplers;

[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);
/// <summary>
/// Returns the sampler employed by this parameter
/// Returns an IEnumerable that iterates over each sampler field in this parameter
public override ISampler[] samplers => new []{ value };
public override IEnumerable<ISampler> samplers
{
get { yield return value; }
}
/// <summary>
/// Generates a float sample

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


using System;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;

[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);
/// <summary>
/// Returns the sampler employed by this parameter
/// Returns an IEnumerable that iterates over each sampler field in this parameter
public override ISampler[] samplers => new[] { value };
public override IEnumerable<ISampler> samplers
{
get { yield return value; }
}
/// <summary>
/// Generates an integer sample

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


using System;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;

[SerializeReference] public ISampler y = new UniformSampler(0f, 1f);
/// <summary>
/// Returns the samplers employed by this parameter
/// Returns an IEnumerable that iterates over each sampler field in this parameter
public override ISampler[] samplers => new []{ x, y };
public override IEnumerable<ISampler> samplers
{
get
{
yield return x;
yield return y;
}
}
/// <summary>
/// Generates a Vector2 sample

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


using System;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;

[SerializeReference] public ISampler z = new UniformSampler(0f, 1f);
/// <summary>
/// Returns the samplers employed by this parameter
/// Returns an IEnumerable that iterates over each sampler field in this parameter
public override ISampler[] samplers => new []{ x, y, z };
public override IEnumerable<ISampler> samplers
{
get
{
yield return x;
yield return y;
yield return z;
}
}
/// <summary>
/// Generates a Vector3 sample

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


using System;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;

[SerializeReference] public ISampler w = new UniformSampler(0f, 1f);
/// <summary>
/// The sampler used the samplers employed by this parameter
/// Returns an IEnumerable that iterates over each sampler field in this parameter
public override ISampler[] samplers => new []{ x, y, z, w };
public override IEnumerable<ISampler> samplers
{
get
{
yield return x;
yield return y;
yield return z;
yield return w;
}
}
/// <summary>
/// Generates a Vector4 sample

2
com.unity.perception/Runtime/Randomization/Samplers/FloatRange.cs


using System;
using Unity.Assertions;
using Assert = UnityEngine.Assertions.Assert;
namespace UnityEngine.Experimental.Perception.Randomization.Samplers
{

16
com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/ConstantSampler.cs


public void ResetState() { }
/// <summary>
/// Resets a sampler's state to its base random seed and then offsets said seed using an index value.
/// Note that ConstantSamplers do not have random states.
/// </summary>
/// <param name="index">Often a the active scenario's currentIteration</param>
public void ResetState(int index) { }
/// <summary>
/// Set the base seed value of this sampler.
/// Note that ConstantSamplers do not have base seeds.
/// </summary>
/// <param name="seed">The seed that will replace the sampler's current seed</param>
public void Rebase(uint seed) { }
/// <summary>
/// Deterministically offsets a sampler's state when generating values within a batched job.
/// Deterministically offsets a sampler's state.
/// Note that ConstantSamplers do not have a state to iterate.
/// </summary>
/// <param name="offsetIndex">

21
com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/NormalSampler.cs


}
/// <summary>
/// Resets a sampler's state to its base random seed and then offsets said seed using an index value
/// </summary>
/// <param name="index">Often a the active scenario's currentIteration</param>
public void ResetState(int index)
{
ResetState();
IterateState(index);
}
/// <summary>
/// Set the base seed value of this sampler
/// </summary>
/// <param name="seed">The seed that will replace the sampler's current seed</param>
public void Rebase(uint seed)
{
baseSeed = seed;
}
/// <summary>
/// Deterministically offsets a sampler's state when generating values within a batched job
/// Deterministically offsets a sampler's state
/// </summary>
/// <param name="offsetIndex">
/// The index used to offset the sampler's state.

21
com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/UniformSampler.cs


}
/// <summary>
/// Resets a sampler's state to its base random seed and then offsets said seed using an index value
/// </summary>
/// <param name="index">Often a the active scenario's currentIteration</param>
public void ResetState(int index)
{
ResetState();
IterateState(index);
}
/// <summary>
/// Set the base seed value of this sampler
/// </summary>
/// <param name="seed">The seed that will replace the sampler's current seed</param>
public void Rebase(uint seed)
{
baseSeed = seed;
}
/// <summary>
/// Deterministically offsets a sampler's state when generating values within a batched job
/// Deterministically offsets a sampler's state
/// </summary>
/// <param name="offsetIndex">
/// The index used to offset the sampler's state.

2
com.unity.perception/Runtime/Randomization/Samplers/SamplerUtility.cs


}
/// <summary>
/// Non-deterministically generates a random seed
/// Non-deterministically generates a non-zero random seed
/// </summary>
/// <returns>A non-deterministically generated random seed</returns>
public static uint GenerateRandomSeed()

4
com.unity.perception/Runtime/Randomization/Scenarios/FixedLengthScenario.cs


public override bool isScenarioComplete => currentIteration >= constants.totalIterations;
/// <summary>
/// Called before the scenario begins iterating
/// Fast forwards the current scenario iteration to the starting iteration indicated in this scenario's constants
public override void OnInitialize()
protected override void OnAwake()
{
currentIteration = constants.startingIteration;
}

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


using System;
using System.Collections.Generic;
using Unity.Simulation;
using UnityEngine.Experimental.Perception.Randomization.Randomizers;
using UnityEngine.Experimental.Perception.Randomization.Configuration;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
/// The base class of all scenario classes
/// Derive ScenarioBase to implement a custom scenario
[DefaultExecutionOrder(-1)]
bool m_WaitingForFinalUploads;
RandomizerTagManager m_TagManager = new RandomizerTagManager();
IEnumerable<Randomizer> activeRandomizers
{
get
{
foreach (var randomizer in m_Randomizers)
if (randomizer.enabled)
yield return randomizer;
}
}
// ReSharper disable once InconsistentNaming
[SerializeReference] internal List<Randomizer> m_Randomizers = new List<Randomizer>();
/// <summary>
/// The RandomizerTagManager attached to this scenario
/// </summary>
public RandomizerTagManager tagManager => m_TagManager;
/// <summary>
/// Return the list of randomizers attached to this scenario
/// </summary>
public IReadOnlyList<Randomizer> randomizers => m_Randomizers.AsReadOnly();
/// <summary>
/// If true, this scenario will quit the Unity application when it's finished executing

/// <summary>
/// Returns the active parameter scenario in the scene
/// </summary>
public static ScenarioBase ActiveScenario
public static ScenarioBase activeScenario
if (s_ActiveScenario != null)
throw new ScenarioException("There cannot be more than one active ParameterConfiguration");
if (value != null && s_ActiveScenario != null && value != s_ActiveScenario)
throw new ScenarioException("There cannot be more than one active Scenario");
s_ActiveScenario = value;
}
}

public abstract bool isScenarioComplete { get; }
/// <summary>
/// Called before the scenario begins iterating
/// </summary>
public virtual void OnInitialize() { }
/// <summary>
/// Called at the beginning of every scenario iteration
/// </summary>
public virtual void OnIterationSetup() { }
/// <summary>
/// Called at the start of every frame
/// </summary>
public virtual void OnFrameStart() { }
/// <summary>
/// Called the frame after an iteration ends
/// </summary>
public virtual void OnIterationTeardown() { }
/// <summary>
/// Called when the scenario has finished iterating
/// </summary>
public virtual void OnComplete() { }
/// <summary>
/// Serializes the scenario's constants to a JSON file located at serializedConstantsFilePath
/// </summary>
public abstract void Serialize();

/// </summary>
public abstract void Deserialize();
/// <summary>
/// This method executed directly after this scenario has been registered and initialized
/// </summary>
protected virtual void OnAwake() { }
void Awake()
{
activeScenario = this;
OnAwake();
foreach (var randomizer in m_Randomizers)
{
randomizer.m_Scenario = this;
randomizer.m_TagManager = tagManager;
}
foreach (var randomizer in m_Randomizers)
randomizer.Create();
}
ActiveScenario = this;
activeScenario = this;
}
void OnDisable()

{
if (deserializeOnStart)
Deserialize();
foreach (var config in ParameterConfiguration.configurations)
config.ValidateParameters();
OnInitialize();
}
void Update()

return;
}
// Wait for any final uploads before exiting quitting
if (m_WaitingForFinalUploads)
{
if (!Manager.FinalUploadsDone)
return;
if (quitOnComplete)
#if UNITY_EDITOR
UnityEditor.EditorApplication.ExitPlaymode();
#else
Application.Quit();
#endif
return;
}
// Iterate Scenario
if (m_FirstScenarioFrame)
{

{
currentIteration++;
currentIterationFrame = 0;
OnIterationTeardown();
foreach (var randomizer in activeRandomizers)
randomizer.IterationEnd();
}
}

OnComplete();
foreach (var randomizer in activeRandomizers)
randomizer.ScenarioComplete();
Manager.Instance.Shutdown();
if (quitOnComplete)
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
m_WaitingForFinalUploads = true;
return;
}
// Perform new iteration tasks

foreach (var config in ParameterConfiguration.configurations)
config.ResetParameterStates(currentIteration);
foreach (var config in ParameterConfiguration.configurations)
config.ApplyParameters(currentIteration, ParameterApplicationFrequency.OnIterationSetup);
OnIterationSetup();
IterateParameterStates();
foreach (var randomizer in activeRandomizers)
randomizer.IterationStart();
foreach (var config in ParameterConfiguration.configurations)
config.ApplyParameters(framesSinceInitialization, ParameterApplicationFrequency.EveryFrame);
OnFrameStart();
foreach (var randomizer in activeRandomizers)
randomizer.Update();
}
/// <summary>
/// Finds and returns a randomizer attached to this scenario of the specified Randomizer type
/// </summary>
/// <typeparam name="T">The type of randomizer to find</typeparam>
/// <returns>A randomizer of the specified type</returns>
/// <exception cref="ScenarioException"></exception>
public T GetRandomizer<T>() where T : Randomizer
{
foreach (var randomizer in m_Randomizers)
if (randomizer is T typedRandomizer)
return typedRandomizer;
throw new ScenarioException($"A Randomizer of type {typeof(T).Name} was not added to this scenario");
}
/// <summary>
/// Creates a new randomizer and adds it to this scenario
/// </summary>
/// <typeparam name="T">The type of randomizer to create</typeparam>
/// <returns>The newly created randomizer</returns>
public T CreateRandomizer<T>() where T : Randomizer, new()
{
return (T)CreateRandomizer(typeof(T));
}
internal Randomizer CreateRandomizer(Type randomizerType)
{
if (!randomizerType.IsSubclassOf(typeof(Randomizer)))
throw new ScenarioException(
$"Cannot add non-randomizer type {randomizerType.Name} to randomizer list");
foreach (var randomizer in m_Randomizers)
if (randomizer.GetType() == randomizerType)
throw new ScenarioException(
$"Two Randomizers of the same type ({randomizerType.Name}) cannot both be active simultaneously");
var newRandomizer = (Randomizer)Activator.CreateInstance(randomizerType);
m_Randomizers.Add(newRandomizer);
newRandomizer.m_Scenario = this;
newRandomizer.m_TagManager = tagManager;
newRandomizer.Create();
return newRandomizer;
}
/// <summary>
/// Removes a randomizer of the specified type from this scenario
/// </summary>
/// <typeparam name="T">The type of scenario to remove</typeparam>
public void RemoveRandomizer<T>() where T : Randomizer, new()
{
RemoveRandomizer(typeof(T));
}
internal void RemoveRandomizer(Type randomizerType)
{
if (!randomizerType.IsSubclassOf(typeof(Randomizer)))
throw new ScenarioException(
$"Cannot add non-randomizer type {randomizerType.Name} to randomizer list");
var removed = false;
for (var i = 0; i < m_Randomizers.Count; i++)
{
if (m_Randomizers[i].GetType() == randomizerType)
{
m_Randomizers.RemoveAt(i);
removed = true;
break;
}
}
if (!removed)
throw new ScenarioException(
$"No active Randomizer of type {randomizerType.Name} could be removed");
}
/// <summary>
/// Returns the execution order index of a randomizer of the given type
/// </summary>
/// <typeparam name="T">The type of randomizer to index</typeparam>
/// <returns>The randomizer index</returns>
/// <exception cref="ScenarioException"></exception>
public int GetRandomizerIndex<T>() where T : Randomizer, new()
{
for (var i = 0; i < m_Randomizers.Count; i++)
{
var randomizer = m_Randomizers[i];
if (randomizer is T)
return i;
}
throw new ScenarioException($"A Randomizer of type {typeof(T).Name} was not added to this scenario");
}
/// <summary>
/// Moves a randomizer from one index to another
/// </summary>
/// <param name="currentIndex">The index of the randomizer to move</param>
/// <param name="nextIndex">The index to move the randomizer to</param>
public void ReorderRandomizer(int currentIndex, int nextIndex)
{
if (currentIndex == nextIndex)
return;
if (nextIndex > currentIndex)
nextIndex--;
var randomizer = m_Randomizers[currentIndex];
m_Randomizers.RemoveAt(currentIndex);
m_Randomizers.Insert(nextIndex, randomizer);
}
void ValidateParameters()
{
foreach (var randomizer in m_Randomizers)
foreach (var parameter in randomizer.parameters)
parameter.Validate();
}
void IterateParameterStates()
{
foreach (var randomizer in m_Randomizers)
{
foreach (var parameter in randomizer.parameters)
{
parameter.ResetState();
parameter.IterateState(currentIteration);
}
}
}
}
}

12
com.unity.perception/Runtime/Randomization/Scenarios/ScenarioBase.cs.meta


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

10
com.unity.perception/Tests/Runtime/Randomization/ParameterTests/CategoricalParameterTests.cs


public void NegativeProbabilities()
{
var parameter = new StringParameter();
parameter.AddOption("option1", 1f);
parameter.AddOption("option2", -1f);
Assert.Throws<ParameterValidationException>(() => parameter.Validate());
var optionsArray = new [] { ("option1", 1f), ("option1", -1f) };
Assert.Throws<ParameterValidationException>(() => parameter.SetOptions(optionsArray));
}
[Test]

parameter.AddOption("option1", 0f);
parameter.AddOption("option2", 0f);
Assert.Throws<ParameterValidationException>(() => parameter.Validate());
var optionsArray = new [] { ("option1", 0f), ("option1", 0f) };
Assert.Throws<ParameterValidationException>(() => parameter.SetOptions(optionsArray));
}
}
}

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


using NUnit.Framework;
using UnityEngine;
using UnityEngine.Perception.GroundTruth;
using UnityEngine.Experimental.Perception.Randomization.Configuration;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
using UnityEngine.Experimental.Perception.Randomization.Samplers;
using UnityEngine.Experimental.Perception.Randomization.Scenarios;
using UnityEngine.TestTools;
using Object = UnityEngine.Object;

yield return null;
}
Assert.True(m_Scenario.isScenarioComplete);
}
[UnityTest]
public IEnumerator AppliesParametersEveryFrame()
{
var config = m_TestObject.AddComponent<ParameterConfiguration>();
var parameter = config.AddParameter<Vector3Parameter>();
parameter.x = new UniformSampler(1, 2);
parameter.y = new UniformSampler(1, 2);
parameter.z = new UniformSampler(1, 2);
parameter.target.AssignNewTarget(
m_TestObject, m_TestObject.transform, "position", ParameterApplicationFrequency.EveryFrame);
var initialPosition = Vector3.zero;
yield return CreateNewScenario(1, 5);
// ReSharper disable once Unity.InefficientPropertyAccess
Assert.AreNotEqual(initialPosition, m_TestObject.transform.position);
// ReSharper disable once Unity.InefficientPropertyAccess
initialPosition = m_TestObject.transform.position;
yield return null;
// ReSharper disable once Unity.InefficientPropertyAccess
Assert.AreNotEqual(initialPosition, m_TestObject.transform.position);
}
[UnityTest]
public IEnumerator AppliesParametersEveryIteration()
{
var config = m_TestObject.AddComponent<ParameterConfiguration>();
var parameter = config.AddParameter<Vector3Parameter>();
parameter.x = new UniformSampler(1, 2);
parameter.y = new UniformSampler(1, 2);
parameter.z = new UniformSampler(1, 2);
var transform = m_TestObject.transform;
var prevPosition = new Vector3();
transform.position = prevPosition;
parameter.target.AssignNewTarget(
m_TestObject, transform, "position", ParameterApplicationFrequency.OnIterationSetup);
yield return CreateNewScenario(2, 2);
Assert.AreNotEqual(prevPosition, transform.position);
// ReSharper disable once Unity.InefficientPropertyAccess
prevPosition = transform.position;
yield return null;
// ReSharper disable once Unity.InefficientPropertyAccess
Assert.AreEqual(prevPosition, transform.position);
// ReSharper disable once Unity.InefficientPropertyAccess
prevPosition = transform.position;
yield return null;
// ReSharper disable once Unity.InefficientPropertyAccess
Assert.AreNotEqual(prevPosition, transform.position);
}
[UnityTest]

2
com.unity.perception/Editor/Randomization/VisualElements/DragToReorderManipulator.cs.meta


fileFormatVersion: 2
guid: dd62abede5784c84f90495b367408ced
guid: f2b59fa8baf440f597257d8eb8219afa
MonoImporter:
externalObjects: {}
serializedVersion: 2

2
com.unity.perception/Editor/Randomization/VisualElements/ParameterDragBar.cs


{
public ParameterDragBar()
{
AddToClassList("parameter-drag-bar");
AddToClassList("drag-bar");
}
}
}

21
com.unity.perception/Editor/Randomization/VisualElements/DragToReorderManipulator.cs


using UnityEngine.UIElements;
using UnityEngine.Experimental.Perception.Randomization.VisualElements;
using UnityEngine.UIElements;
class ParameterDragManipulator : MouseManipulator
class DragToReorderManipulator : MouseManipulator
ParameterElement m_ParameterElement;
RandomizerElement m_RandomizerElement;
VisualElement m_DragHandle;
VisualElement m_DragBar;
VisualElement m_ParameterContainer;

m_DragHandle = target.Q<VisualElement>("drag-handle");
m_ParameterElement = (ParameterElement)target;
m_RandomizerElement = (RandomizerElement)target;
m_DragHandle = m_RandomizerElement.Q<VisualElement>("drag-handle");
m_DragHandle.RegisterCallback<MouseDownEvent>(OnMouseDown);
m_DragHandle.RegisterCallback<MouseMoveEvent>(OnMouseMove);
m_DragHandle.RegisterCallback<MouseUpEvent>(OnMouseUp);

return;
}
if (m_ParameterElement.ConfigEditor.FilterString != string.Empty)
return;
m_ParameterContainer = target.parent;
m_DragBar = new ParameterDragBar();
m_DragBar.style.width = new StyleLength(m_ParameterContainer.resolvedStyle.width);

middlePoints[p++] = middleHeight + localY;
}
var randomizerIndex = m_RandomizerElement.parent.IndexOf(m_RandomizerElement);
ReorderParameter(m_ParameterElement.ParameterIndex, i);
ReorderParameter(randomizerIndex, i);
ReorderParameter(m_ParameterElement.ParameterIndex, middlePoints.Length);
ReorderParameter(randomizerIndex, middlePoints.Length);
m_ParameterElement.ConfigEditor.ReorderParameter(currentIndex, nextIndex);
m_RandomizerElement.randomizerList.ReorderRandomizer(currentIndex, nextIndex);
}
}
}

2
com.unity.perception/Editor/Randomization/VisualElements/SamplerElement.cs


m_Properties.Clear();
var currentProperty = m_Property.Copy();
var nextSiblingProperty = m_Property.Copy();
nextSiblingProperty.Next(false);
nextSiblingProperty.NextVisible(false);
if (currentProperty.NextVisible(true))
{

3
com.unity.perception.meta


fileFormatVersion: 2
guid: 2c0b9128211c487091d21926e24c3303
timeCreated: 1600211324

8
com.unity.perception/Editor/Randomization/Editors.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 85401640505a48f9a8fe55045f5f28d8
timeCreated: 1600754567
=======
guid: 0b17046409af4c22bf74eec2a5965984
timeCreated: 1598135707
>>>>>>> 86d25d2... implemented parameter behaviours

8
com.unity.perception/Editor/Randomization/PropertyDrawers.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 47a26876f92a4b19adb3b7b525efa830
timeCreated: 1600754588
=======
guid: d3107e026b2943c1868c9b3f8c6480d3
timeCreated: 1598135730
>>>>>>> 86d25d2... implemented parameter behaviours

109
com.unity.perception/Editor/Randomization/Uss/ParameterStyles.uss


.randomizer-element {
border-width: 2px;
border-radius: 5px;
margin: 2px 1px;
background-color: #383838;
}
.parameter-type-label-container {
flex-direction: row;
justify-content: space-between;
align-items: center;
margin-bottom: 1px;
}
.parameter-type-label-box {
flex-direction: row;
align-items: center;
justify-content: flex-start;
flex-grow: 0;
-unity-text-align: middle-center;
border-width: 0;
padding: 1px;
font-size: 13px;
}
.parameter-type-label {
color: cornflowerblue;
-unity-text-align: middle-left;
margin-right: 4px;
}
.parameter-type-label-box .unity-base-text-field__input {
padding-left: 6px;
padding-right: 6px;
}
.collapse-toggle {
flex-shrink: 0;
margin-right: 3px;
margin-left: 3px;
width: 12px;
height: 12px;
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/FoldoutOpen.png");
}
.collapsed .collapse-toggle {
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/FoldoutClosed.png");
}
.collapsed .properties-container {
display: none;
}
.categorical-option {
flex-direction: row;
background-color: #3F3F3F;
margin: 1px;
border-radius: 4px;
}
.options-list-view {
background-color: #191919;
border-radius: 4px;
margin-right: 2px;
padding: 3px;
border-bottom-right-radius: 0;
}
.option-property-field {
width: 0;
flex-grow: 1;
flex-shrink: 0;
}
.uniform-probability .hide-when-uniform {
display: none;
}
.add-option-button {
align-self: flex-end;
border-width: 0;
border-top-right-radius: 0;
border-top-left-radius: 0;
background-color: #191919;
margin-top: 0;
margin-right: 2px;
}
.add-option-button:hover {
background-color: #2A2A2A;
}
.add-option-button:active {
color: cornflowerblue;
}
.remove-option-button {
width: 12px;
height: 14px;
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/X.png");
}
.drag-handle {
flex-shrink: 0;
width: 16px;
height: 100%;
min-height: 20px;
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/DragHandle.png");
}

8
com.unity.perception/Editor/Randomization/Uss/ParameterStyles.uss.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 0a4e5cce05674cabb4e35dbba3176bb0
timeCreated: 1600754588
=======
guid: def81fa16f8b41aca393a30c3b1fac72
timeCreated: 1598222679
>>>>>>> 86d25d2... implemented parameter behaviours

16
com.unity.perception/Editor/Randomization/Uss/SamplerStyles.uss


.sampler-type-menu {
flex-grow: 1.5;
border-radius: 3px;
border-width: 1px;
margin-top: 2px;
margin-right: 3px;
}
.sampler-name {
/*color: lightgreen;*/
}
.float-range .unity-base-field__label {
min-width: auto;
margin-right: 4px;
}

8
com.unity.perception/Editor/Randomization/Uss/SamplerStyles.uss.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: f96184638ee64ea18b5e2d5c90f94c67
timeCreated: 1600754588
=======
guid: 85ff041b142f41798a7703bda9bb1ba7
timeCreated: 1598222791
>>>>>>> 86d25d2... implemented parameter behaviours

21
com.unity.perception/Editor/Randomization/Uss/ScenarioStyles.uss


.dark-viewport {
border-radius: 5px;
background-color: #191919;
padding: 2px;
}
.info-box {
border-width: 1px;
border-color: #191919;
padding: 2px 4px 2px 4px;
white-space: normal;
margin-top: 4px;
margin-bottom: 4px;
}
.drag-bar {
width: 100px;
height: 6px;
background-color: rgba(100,149,237,0.4);
position: absolute;
}

3
com.unity.perception/Editor/Randomization/Uss/ScenarioStyles.uss.meta


fileFormatVersion: 2
guid: 7db846b4c7cf420e8fdc32c7f701f5c3
timeCreated: 1600276536

10
com.unity.perception/Editor/Randomization/Uxml/ParameterDrawer.uxml


<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements">
<VisualElement>
<Style src="../Uss/ParameterStyles.uss"/>
<VisualElement style="flex-direction: row; align-items: center;">
<VisualElement name="collapse" class="collapse-toggle foldout-open"/>
<Label name="field-name" style="font-size: 12px;"/>
</VisualElement>
<VisualElement name="drawer" class="properties-container" style="padding-left: 18px;"/>
</VisualElement>
</UXML>

8
com.unity.perception/Editor/Randomization/Uxml/ParameterDrawer.uxml.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: fbfd6bfda79247c1a4578907f9df9d6c
timeCreated: 1600754588
=======
guid: 6a4bb3efae29429292ccdfa63e661872
timeCreated: 1598240583
>>>>>>> 86d25d2... implemented parameter behaviours

19
com.unity.perception/Editor/Randomization/Uxml/RandomizerElement.uxml


<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements">
<VisualElement class="randomizer-element" style="flex-direction: row;">
<Style src="../Uss/ParameterStyles.uss"/>
<VisualElement name="drag-handle" class="drag-handle"/>
<VisualElement style="flex-grow: 1;">
<VisualElement style="flex-direction: row; justify-content: space-between;">
<VisualElement style="flex-direction: row; align-items: center;">
<VisualElement name="collapse" class="collapse-toggle foldout-open"/>
<Toggle name="enabled"/>
<TextElement name="class-name" text="Randomizer Class Name"/>
</VisualElement>
<Button name="remove" class="remove-option-button"/>
</VisualElement>
<VisualElement name="properties" class="properties-container" style="padding-left: 16px;"/>
</VisualElement>
</VisualElement>
</UXML>

3
com.unity.perception/Editor/Randomization/Uxml/RandomizerElement.uxml.meta


fileFormatVersion: 2
guid: f68d0e4ae9a94881adad2ff4835cddaf
timeCreated: 1600290113

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


<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements">
<VisualElement name="randomizers-container" class="dark-viewport" style="margin-top: 6px; min-height: 100px;"/>
<VisualElement style="flex-direction: row; align-items: center; justify-content: center; margin-top: 4px;">
<editor:ToolbarMenu name="add-randomizer" text="Add Randomizer"/>
<Button name="expand-all" text="Expand All"/>
<Button name="collapse-all" text="Collapse All"/>
</VisualElement>
</UXML>

3
com.unity.perception/Editor/Randomization/Uxml/RandomizerList.uxml.meta


fileFormatVersion: 2
guid: 61284b57145a4b87b960f780ead021cb
timeCreated: 1600368801

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


fileFormatVersion: 2
<<<<<<< HEAD
guid: 64930d74a0b54875ab472b72066417bc
timeCreated: 1600754567
=======
guid: 7f8f95a1bb144a96b9310164f5560387
timeCreated: 1598135666
>>>>>>> 86d25d2... implemented parameter behaviours

8
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 2b14f5553d2847319c3077ecf7206d06
timeCreated: 1600754588
=======
guid: ce91e289cdaa4ccc849a0c287aefd34d
timeCreated: 1598326361
>>>>>>> 50f2c39... Added xml documentation

8
com.unity.perception/Runtime/Randomization/Randomizers.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 80645bae9cd440ca81c7a1e03572e7da
timeCreated: 1600754588
=======
guid: ae6aad06c0e14f67aa7a9ad9004a1828
timeCreated: 1600274594
>>>>>>> c653d18... Implemented randomizer class. Ran into SerializeReference issue 1193322.

8
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 6693ffffff2148b0a248e1d8c5ddc805
timeCreated: 1600754588
=======
guid: f9e02c502b7845229d26d377a0d871f1
timeCreated: 1600744200
>>>>>>> cb407fb... added randomizer tests

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


using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.Experimental.Perception.Randomization.Scenarios;
using UnityEngine.Experimental.Perception.Randomization.VisualElements;
using UnityEngine.UIElements;
namespace UnityEngine.Experimental.Perception.Randomization.Editor
{
[CustomEditor(typeof(ScenarioBase), true)]
class ScenarioBaseEditor : UnityEditor.Editor
{
ScenarioBase m_Scenario;
SerializedObject m_SerializedObject;
VisualElement m_Root;
VisualElement m_InspectorPropertiesContainer;
VisualElement m_ConstantsContainer;
VisualElement m_RandomizerListPlaceholder;
SerializedProperty m_ConstantsProperty;
public override VisualElement CreateInspectorGUI()
{
m_Scenario = (ScenarioBase)target;
m_SerializedObject = new SerializedObject(m_Scenario);
m_Root = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{StaticData.uxmlDir}/ScenarioBaseElement.uxml").CloneTree();
var serializeConstantsButton = m_Root.Q<Button>("serialize-constants");
serializeConstantsButton.clicked += () => m_Scenario.Serialize();
var deserializeConstantsButton = m_Root.Q<Button>("deserialize-constants");
deserializeConstantsButton.clicked += () => m_Scenario.Deserialize();
m_RandomizerListPlaceholder = m_Root.Q<VisualElement>("randomizer-list-placeholder");
CreatePropertyFields();
CheckIfConstantsExist();
return m_Root;
}
void CreatePropertyFields()
{
m_InspectorPropertiesContainer = m_Root.Q<VisualElement>("inspector-properties");
m_InspectorPropertiesContainer.Clear();
var iterator = m_SerializedObject.GetIterator();
var foundProperties = false;
if (iterator.NextVisible(true))
{
do
{
switch (iterator.name)
{
case "m_Script":
break;
case "constants":
m_ConstantsProperty = iterator.Copy();
break;
case "m_Randomizers":
m_RandomizerListPlaceholder.Add(new RandomizerList(iterator.Copy()));
break;
default:
{
foundProperties = true;
var propertyField = new PropertyField(iterator.Copy());
propertyField.Bind(m_SerializedObject);
m_InspectorPropertiesContainer.Add(propertyField);
break;
}
}
} while (iterator.NextVisible(false));
}
if (!foundProperties)
m_InspectorPropertiesContainer.style.display = new StyleEnum<DisplayStyle>(DisplayStyle.None);
}
void CheckIfConstantsExist()
{
m_ConstantsContainer = m_Root.Q<VisualElement>("constants-container");
if (m_ConstantsProperty == null)
{
m_InspectorPropertiesContainer.style.marginBottom = 0;
m_ConstantsContainer.style.display = new StyleEnum<DisplayStyle>(DisplayStyle.None);
}
}
}
}

8
com.unity.perception/Editor/Randomization/Editors/ScenarioBaseEditor.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 57a29c3831024d55aca1a6267dabb56c
timeCreated: 1600754583
=======
guid: face5e97e23d402cbf6fafadb39fa0c3
timeCreated: 1596213301
>>>>>>> 86d25d2... implemented parameter behaviours

25
com.unity.perception/Editor/Randomization/PropertyDrawers/ColorHsvaDrawer.cs


using UnityEditor;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
using UnityEngine.UIElements;
namespace UnityEngine.Perception.Randomization.Editor.PropertyDrawers
{
[CustomPropertyDrawer(typeof(ColorHsva), true)]
class ColorHsvaDrawer : PropertyDrawer
{
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
return new ColorHsvaField(property);
}
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);
}
}
}

8
com.unity.perception/Editor/Randomization/PropertyDrawers/ColorHsvaDrawer.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: e2ea91ddb1134cc6a14d2e3859a275f5
timeCreated: 1600754588
=======
guid: 5e8094c28dd142a09fbbd38ca560164b
timeCreated: 1598250942
>>>>>>> 86d25d2... implemented parameter behaviours

26
com.unity.perception/Editor/Randomization/PropertyDrawers/ParameterDrawer.cs


using System;
using UnityEditor;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
using UnityEngine.UIElements;
namespace UnityEngine.Perception.Randomization.Editor.PropertyDrawers
{
[CustomPropertyDrawer(typeof(Parameter), true)]
class ParameterDrawer : PropertyDrawer
{
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
return new DrawerParameterElement(property);
}
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);
}
}
}

8
com.unity.perception/Editor/Randomization/PropertyDrawers/ParameterDrawer.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: e396dea59a4843529416020c3d0ef5af
timeCreated: 1600754588
=======
guid: d389620d3aa3471ca1877eb59cdfb465
timeCreated: 1598135745
>>>>>>> 86d25d2... implemented parameter behaviours

8
com.unity.perception/Editor/Randomization/VisualElements/CategoricalOptionElement.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 5b6d309152934df99cfff89a96b9703e
timeCreated: 1600754567
=======
guid: 3066f77d411047baafb6cc454adc6e37
timeCreated: 1595535184
>>>>>>> 86d25d2... implemented parameter behaviours

39
com.unity.perception/Editor/Randomization/VisualElements/ColorHsvaField.cs


using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
using UnityEngine.UIElements;
namespace UnityEngine.Perception.Randomization.Editor
{
class ColorHsvaField : ColorField
{
SerializedProperty m_Property;
SerializedProperty m_H;
SerializedProperty m_S;
SerializedProperty m_V;
SerializedProperty m_A;
public ColorHsvaField(SerializedProperty property)
{
m_Property = property;
label = m_Property.displayName;
m_H = m_Property.FindPropertyRelative("h");
m_S = m_Property.FindPropertyRelative("s");
m_V = m_Property.FindPropertyRelative("v");
m_A = m_Property.FindPropertyRelative("a");
rawValue = (Color)new ColorHsva(m_H.floatValue, m_S.floatValue, m_V.floatValue, m_A.floatValue);
this.RegisterValueChangedCallback(evt =>
{
var color = (ColorHsva)evt.newValue;
m_H.floatValue = color.h;
m_S.floatValue = color.s;
m_V.floatValue = color.v;
m_A.floatValue = color.a;
m_Property.serializedObject.ApplyModifiedProperties();
});
}
}
}

8
com.unity.perception/Editor/Randomization/VisualElements/ColorHsvaField.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: c70590a385e44f6fbe82f5c74cb92f71
timeCreated: 1600754567
=======
guid: 103b163a2467415ab86b0df8175b12a6
timeCreated: 1598254290
>>>>>>> 86d25d2... implemented parameter behaviours

48
com.unity.perception/Editor/Randomization/VisualElements/DrawerParameterElement.cs


using UnityEditor;
using UnityEngine.Experimental.Perception.Randomization.Editor;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
using UnityEngine.UIElements;
namespace UnityEngine.Perception.Randomization.Editor
{
class DrawerParameterElement : VisualElement
{
Parameter m_Parameter;
SerializedProperty m_Collapsed;
SerializedProperty m_Property;
const string k_CollapsedParameterClass = "collapsed";
bool collapsed
{
get => m_Collapsed.boolValue;
set
{
m_Collapsed.boolValue = value;
m_Property.serializedObject.ApplyModifiedPropertiesWithoutUndo();
if (value)
AddToClassList(k_CollapsedParameterClass);
else
RemoveFromClassList(k_CollapsedParameterClass);
}
}
public DrawerParameterElement(SerializedProperty property)
{
m_Property = property;
m_Collapsed = property.FindPropertyRelative("collapsed");
AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{StaticData.uxmlDir}/ParameterDrawer.uxml").CloneTree(this);
var collapseToggle = this.Q<VisualElement>("collapse");
collapseToggle.RegisterCallback<MouseUpEvent>(evt => collapsed = !collapsed);
collapsed = m_Collapsed.boolValue;
var fieldNameField = this.Q<Label>("field-name");
fieldNameField.text = property.displayName;
var drawer = this.Q<VisualElement>("drawer");
drawer.Add(new ParameterElement(property));
}
}
}

8
com.unity.perception/Editor/Randomization/VisualElements/DrawerParameterElement.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: a9f0d234cfc24a8da54ec04d5ec9a129
timeCreated: 1600754567
=======
guid: e2eb905ca8c14b5cbe43e48418948be0
timeCreated: 1598255728
>>>>>>> 86d25d2... implemented parameter behaviours

8
com.unity.perception/Editor/Randomization/VisualElements/FloatRangeElement.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 708f941b18c345d8a0b7d1ea31d27843
timeCreated: 1600754567
=======
guid: e37f169c618d471d8ed9614a41096437
timeCreated: 1595281335
>>>>>>> 86d25d2... implemented parameter behaviours

22
com.unity.perception/Editor/Randomization/VisualElements/ParameterDragBar.cs.meta


<<<<<<< HEAD
fileFormatVersion: 2
<<<<<<< HEAD
guid: 61021c66c33e40e98de0702ae0aa4449
timeCreated: 1600754567
=======
guid: 7c1e08b02e5a4c55875f34baf32f8e76
timeCreated: 1596143672
>>>>>>> 86d25d2... implemented parameter behaviours
=======
fileFormatVersion: 2
guid: 7c1e08b02e5a4c55875f34baf32f8e76
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
>>>>>>> 750f255... working on new workflow

196
com.unity.perception/Editor/Randomization/VisualElements/ParameterElement.cs


using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.Experimental.Perception.Randomization.Editor;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
using UnityEngine.UIElements;
namespace UnityEngine.Perception.Randomization.Editor
{
class ParameterElement : VisualElement
{
VisualElement m_PropertiesContainer;
SerializedProperty m_SerializedProperty;
Parameter parameter => (Parameter)StaticData.GetManagedReferenceValue(m_SerializedProperty);
CategoricalParameterBase categoricalParameter => (CategoricalParameterBase)parameter;
public ParameterElement(SerializedProperty property)
{
var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{StaticData.uxmlDir}/ParameterElement.uxml");
template.CloneTree(this);
m_SerializedProperty = property;
m_PropertiesContainer = this.Q<VisualElement>("properties");
CreatePropertyFields();
}
void CreatePropertyFields()
{
m_PropertiesContainer.Clear();
if (parameter is CategoricalParameterBase)
{
CreateCategoricalParameterFields();
return;
}
var currentProperty = m_SerializedProperty.Copy();
var nextSiblingProperty = m_SerializedProperty.Copy();
nextSiblingProperty.NextVisible(false);
if (currentProperty.NextVisible(true))
{
do
{
if (SerializedProperty.EqualContents(currentProperty, nextSiblingProperty))
break;
if (currentProperty.type.Contains("managedReference") &&
currentProperty.managedReferenceFieldTypename == StaticData.samplerSerializedFieldType)
m_PropertiesContainer.Add(new SamplerElement(currentProperty.Copy(), parameter));
else
{
var propertyField = new PropertyField(currentProperty.Copy());
propertyField.Bind(currentProperty.serializedObject);
m_PropertiesContainer.Add(propertyField);
}
} while (currentProperty.NextVisible(false));
}
}
void CreateCategoricalParameterFields()
{
var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{StaticData.uxmlDir}/CategoricalParameterTemplate.uxml").CloneTree();
var optionsProperty = m_SerializedProperty.FindPropertyRelative("m_Categories");
var probabilitiesProperty = m_SerializedProperty.FindPropertyRelative("probabilities");
var probabilities = categoricalParameter.probabilities;
var listView = template.Q<ListView>("options");
listView.itemsSource = probabilities;
listView.itemHeight = 22;
listView.selectionType = SelectionType.None;
listView.style.flexGrow = 1.0f;
listView.style.height = new StyleLength(listView.itemHeight * 4);
VisualElement MakeItem() => new CategoricalOptionElement(
optionsProperty, probabilitiesProperty);
listView.makeItem = MakeItem;
void BindItem(VisualElement e, int i)
{
var optionElement = (CategoricalOptionElement)e;
optionElement.BindProperties(i);
var removeButton = optionElement.Q<Button>("remove");
removeButton.clicked += () =>
{
probabilitiesProperty.DeleteArrayElementAtIndex(i);
// First delete sets option to null, second delete removes option
var numOptions = optionsProperty.arraySize;
optionsProperty.DeleteArrayElementAtIndex(i);
if (numOptions == optionsProperty.arraySize)
optionsProperty.DeleteArrayElementAtIndex(i);
m_SerializedProperty.serializedObject.ApplyModifiedProperties();
listView.itemsSource = categoricalParameter.probabilities;
listView.Refresh();
};
}
listView.bindItem = BindItem;
var addOptionButton = template.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 addFolderButton = template.Q<Button>("add-folder");
if (categoricalParameter.sampleType.IsSubclassOf(typeof(Object)))
{
addFolderButton.clicked += () =>
{
var folderPath = EditorUtility.OpenFolderPanel(
"Add Options From Folder", Application.dataPath, string.Empty);
if (folderPath == string.Empty)
return;
var categories = LoadAssetsFromFolder(folderPath, categoricalParameter.sampleType);
probabilitiesProperty.arraySize += categories.Count;
optionsProperty.arraySize += categories.Count;
var uniformProbability = 1f / categories.Count;
for (var i = 0; i < categories.Count; i++)
{
var optionProperty = optionsProperty.GetArrayElementAtIndex(i);
var probabilityProperty = probabilitiesProperty.GetArrayElementAtIndex(i);
optionProperty.objectReferenceValue = categories[i];
probabilityProperty.floatValue = uniformProbability;
}
m_SerializedProperty.serializedObject.ApplyModifiedProperties();
listView.itemsSource = categoricalParameter.probabilities;
listView.Refresh();
};
}
else
addFolderButton.style.display = new StyleEnum<DisplayStyle>(DisplayStyle.None);
var clearOptionsButton = template.Q<Button>("clear-options");
clearOptionsButton.clicked += () =>
{
probabilitiesProperty.arraySize = 0;
optionsProperty.arraySize = 0;
m_SerializedProperty.serializedObject.ApplyModifiedProperties();
listView.itemsSource = categoricalParameter.probabilities;
listView.Refresh();
};
var scrollView = listView.Q<ScrollView>();
listView.RegisterCallback<WheelEvent>(evt =>
{
if (Mathf.Approximately(scrollView.verticalScroller.highValue, 0f))
return;
if ((scrollView.scrollOffset.y <= 0f && evt.delta.y < 0f) ||
scrollView.scrollOffset.y >= scrollView.verticalScroller.highValue && evt.delta.y > 0f)
evt.StopImmediatePropagation();
});
var uniformToggle = template.Q<Toggle>("uniform");
var uniformProperty = m_SerializedProperty.FindPropertyRelative("uniform");
uniformToggle.BindProperty(uniformProperty);
void ToggleProbabilityFields(bool toggle)
{
if (toggle)
listView.AddToClassList("uniform-probability");
else
listView.RemoveFromClassList("uniform-probability");
}
ToggleProbabilityFields(uniformToggle.value);
if (Application.isPlaying)
uniformToggle.SetEnabled(false);
else
uniformToggle.RegisterCallback<ChangeEvent<bool>>(evt => ToggleProbabilityFields(evt.newValue));
var seedField = template.Q<IntegerField>("seed");
seedField.BindProperty(m_SerializedProperty.FindPropertyRelative("m_Sampler.<baseSeed>k__BackingField"));
m_PropertiesContainer.Add(template);
}
static List<Object> LoadAssetsFromFolder(string folderPath, Type assetType)
{
if (!folderPath.StartsWith(Application.dataPath))
throw new ApplicationException("Selected folder is not an asset folder in this project");
var assetsPath = "Assets" + folderPath.Remove(0, Application.dataPath.Length);
var assetIds = AssetDatabase.FindAssets($"t:{assetType.Name}", new []{assetsPath});
var assets = new List<Object>();
foreach (var guid in assetIds)
assets.Add(AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), assetType));
return assets;
}
}
}

8
com.unity.perception/Editor/Randomization/VisualElements/ParameterElement.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: b15caa7425ab4b9a8367bd544ab4730d
timeCreated: 1600754567
=======
guid: ea72d77c64d1447aa195e2068f02cf74
timeCreated: 1595279847
>>>>>>> 86d25d2... implemented parameter behaviours

8
com.unity.perception/Editor/Randomization/VisualElements/RandomSeedField.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 7df00c41d9394fa0ae239349350cb563
timeCreated: 1600754567
=======
guid: b4fa54f5ed5d4d67a278fa8b42dc55cb
timeCreated: 1596171029
>>>>>>> 86d25d2... implemented parameter behaviours

93
com.unity.perception/Editor/Randomization/VisualElements/RandomizerElement.cs


using System;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.Experimental.Perception.Randomization.Editor;
using UnityEngine.Experimental.Perception.Randomization.Randomizers;
using UnityEngine.UIElements;
namespace UnityEngine.Experimental.Perception.Randomization.VisualElements
{
class RandomizerElement : VisualElement
{
SerializedProperty m_Collapsed;
SerializedProperty m_Property;
VisualElement m_PropertiesContainer;
Randomizer randomizer => (Randomizer)StaticData.GetManagedReferenceValue(m_Property);
public Type randomizerType => randomizer.GetType();
const string k_CollapsedParameterClass = "collapsed";
public RandomizerList randomizerList { get; }
public bool collapsed
{
get => m_Collapsed.boolValue;
set
{
m_Collapsed.boolValue = value;
m_Property.serializedObject.ApplyModifiedProperties();
if (value)
AddToClassList(k_CollapsedParameterClass);
else
RemoveFromClassList(k_CollapsedParameterClass);
}
}
public RandomizerElement(SerializedProperty property, RandomizerList randomizerList)
{
m_Property = property;
this.randomizerList = randomizerList;
m_Collapsed = property.FindPropertyRelative("collapsed");
AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{StaticData.uxmlDir}/RandomizerElement.uxml").CloneTree(this);
var classNameLabel = this.Q<TextElement>("class-name");
var splitType = property.managedReferenceFullTypename.Split(' ', '.');
classNameLabel.text = splitType[splitType.Length - 1];
m_PropertiesContainer = this.Q<VisualElement>("properties");
var collapseToggle = this.Q<VisualElement>("collapse");
collapseToggle.RegisterCallback<MouseUpEvent>(evt => collapsed = !collapsed);
var enabledToggle = this.Q<Toggle>("enabled");
enabledToggle.BindProperty(property.FindPropertyRelative("<enabled>k__BackingField"));
var removeButton = this.Q<Button>("remove");
removeButton.clicked += () => randomizerList.RemoveRandomizer(this);
this.AddManipulator(new DragToReorderManipulator());
FillPropertiesContainer();
}
void FillPropertiesContainer()
{
m_PropertiesContainer.Clear();
var iterator = m_Property.Copy();
var nextSiblingProperty = m_Property.Copy();
nextSiblingProperty.NextVisible(false);
var foundProperties = false;
if (iterator.NextVisible(true))
{
do
{
if (SerializedProperty.EqualContents(iterator, nextSiblingProperty))
break;
if (iterator.name == "<enabled>k__BackingField")
continue;
foundProperties = true;
var propertyField = new PropertyField(iterator.Copy());
propertyField.Bind(m_Property.serializedObject);
m_PropertiesContainer.Add(propertyField);
} while (iterator.NextVisible(false));
}
if (!foundProperties)
m_PropertiesContainer.style.display = new StyleEnum<DisplayStyle>(DisplayStyle.None);
}
}
}

3
com.unity.perception/Editor/Randomization/VisualElements/RandomizerElement.cs.meta


fileFormatVersion: 2
guid: b06477660dbb47749bbc3db0aeb5005d
timeCreated: 1600290125

92
com.unity.perception/Editor/Randomization/VisualElements/RandomizerList.cs


using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.Experimental.Perception.Randomization.Editor;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
using UnityEngine.Experimental.Perception.Randomization.Scenarios;
using UnityEngine.UIElements;
namespace UnityEngine.Experimental.Perception.Randomization.VisualElements
{
class RandomizerList : VisualElement
{
SerializedProperty m_Property;
VisualElement m_Container;
ToolbarMenu m_AddRandomizerMenu;
ScenarioBase scenario => (ScenarioBase)m_Property.serializedObject.targetObject;
public RandomizerList(SerializedProperty property)
{
m_Property = property;
AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{StaticData.uxmlDir}/RandomizerList.uxml").CloneTree(this);
m_Container = this.Q<VisualElement>("randomizers-container");
m_AddRandomizerMenu = this.Q<ToolbarMenu>("add-randomizer");
var expandAllButton = this.Q<Button>("expand-all");
expandAllButton.clicked += () => CollapseRandomizers(false);
var collapseAllButton = this.Q<Button>("collapse-all");
collapseAllButton.clicked += () => CollapseRandomizers(true);
RefreshList();
}
void RefreshList()
{
m_Container.Clear();
for (var i = 0; i < m_Property.arraySize; i++)
m_Container.Add(new RandomizerElement(m_Property.GetArrayElementAtIndex(i), this));
SetMenuOptions();
}
void SetMenuOptions()
{
m_AddRandomizerMenu.menu.MenuItems().Clear();
var typeSet = new HashSet<Type>();
foreach (var randomizer in scenario.randomizers)
typeSet.Add(randomizer.GetType());
foreach (var randomizerType in StaticData.randomizerTypes)
{
if (typeSet.Contains(randomizerType))
continue;
m_AddRandomizerMenu.menu.AppendAction(
Parameter.GetDisplayName(randomizerType),
a => { AddRandomizer(randomizerType); });
}
}
void AddRandomizer(Type randomizerType)
{
var newRandomizer = scenario.CreateRandomizer(randomizerType);
newRandomizer.RandomizeParameterSeeds();
m_Property.serializedObject.Update();
RefreshList();
}
public void RemoveRandomizer(RandomizerElement element)
{
scenario.RemoveRandomizer(element.randomizerType);
m_Property.serializedObject.Update();
RefreshList();
}
public void ReorderRandomizer(int currentIndex, int nextIndex)
{
if (currentIndex == nextIndex)
return;
scenario.ReorderRandomizer(currentIndex, nextIndex);
m_Property.serializedObject.Update();
RefreshList();
}
void CollapseRandomizers(bool collapsed)
{
foreach (var child in m_Container.Children())
((RandomizerElement)child).collapsed = collapsed;
}
}
}

3
com.unity.perception/Editor/Randomization/VisualElements/RandomizerList.cs.meta


fileFormatVersion: 2
guid: dcef5294bac746bbad269c94b529f7df
timeCreated: 1600366159

8
com.unity.perception/Editor/Randomization/VisualElements/SamplerElement.cs.meta


fileFormatVersion: 2
<<<<<<< HEAD
guid: 134b50014b9f4c0694a087d3529ea4c2
timeCreated: 1600754567
=======
guid: b367f8f2cb8e465ca2d60ccbd5414a14
timeCreated: 1595277943
>>>>>>> 86d25d2... implemented parameter behaviours

107
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsva.cs


using System;
using Unity.Mathematics;
namespace UnityEngine.Experimental.Perception.Randomization.Parameters
{
/// <summary>
/// A struct representing the hue, saturation, value, and alpha components of a particular color
/// </summary>
[Serializable]
public struct ColorHsva
{
/// <summary>
/// A float value representing the hue component of a color
/// </summary>
public float h;
/// <summary>
/// A float value representing the saturation component of a color
/// </summary>
public float s;
/// <summary>
/// A float value representing the value component of a color
/// </summary>
public float v;
/// <summary>
/// A float value representing the alpha component of a color
/// </summary>
public float a;
/// <summary>
/// Constructs an ColorHsva struct
/// </summary>
/// <param name="h">Hue</param>
/// <param name="s">Saturation</param>
/// <param name="v">Value</param>
/// <param name="a">Alpha</param>
public ColorHsva(float h, float s, float v, float a)
{
this.h = h;
this.s = s;
this.v = v;
this.a = a;
}
/// <summary>
/// Implicitly converts an HSVA Color to a float4
/// </summary>
/// <param name="c">The HSVA color to convert to a float4</param>
/// <returns>A new float4</returns>
public static implicit operator float4(ColorHsva c) => new float4(c.h, c.s, c.v, c.a);
/// <summary>
/// Implicitly converts an float4 to an HSVA color
/// </summary>
/// <param name="f">The float4 to convert to an HSVA color</param>
/// <returns>A new HSVA color</returns>
public static implicit operator ColorHsva(float4 f) => new ColorHsva(f.x, f.y, f.z, f.w);
/// <summary>
/// Implicitly converts an HSVA Color to a Vector4
/// </summary>
/// <param name="c">The HSVA color to convert to a Vector4</param>
/// <returns>A new Vector4</returns>
public static implicit operator Vector4(ColorHsva c) => new float4(c.h, c.s, c.v, c.a);
/// <summary>
/// Implicitly converts an Vector4 to an HSVA color
/// </summary>
/// <param name="v">The Vector4 color to convert to an HSVA color</param>
/// <returns>A new HSVA color</returns>
public static implicit operator ColorHsva(Vector4 v) => new ColorHsva(v.x, v.y, v.z, v.w);
/// <summary>
/// Converts an HSVA Color to an RGBA Color
/// </summary>
/// <param name="c">The HSVA color to convert to RGBA</param>
/// <returns>A new RGBA color</returns>
public static explicit operator Color(ColorHsva c)
{
var color = Color.HSVToRGB(c.h, c.s, c.v);
color.a = c.a;
return color;
}
/// <summary>
/// Converts an RGBA Color to an HSVA Color
/// </summary>
/// <param name="c">The RGBA color to convert to HSVA</param>
/// <returns>A new HSVA color</returns>
public static explicit operator ColorHsva(Color c)
{
Color.RGBToHSV(c, out var h, out var s, out var v);
return new ColorHsva(h, s, v, c.a);
}
/// <summary>
/// Generates a string representation of a ColorHsva
/// </summary>
/// <returns>A string representing the components of this ColorHsva</returns>
public override string ToString()
{
return $"ColorHsva({h}, {s}, {v}, {a})";
}
}
}

3
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsva.cs.meta


fileFormatVersion: 2
guid: ccdce8798ec146649d4714046529de2c
timeCreated: 1598326388

10
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsvaCategoricalParameter.cs


using System;
namespace UnityEngine.Experimental.Perception.Randomization.Parameters
{
/// <summary>
/// A categorical parameter for generating ColorHsva samples
/// </summary>
[Serializable]
public class ColorHsvaCategoricalParameter : CategoricalParameter<ColorHsva> { }
}

3
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsvaCategoricalParameter.cs.meta


fileFormatVersion: 2
guid: e7985c4ea0bf49578e9cabd2c1a63cb6
timeCreated: 1598217458

181
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorHsvaParameter.cs


using System;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine.Experimental.Perception.Randomization.Samplers;
namespace UnityEngine.Experimental.Perception.Randomization.Parameters
{
/// <summary>
/// A numeric parameter for generating color samples using HSVA samplers
/// </summary>
[Serializable]
public class ColorHsvaParameter : NumericParameter<Color>
{
/// <summary>
/// The sampler used for randomizing the hue component of generated samples
/// </summary>
[SerializeReference] public ISampler hue = new UniformSampler(0f, 1f);
/// <summary>
/// The sampler used for randomizing the saturation component of generated samples
/// </summary>
[SerializeReference] public ISampler saturation = new UniformSampler(0f, 1f);
/// <summary>
/// The sampler used for randomizing the value component of generated samples
/// </summary>
[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);
/// <summary>
/// The sampler used for randomizing the alpha component of generated samples
/// </summary>
[SerializeReference] public ISampler alpha = new ConstantSampler(1f);
/// <summary>
/// Returns an IEnumerable that iterates over each sampler field in this parameter
/// </summary>
public override IEnumerable<ISampler> samplers
{
get
{
yield return hue;
yield return saturation;
yield return value;
yield return alpha;
}
}
/// <summary>
/// Generates an RGBA color sample
/// </summary>
/// <returns>The generated RGBA sample</returns>
public override Color Sample()
{
var color = Color.HSVToRGB(hue.Sample(), saturation.Sample(), value.Sample());
color.a = alpha.Sample();
return color;
}
/// <summary>
/// Generates an HSVA color sample
/// </summary>
/// <returns>The generated HSVA sample</returns>
public ColorHsva SampleHsva()
{
return new ColorHsva(hue.Sample(), saturation.Sample(), value.Sample(), alpha.Sample());
}
/// <summary>
/// Schedules a job to generate an array of RGBA color samples
/// </summary>
/// <param name="sampleCount">The number of samples to generate</param>
/// <param name="jobHandle">The handle of the scheduled job</param>
/// <returns>A NativeArray of samples</returns>
public override NativeArray<Color> Samples(int sampleCount, out JobHandle jobHandle)
{
var samples = new NativeArray<Color>(sampleCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
var hueRng = hue.Samples(sampleCount, out var hueHandle);
var satRng = saturation.Samples(sampleCount, out var satHandle);
var valRng = value.Samples(sampleCount, out var valHandle);
var alphaRng = alpha.Samples(sampleCount, out var alphaHandle);
var handles = new NativeArray<JobHandle>(4, Allocator.TempJob)
{
[0] = hueHandle,
[1] = satHandle,
[2] = valHandle,
[3] = alphaHandle
};
var combinedJobHandles = JobHandle.CombineDependencies(handles);
jobHandle = new SamplesJob
{
hueRng = hueRng,
satRng = satRng,
valRng = valRng,
alphaRng = alphaRng,
samples = samples
}.Schedule(combinedJobHandles);
handles.Dispose(jobHandle);
return samples;
}
[BurstCompile]
struct SamplesJob : IJob
{
[DeallocateOnJobCompletion] public NativeArray<float> hueRng;
[DeallocateOnJobCompletion] public NativeArray<float> satRng;
[DeallocateOnJobCompletion] public NativeArray<float> valRng;
[DeallocateOnJobCompletion] public NativeArray<float> alphaRng;
public NativeArray<Color> samples;
static Color CreateColorHsva(float h, float s, float v, float a)
{
var color = Color.HSVToRGB(h, s, v);
color.a = a;
return color;
}
public void Execute()
{
for (var i = 0; i < samples.Length; i++)
samples[i] = CreateColorHsva(hueRng[i], satRng[i], valRng[i], alphaRng[i]);
}
}
/// <summary>
/// Schedules a job to generate an array of HSVA color samples
/// </summary>
/// <param name="sampleCount">The number of samples to generate</param>
/// <param name="jobHandle">The handle of the scheduled job</param>
/// <returns>A NativeArray of samples</returns>
public NativeArray<ColorHsva> SamplesHsva(int sampleCount, out JobHandle jobHandle)
{
var samples = new NativeArray<ColorHsva>(sampleCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
var hueRng = hue.Samples(sampleCount, out var hueHandle);
var satRng = saturation.Samples(sampleCount, out var satHandle);
var valRng = value.Samples(sampleCount, out var valHandle);
var alphaRng = alpha.Samples(sampleCount, out var alphaHandle);
var handles = new NativeArray<JobHandle>(4, Allocator.TempJob)
{
[0] = hueHandle,
[1] = satHandle,
[2] = valHandle,
[3] = alphaHandle
};
var combinedJobHandles = JobHandle.CombineDependencies(handles);
jobHandle = new SamplesHsvaJob
{
hueRng = hueRng,
satRng = satRng,
valRng = valRng,
alphaRng = alphaRng,
samples = samples
}.Schedule(combinedJobHandles);
handles.Dispose(jobHandle);
return samples;
}
[BurstCompile]
struct SamplesHsvaJob : IJob
{
[DeallocateOnJobCompletion] public NativeArray<float> hueRng;
[DeallocateOnJobCompletion] public NativeArray<float> satRng;
[DeallocateOnJobCompletion] public NativeArray<float> valRng;
[DeallocateOnJobCompletion] public NativeArray<float> alphaRng;
public NativeArray<ColorHsva> samples;
public void Execute()
{
for (var i = 0; i < samples.Length; i++)
samples[i] = new ColorHsva(hueRng[i], satRng[i], valRng[i], alphaRng[i]);
}
}
}
}

10
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorRgbCategoricalParameter.cs


using System;
namespace UnityEngine.Experimental.Perception.Randomization.Parameters
{
/// <summary>
/// A categorical parameter for generating RGBA color samples
/// </summary>
[Serializable]
public class ColorRgbCategoricalParameter : CategoricalParameter<Color> { }
}

3
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorRgbCategoricalParameter.cs.meta


fileFormatVersion: 2
guid: f4bd575c48a145ec9b63eb48ce636ed7
timeCreated: 1598251957

111
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorRgbParameter.cs


using System;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine.Experimental.Perception.Randomization.Samplers;
namespace UnityEngine.Experimental.Perception.Randomization.Parameters
{
/// <summary>
/// A numeric parameter for generating RGBA color samples
/// </summary>
[Serializable]
public class ColorRgbParameter : NumericParameter<Color>
{
/// <summary>
/// The sampler used for randomizing the red component of generated samples
/// </summary>
[SerializeReference] public ISampler red = new UniformSampler(0f, 1f);
/// <summary>
/// The sampler used for randomizing the green component of generated samples
/// </summary>
[SerializeReference] public ISampler green = new UniformSampler(0f, 1f);
/// <summary>
/// The sampler used for randomizing the blue component of generated samples
/// </summary>
[SerializeReference] public ISampler blue = new UniformSampler(0f, 1f);
/// <summary>
/// The sampler used for randomizing the alpha component of generated samples
/// </summary>
[SerializeReference] public ISampler alpha = new ConstantSampler(1f);
/// <summary>
/// Returns an IEnumerable that iterates over each sampler field in this parameter
/// </summary>
public override IEnumerable<ISampler> samplers
{
get
{
yield return red;
yield return green;
yield return blue;
yield return alpha;
}
}
/// <summary>
/// Generates an RGBA color sample
/// </summary>
/// <returns>The generated RGBA sample</returns>
public override Color Sample()
{
return new Color(red.Sample(), green.Sample(), blue.Sample(), alpha.Sample());
}
/// <summary>
/// Schedules a job to generate an array of samples
/// </summary>
/// <param name="sampleCount">The number of samples to generate</param>
/// <param name="jobHandle">The handle of the scheduled job</param>
/// <returns>A NativeArray of samples</returns>
public override NativeArray<Color> Samples(int sampleCount, out JobHandle jobHandle)
{
var samples = new NativeArray<Color>(sampleCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
var redRng = red.Samples(sampleCount, out var redHandle);
var greenRng = green.Samples(sampleCount, out var greenHandle);
var blueRng = blue.Samples(sampleCount, out var blueHandle);
var alphaRng = alpha.Samples(sampleCount, out var alphaHandle);
var handles = new NativeArray<JobHandle>(4, Allocator.TempJob)
{
[0] = redHandle,
[1] = greenHandle,
[2] = blueHandle,
[3] = alphaHandle
};
var combinedJobHandles = JobHandle.CombineDependencies(handles);
jobHandle = new SamplesJob
{
redRng = redRng,
greenRng = greenRng,
blueRng = blueRng,
alphaRng = alphaRng,
samples = samples
}.Schedule(combinedJobHandles);
handles.Dispose(jobHandle);
return samples;
}
[BurstCompile]
struct SamplesJob : IJob
{
[DeallocateOnJobCompletion] public NativeArray<float> redRng;
[DeallocateOnJobCompletion] public NativeArray<float> greenRng;
[DeallocateOnJobCompletion] public NativeArray<float> blueRng;
[DeallocateOnJobCompletion] public NativeArray<float> alphaRng;
public NativeArray<Color> samples;
public void Execute()
{
for (var i = 0; i < samples.Length; i++)
samples[i] = new Color(redRng[i], greenRng[i], blueRng[i], alphaRng[i]);
}
}
}
}

3
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorParameters/ColorRgbParameter.cs.meta


fileFormatVersion: 2
guid: a4fdf61227254683a9950f586d6e8f57
timeCreated: 1598252064

140
com.unity.perception/Runtime/Randomization/Randomizers/Randomizer.cs


using System;
using System.Collections.Generic;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
using UnityEngine.Experimental.Perception.Randomization.Scenarios;
namespace UnityEngine.Experimental.Perception.Randomization.Randomizers
{
/// <summary>
/// Derive Randomizer to implement systems that randomize GameObjects and/or simulation properties.
/// </summary>
/// <remark>
/// Known issue:
/// https://issuetracker.unity3d.com/issues/serializereference-non-serialized-initialized-fields-lose-their-values-when-entering-play-mode
/// </remark>
[Serializable]
public abstract class Randomizer
{
bool m_PreviouslyEnabled;
// ReSharper disable once InconsistentNaming
internal ScenarioBase m_Scenario;
// ReSharper disable once InconsistentNaming
internal RandomizerTagManager m_TagManager;
[HideInInspector, SerializeField] internal bool collapsed;
/// <summary>
/// Enabled Randomizers are updated, disabled Randomizers are not.
/// </summary>
[field: SerializeField] public bool enabled { get; set; } = true;
/// <summary>
/// Returns the scenario containing this Randomizer
/// </summary>
public ScenarioBase scenario => m_Scenario;
/// <summary>
/// Retrieves the RandomizerTagManager of the scenario containing this Randomizer
/// </summary>
public RandomizerTagManager tagManager => m_TagManager;
internal IEnumerable<Parameter> parameters
{
get
{
var fields = GetType().GetFields();
foreach (var field in fields)
{
if (!field.IsPublic || !field.FieldType.IsSubclassOf(typeof(Parameter)))
continue;
var parameter = (Parameter)field.GetValue(this);
if (parameter == null)
{
parameter = (Parameter)Activator.CreateInstance(field.FieldType);
field.SetValue(this, parameter);
}
yield return parameter;
}
}
}
/// <summary>
/// OnCreate is called when the Randomizer is added or loaded to a scenario
/// </summary>
protected virtual void OnCreate() { }
/// <summary>
/// OnIterationStart is called at the start of a new scenario iteration
/// </summary>
protected virtual void OnIterationStart() { }
/// <summary>
/// OnIterationEnd is called the after a scenario iteration has completed
/// </summary>
protected virtual void OnIterationEnd() { }
/// <summary>
/// OnScenarioComplete is called the after the entire scenario has completed
/// </summary>
protected virtual void OnScenarioComplete() { }
/// <summary>
/// OnStartRunning is called on the first frame a Randomizer is enabled
/// </summary>
protected virtual void OnStartRunning() { }
/// <summary>
/// OnStartRunning is called on the first frame a disabled Randomizer is updated
/// </summary>
protected virtual void OnStopRunning() { }
/// <summary>
/// OnUpdate is executed every frame for enabled Randomizers
/// </summary>
protected virtual void OnUpdate() { }
internal virtual void Create()
{
OnCreate();
}
internal virtual void IterationStart()
{
OnIterationStart();
}
internal virtual void IterationEnd()
{
OnIterationEnd();
}
internal virtual void ScenarioComplete()
{
OnScenarioComplete();
}
internal void Update()
{
if (enabled)
{
if (!m_PreviouslyEnabled)
{
m_PreviouslyEnabled = true;
OnStartRunning();
}
OnUpdate();
}
else if (m_PreviouslyEnabled)
{
m_PreviouslyEnabled = false;
OnStopRunning();
}
}
internal void RandomizeParameterSeeds()
{
foreach (var parameter in parameters)
parameter.RandomizeSamplers();
}
}
}

3
com.unity.perception/Runtime/Randomization/Randomizers/Randomizer.cs.meta


fileFormatVersion: 2
guid: 3a0043de777a49488339296ce069550d
timeCreated: 1600274620

25
com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTag.cs


using System;
using UnityEngine.Experimental.Perception.Randomization.Scenarios;
namespace UnityEngine.Experimental.Perception.Randomization.Randomizers
{
/// <summary>
/// Derive the RandomizerTag class to create new tag components.
/// RandomizerTags are used to help randomizers query for a set of GameObjects to randomize.
/// </summary>
[Serializable]
public abstract class RandomizerTag : MonoBehaviour
{
void Awake()
{
ScenarioBase.activeScenario.tagManager.AddTag(GetType(), gameObject);
}
void OnDestroy()
{
var scenario = ScenarioBase.activeScenario;
if (scenario)
scenario.tagManager.RemoveTag(GetType(), gameObject);
}
}
}

3
com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTag.cs.meta


fileFormatVersion: 2
guid: 1a4fbe784c3d410988a620711a78a68c
timeCreated: 1600717080

44
com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTagManager.cs


using System;
using System.Collections.Generic;
using System.Linq;
namespace UnityEngine.Experimental.Perception.Randomization.Randomizers
{
/// <summary>
/// Organizes RandomizerTags attached to GameObjects in the scene
/// </summary>
public class RandomizerTagManager
{
Dictionary<Type, HashSet<GameObject>> m_TagMap = new Dictionary<Type, HashSet<GameObject>>();
/// <summary>
/// Returns a list of all GameObjects in the scene that have a RandomizerTag of the given type
/// </summary>
/// <typeparam name="T">The type of RandomizerTag to query for</typeparam>
/// <returns>A list of GameObjects with the given RandomizerTag</returns>
public GameObject[] Query<T>() where T : RandomizerTag
{
var type = typeof(T);
return m_TagMap.ContainsKey(type) ? m_TagMap[type].ToArray() : new GameObject[0];
}
internal void AddTag(Type tagType, GameObject obj)
{
if (m_TagMap.ContainsKey(tagType))
{
m_TagMap[tagType].Add(obj);
}
else
{
var newSet = new HashSet<GameObject> { obj };
m_TagMap.Add(tagType, newSet);
}
}
internal void RemoveTag(Type tagType, GameObject obj)
{
if (m_TagMap.ContainsKey(tagType))
m_TagMap[tagType].Remove(obj);
}
}
}

3
com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTagManager.cs.meta


fileFormatVersion: 2
guid: f9218725d6964d589d0dcb001e29744d
timeCreated: 1600717731

6
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/ExampleTag.cs


using UnityEngine.Experimental.Perception.Randomization.Randomizers;
namespace RandomizationTests.RandomizerTests
{
public class ExampleTag : RandomizerTag { }
}

3
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/ExampleTag.cs.meta


fileFormatVersion: 2
guid: 03b2ff8b0d794506bd887a94204d85f4
timeCreated: 1600747384

30
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/ExampleTransformRandomizer.cs


using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Experimental.Perception.Randomization.Parameters;
using UnityEngine.Experimental.Perception.Randomization.Randomizers;
namespace RandomizationTests.RandomizerTests
{
public class ExampleTransformRandomizer : Randomizer
{
public Vector3Parameter position = new Vector3Parameter();
public Vector3Parameter rotation = new Vector3Parameter();
public Transform transform;
protected override void OnCreate()
{
transform = scenario.transform;
}
protected override void OnUpdate()
{
transform.position = position.Sample();
}
protected override void OnIterationStart()
{
transform.rotation = quaternion.Euler(rotation.Sample());
}
}
}

3
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/ExampleTransformRandomizer.cs.meta


fileFormatVersion: 2
guid: 9ea673939dfa4285b0752c784d21f3f3
timeCreated: 1600744655

40
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTagTests.cs


using NUnit.Framework;
using UnityEngine;
using UnityEngine.Experimental.Perception.Randomization.Scenarios;
using Assert = Unity.Assertions.Assert;
namespace RandomizationTests.RandomizerTests
{
[TestFixture]
public class RandomizerTagTests
{
GameObject m_TestObject;
FixedLengthScenario m_Scenario;
[SetUp]
public void Setup()
{
m_TestObject = new GameObject();
m_Scenario = m_TestObject.AddComponent<FixedLengthScenario>();
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_TestObject);
}
[Test]
public void TagQueryFindsCorrectNumberOfGameObjects()
{
const int copyCount = 5;
var gameObject = new GameObject();
gameObject.AddComponent<ExampleTag>();
for (var i = 0; i < copyCount - 1; i++)
Object.Instantiate(gameObject);
var queriedObjects = m_Scenario.tagManager.Query<ExampleTag>();
Assert.AreEqual(queriedObjects.Length, copyCount);
}
}
}

3
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTagTests.cs.meta


fileFormatVersion: 2
guid: adcecb355e194c7e8212f1c2de0e5176
timeCreated: 1600747276

89
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTests.cs


using System.Collections;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.Experimental.Perception.Randomization.Scenarios;
using UnityEngine.TestTools;
namespace RandomizationTests.RandomizerTests
{
[TestFixture]
public class RandomizerTests
{
GameObject m_TestObject;
FixedLengthScenario m_Scenario;
[SetUp]
public void Setup()
{
m_TestObject = new GameObject();
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_TestObject);
}
// 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;
m_Scenario.constants.framesPerIteration = framesPerIteration;
yield return null; // Skip first frame
}
[Test]
public void OneRandomizerInstancePerTypeTest()
{
m_Scenario = m_TestObject.AddComponent<FixedLengthScenario>();
m_Scenario.CreateRandomizer<ExampleTransformRandomizer>();
Assert.Throws<ScenarioException>(() => m_Scenario.CreateRandomizer<ExampleTransformRandomizer>());
}
[UnityTest]
public IEnumerator OnUpdateExecutesEveryFrame()
{
yield return CreateNewScenario(10, 1);
m_Scenario.CreateRandomizer<ExampleTransformRandomizer>();
var transform = m_TestObject.transform;
var initialPosition = Vector3.zero;
transform.position = initialPosition;
yield return null;
Assert.AreNotEqual(initialPosition, transform.position);
// ReSharper disable once Unity.InefficientPropertyAccess
initialPosition = transform.position;
yield return null;
// ReSharper disable once Unity.InefficientPropertyAccess
Assert.AreNotEqual(initialPosition, transform.position);
}
[UnityTest]
public IEnumerator OnIterationStartExecutesEveryIteration()
{
yield return CreateNewScenario(10, 2);
m_Scenario.CreateRandomizer<ExampleTransformRandomizer>();
var transform = m_TestObject.transform;
var initialRotation = Quaternion.identity;
transform.rotation = initialRotation;
yield return null;
Assert.AreNotEqual(initialRotation, transform.rotation);
// ReSharper disable once Unity.InefficientPropertyAccess
initialRotation = transform.rotation;
yield return null;
// ReSharper disable once Unity.InefficientPropertyAccess
Assert.AreEqual(initialRotation, transform.rotation);
// ReSharper disable once Unity.InefficientPropertyAccess
initialRotation = transform.rotation;
yield return null;
// ReSharper disable once Unity.InefficientPropertyAccess
Assert.AreNotEqual(initialRotation, transform.rotation);
}
}
}

3
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTests.cs.meta


fileFormatVersion: 2
guid: 4eedc6c78eed4f40aea7fa4f3dea0e34
timeCreated: 1600744209

213
com.unity.perception/Editor/Randomization/Uss/Styles.uss


.dark-viewport {
border-radius: 5px;
background-color: #191919;
padding: 2px;
}
.parameter-container {
border-width: 2px;
border-radius: 5px;
flex-direction: row;
margin: 2px 1px;
}
.parameter-type-menu {
margin: 1px 3px;
border-width: 1px;
border-radius: 3px;
background-color: #585858;
}
#parameter-type-menu .unity-toolbar-menu__text {
font-size: 13px;
padding: 3px;
}
.sampler-type-menu {
flex-grow: 1.5;
border-radius: 3px;
border-width: 1px;
margin-top: 2px;
margin-right: 3px;
}
.sampler-name {
/*color: lightgreen;*/
-unity-font-style: bold;
}
.parameter-type-label-container {
flex-direction: row;
justify-content: space-between;
align-items: center;
margin-bottom: 1px;
}
.parameter-type-label-box {
flex-direction: row;
align-items: center;
justify-content: flex-start;
flex-grow: 0;
-unity-text-align: middle-center;
border-width: 0;
padding: 1px;
font-size: 13px;
-unity-font-style: bold;
}
.parameter-type-label {
color: cornflowerblue;
/*min-width: 120px;*/
-unity-text-align: middle-left;
}
.parameter-type-label-box .unity-base-text-field__input {
padding-left: 6px;
padding-right: 6px;
}
.unity-toggle {
margin-left: 0;
}
.property-selection-container {
flex-direction: row;
}
.property-select-menu {
flex-grow: 1;
border-width: 1px;
padding-bottom: 1px;
border-radius: 3px;
margin-right: 1px;
}
.remove-parameter-button {
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/X.png");
width: 16px;
height: 16px;
}
.move-buttons-container {
width: auto;
margin-right: 6px;
border-color: black;
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
background-color: #2A2A2A;
padding: 3px 2px;
justify-content: center;
}
.drag-handle {
width: 16px;
height: 70%;
min-height: 20px;
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/DragHandle.png");
}
.move-button {
border-width: 0;
width: 42px;
height: 16px;
padding: 9px;
-unity-background-scale-mode: scale-to-fit;
}
.unity-imgui-container {
margin-left: 1px;
margin-right: 3px;
}
.search-icon {
width: 16px;
height: 16px;
margin-top: 2px;
flex-shrink: 0;
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/Search.png");
}
.collapse-parameter-toggle {
flex-shrink: 0;
margin-right: 2px;
width: 12px;
height: 12px;
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/FoldoutOpen.png");
}
.collapsed-parameter .collapse-parameter-toggle {
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/FoldoutClosed.png");
}
.collapsed-parameter .parameter-properties-container {
display: none;
}
.collapsed-parameter .move-buttons-container {
flex-direction: row;
}
.collapsed-parameter .move-button {
width: 16px;
}
.categorical-option {
flex-direction: row;
background-color: #3F3F3F;
margin: 1px;
border-radius: 4px;
}
.options-list-view {
background-color: #191919;
border-radius: 4px;
margin-right: 2px;
padding: 3px;
border-bottom-right-radius: 0;
}
.option-property-field {
width: 0;
flex-grow: 1;
flex-shrink: 0;
}
.uniform-probability .hide-when-uniform {
display: none;
}
.add-option-button {
align-self: flex-end;
border-width: 0;
border-top-right-radius: 0;
border-top-left-radius: 0;
background-color: #191919;
margin-top: 0;
margin-right: 2px;
}
.add-option-button:hover {
background-color: #2A2A2A;
}
.add-option-button:active {
color: cornflowerblue;
}
.remove-option-button {
width: 12px;
height: 14px;
background-image: resource("Packages/com.unity.perception/Editor/Randomization/Icons/X.png");
}
.parameter-drag-bar {
width: 100px;
height: 6px;
background-color: rgba(100,149,237,0.4);
position: absolute;
}
.float-range .unity-base-field__label {
min-width: auto;
margin-right: 4px;
}

部分文件因为文件数量过多而无法显示

正在加载...
取消
保存