Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
Size: Mime:
using System.Collections.Generic;
using System.Linq;
using Fluctio.FluctioSim.Common.Configuration;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Fluctio.FluctioSim.Core.Components.MachineLearning.Agents
{
	[AddComponentMenu(Config.PrefixedName+"/Machine Learning/Training Area", Config.ComponentMenuOrder + 21)]
	[DefaultExecutionOrder(-5)] // before MLAgents initialization, same as in Unity.MLAgents.Areas.TrainingAreaReplicator
	public class TrainingArea: MonoBehaviour
	{
		[field: SerializeField, Min(1)] private int CopiesAmount { get; set; } = 30;
		[field: SerializeField, Min(Config.MinFloat)] private float Distance { get; set; } = 1;
		
		[SerializeField, HideInInspector] private bool isCopy = false;
		[SerializeField, HideInInspector] private TrainingArea original = null;

		private void OnValidate()
		{
			original ??= this;
		}

		private void Awake()
		{
			if (isCopy)
			{
				return;
			}
			isCopy = true;
			
			var positions = GetPositions().Skip(1);
			foreach (var position in positions)
			{
				var copyObject = Instantiate(gameObject, position, transform.rotation);
				var copyArea = copyObject.GetComponent<TrainingArea>();
				copyArea.original = this;
				copyObject.name = gameObject.name;
				copyObject.transform.SetParent(transform.parent);
			}

			isCopy = false;
		}

		private IEnumerable<Vector3> GetPositions()
		{
			var copiesAmountRoot = Mathf.CeilToInt(Mathf.Sqrt(CopiesAmount));
			var counter = 0;
			for (var z = 0; z < copiesAmountRoot; z++)
			{
				for (var x = 0; x < copiesAmountRoot; x++)
				{
					yield return original.transform.position + Distance * new Vector3(x, 0, z);
					counter++;
					if (counter >= CopiesAmount)
					{
						yield break;
					}
				}
			}
		}

		private void OnDrawGizmosSelected()
		{
			var positions = GetPositions();
			var size = Vector3.one * Distance;
			foreach (var position in positions)
			{
				Gizmos.color = position == transform.position ? Color.blue : Color.white;
				Gizmos.DrawWireCube(position, size);
			}
		}
		
	}
	
	#if UNITY_EDITOR
	[CustomEditor(typeof(TrainingArea), true)]
	public class TrainingAreaEditor : Editor
	{
		public override void OnInspectorGUI()
		{
			serializedObject.Update();
			using (new EditorGUI.DisabledScope(Application.isPlaying))
			{
				DrawPropertiesExcluding(serializedObject, "m_Script");
			}
			serializedObject.ApplyModifiedProperties();
		}
	}
	#endif
}