Example #1
0
        public override string Run(ArrayList arguments)
        {
            //OCObjects = GameObject.Find ("Objects") as GameObject;
            if (arguments.Count != 1)
            {
                return("Wrong number of arguments");
            }

            string agentName = (string)arguments [0];
            // Get the appropriate agent's actionController
            OCActionController actionController =
                GameObject.FindSceneObjectsOfType(typeof(OCActionController))
                .Where(ac => (ac as OCActionController).gameObject.name == agentName)
                .Cast <OCActionController>()
                .FirstOrDefault()
            ;

            string result = actionController.gameObject.name + "'s actions: ";
            bool   first  = true;

            List <OCAction> actions = actionController.GetComponentsInChildren <OCAction>().ToList();

            foreach (OCAction action in actions)
            {
                if (!first)
                {
                    result += "\n";
                }
                first   = false;
                result += action.ToString();
            }

            return(result);
        }
            //---------------------------------------------------------------------------

            #endregion

            //---------------------------------------------------------------------------

            #region Public Member Functions

            //---------------------------------------------------------------------------

            public void Start()
            {
                _AnimationEffects =
                    gameObject.GetComponentsInChildren <OCAnimationEffect>().ToList();

                _CreateBlockEffects =
                    gameObject.GetComponentsInChildren <OCCreateBlockEffect>().ToList();

                _DestroyBlockEffects =
                    gameObject.GetComponentsInChildren <OCDestroyBlockEffect>().ToList();

                _Map = (OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).LastOrDefault();

                _ActionController = _Source.GetComponent <OCActionController>();

//		foreach(OCDelegate del in _Preconditions)
//		{
//			PreCondition += (OCActionCondition)del.Delegate;
//		}
//
//		foreach(OCDelegate del in _Invariants)
//		{
//			InvariantCondition += (OCActionCondition)del.Delegate;
//		}
//
//		foreach(OCDelegate del in _Postconditions)
//		{
//			PostCondition += (OCActionCondition)del.Delegate;
//		}

                foreach (string condition in _Preconditions)
                {
                    PreCondition += (OCActionCondition)Delegate.CreateDelegate(typeof(OCActionCondition), typeof(OCAction).GetMethod(condition));
                }

                foreach (string condition in _Invariants)
                {
                    InvariantCondition += (OCActionCondition)Delegate.CreateDelegate(typeof(OCActionCondition), typeof(OCAction).GetMethod(condition));
                }

                foreach (string condition in _Postconditions)
                {
                    PostCondition += (OCActionCondition)Delegate.CreateDelegate(typeof(OCActionCondition), typeof(OCAction).GetMethod(condition));
                }

//		PreCondition += IsEndTarget;
//		InvariantCondition += IsSourceAnimating;
//		InvariantCondition += IsSourceNotRunningOtherActionsIgnoreIdle;
//		PostCondition += IsSourceRunningOtherActionsIgnoreIdle;

//		if(_EndTarget == null)
//			_EndTarget = GameObject.Find("EndPointStub");
//		if(_StartTarget == null)
//			_StartTarget = GameObject.Find("StartPointStub");

                DontDestroyOnLoad(this);
            }
Example #3
0
        public override string Run(ArrayList arguments)
        {
            //OCObjects = GameObject.Find ("Objects") as GameObject;
            if (arguments.Count != 1)
            {
                return("Wrong number of arguments");
            }

            string agentName = (string)arguments [0];

            // Get the appropriate agent's actionController
            OCActionController actionController = null;

            OCActionController[] actionControllers = Object.FindObjectsOfType(typeof(OCActionController)) as OCActionController[];


            foreach (OCActionController ac in actionControllers)
            {
                if (ac.gameObject.name == agentName)
                {
                    actionController = ac;
                }
            }

            if (actionController == null)
            {
                //If there is not currently an agent, then...
                return("There are no agent by this name with an OCActionController component. Use /load to create one.");
            }

            string result = actionController.gameObject.name + "'s actions: ";
            bool   first  = true;

            List <OCAction> actions = actionController.GetComponentsInChildren <OCAction>().ToList();

            foreach (OCAction action in actions)
            {
                if (!first)
                {
                    result += "\n";
                }
                first   = false;
                result += action.ToString();
            }

            return(result);
        }
	/**
	 * Parse action plan and append the result into action list.
	 *
	 * @param element meta action in xml format
	 */
	private void ParseActionPlanElement(XmlElement actionPlan)
	{
		// TODO: Determine if we need this:
		bool adjustCoordinate = false;
		
		OpenCog.Utility.Console.Console console = OpenCog.Utility.Console.Console.Instance;
		
		// Get the action performer id.
		string avatarId = actionPlan.GetAttribute(OCEmbodimentXMLTags.ENTITY_ID_ATTRIBUTE);
		if(avatarId != _brainID)
		{
			// Usually this would not happen.
			OCLogger.Warn("Avatar[" + _ID + "]: This action plan is not for me.");
			return;
		}
		
		// Cancel current action and clear old action plan in the list.
		if(_actionsList.Count > 0)
		{
			OCLogger.Warn("Stop all current actions");
			CancelAvatarActions();
		}
		
		GameObject endPointStub = GameObject.Find("EndPointStub");

		// Update current plan id and selected demand name.
		_currentPlanId = actionPlan.GetAttribute(OCEmbodimentXMLTags.ID_ATTRIBUTE);
		_currentDemandName = actionPlan.GetAttribute(OCEmbodimentXMLTags.DEMAND_ATTRIBUTE);
        
		// Get the action elements from the actionPlan
		XmlNodeList list = actionPlan.GetElementsByTagName(OCEmbodimentXMLTags.ACTION_ELEMENT);

		if(_actionController == null)
		{
			_actionController = GameObject.FindGameObjectWithTag("OCAGI").GetComponent<OCActionController>();
		}

		// list contains 'action' elements.
		foreach(XmlNode actionNode in list)
		{
			// Cast actionNode to actionElement (XmlElement)
			XmlElement actionElement = (XmlElement)actionNode;
			
			// Get attributes from actionElement (name, sequence)
			string actionName = actionElement.GetAttribute(OCEmbodimentXMLTags.NAME_ATTRIBUTE);
			int sequence = System.Int32.Parse(actionElement.GetAttribute(OCEmbodimentXMLTags.SEQUENCE_ATTRIBUTE));
			
			// Get the actionParameter nodes from the actionElement
			XmlNodeList actionParameters = actionElement.GetElementsByTagName(OCEmbodimentXMLTags.PARAMETER_ELEMENT);
			
			// Prepare a new actionArgs object
			OCAction.OCActionArgs actionArguments = new OCAction.OCActionArgs();
			
			actionArguments.StartTarget = GameObject.Find("StartPointStub");
			actionArguments.StartTarget.transform.position = GameObject.FindGameObjectWithTag("OCAGI").transform.position;		
			actionArguments.EndTarget = null;
			
			// 'action' elements contain 'params'
			foreach(XmlNode actionParameterNode in actionParameters)
			{
				// Cast actionParameterNode to an actionParameterElement (XmlElement)
				XmlElement actionParameterElement = (XmlElement)actionParameterNode;
				
				// Get attributes from actionParameterElement
				string actionParameterType = actionParameterElement.GetAttribute(OCEmbodimentXMLTags.TYPE_ATTRIBUTE);	
				
				switch(actionParameterType)
				{
				// If it's a vector, then it's a walk. So the target is a gameobject at the location of the vector.
				case "vector":


					XmlNodeList vectorParameterChildren = actionParameterElement.GetElementsByTagName(OCEmbodimentXMLTags.VECTOR_ELEMENT);
					XmlElement vectorElement = (XmlElement)vectorParameterChildren.Item(0);
						
					float x = float.Parse(vectorElement.GetAttribute(OCEmbodimentXMLTags.X_ATTRIBUTE), System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
					float y = float.Parse(vectorElement.GetAttribute(OCEmbodimentXMLTags.Y_ATTRIBUTE), System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
					float z = float.Parse(vectorElement.GetAttribute(OCEmbodimentXMLTags.Z_ATTRIBUTE), System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
					
//						if (adjustCoordinate)
//						{
//							x += 0.5f;
//							y += 0.5f;
//							z += 0.5f;
//						}
					
					string gameObjectString = "PLAN" + _currentPlanId.ToString().PadLeft(3, '0') + "_SEQ" + sequence.ToString().PadLeft(3, '0') + "_VECTOR";
							
					UnityEngine.GameObject vectorGameObject = (UnityEngine.GameObject)UnityEngine.GameObject.Instantiate(_map.WaypointPrefab);
					vectorGameObject.name = gameObjectString;
					vectorGameObject.transform.parent = _map.WaypointsSceneObject.transform;
					
						// Swapping Y and Z!!
					
						// ORIGINAL:
						// vectorGameObject.transform.position = new Vector3(x, y, z);
						// UnityEngine.Debug.Log ("A '" + actionName + "' command told me to go to [" + x + ", " + y + ", " + z + "]");
					
						// SWAPPED:
					vectorGameObject.transform.position = new Vector3(x, z, y);
					TextMesh textMesh = vectorGameObject.GetComponentInChildren<TextMesh>();
					textMesh.text = sequence.ToString();
						//UnityEngine.Debug.Log ("A '" + actionName + "' command (planID = " +  _currentPlanId + ", sequence = " + sequence + " told me to go to [" + x + ", " + z + ", " + y + "]");

					if(actionName == "walk" || actionName == "jump_toward")
					{

						console.AddConsoleEntry("A '" + actionName + "' command (planID = " + _currentPlanId + ", sequence = " + sequence + " told me to go to [" + x + ", " + z + ", " + y + "]", "AGI Robot", OpenCog.Utility.Console.Console.ConsoleEntry.Type.SAY);
					
						actionArguments.EndTarget = vectorGameObject;
						//actionArguments.EndTarget = GameObject.Find("EndPointStub");
						actionArguments.EndTarget.transform.position = new Vector3(x, z, y);
						

//						OCGoalController goalController = _actionController.gameObject.GetComponent<OCGoalController>();
//						goalController.BlockType = "Hearth";
//						goalController.FindGoalBlockPositionInChunks(_map.Chunks);
					
					} else if(actionName == "destroy" || actionName == "build_block")
					{
						console.AddConsoleEntry("A '" + actionName + "' command (planID = " + _currentPlanId + ", sequence = " + sequence + " told me to destroy/create block at [" + x + ", " + z + ", " + y + "]", "AGI Robot", OpenCog.Utility.Console.Console.ConsoleEntry.Type.SAY);
						
						actionArguments.EndTarget = vectorGameObject;
						//actionArguments.EndTarget = GameObject.Find("EndPointStub");
						actionArguments.EndTarget.transform.position = new Vector3(x, z, y);
					}
					
					break;	
				// If it's an entity, then it's a grab or a consume. So the target is the battery.
				case "entity":
					XmlNodeList entityParameterChildren = actionParameterElement.GetElementsByTagName(OCEmbodimentXMLTags.ENTITY_ELEMENT);
					XmlElement entityElement = (XmlElement)entityParameterChildren.Item(0);
						
					int entityID = System.Int32.Parse(entityElement.GetAttribute(OCEmbodimentXMLTags.ID_ATTRIBUTE));
					string entityType = entityElement.GetAttribute(OCEmbodimentXMLTags.TYPE_ATTRIBUTE);
					
					if(actionName == "grab" || actionName == "eat")
					{
						UnityEngine.GameObject[] batteryArray = UnityEngine.GameObject.FindGameObjectsWithTag("OCBattery");
					
						for(int iBattery = 0; iBattery < batteryArray.Length; iBattery++)
						{
							UnityEngine.GameObject batteryObject = batteryArray[iBattery];
								
							if(entityID == batteryObject.GetInstanceID())
							{
								endPointStub.transform.position = batteryObject.transform.position;
								
								// This is the one!	
								actionArguments.EndTarget = batteryObject;
									
								break;
							}
						}
						
						if(actionArguments.EndTarget != null)
						{
							// Then we can grab it, eat it, whatever...since it's a battery
							if(actionName == "grab")
							{
								//UnityEngine.Debug.Log ("A 'grab' command (planID = " +  _currentPlanId + ", sequence = " + sequence + " told me to grab an object with ID " + entityID);
								
								console.AddConsoleEntry("A 'grab' command (planID = " + _currentPlanId + ", sequence = " + sequence + " told me to grab an object with ID " + entityID, "AGI Robot", OpenCog.Utility.Console.Console.ConsoleEntry.Type.SAY);
							} else if(actionName == "eat")
							{
								//UnityEngine.Debug.Log ("An 'eat' command (planID = " +  _currentPlanId + ", sequence = " + sequence + " told me to eat an object with ID " + entityID);
								
								console.AddConsoleEntry("An 'eat' command (planID = " + _currentPlanId + ", sequence = " + sequence + " told me to eat an object with ID " + entityID, "AGI Robot", OpenCog.Utility.Console.Console.ConsoleEntry.Type.SAY);
								
							}	

							OCGoalController goalController = _actionController.gameObject.GetComponent<OCGoalController>();
							goalController.BlockType = "Battery";
							goalController.FindGoalBlockPositionInChunks(_map.Chunks);
						} else
						{
							// That's silly..we can only eat / grab batteries!
							UnityEngine.Debug.Log("Received a grab or eat command, but couldn't find the battery in Unity!");
						}
						
							
					} 
					// if (actionName == "grab" || actionName == "eat"
//						else
//						{
//							// I'll bet the section below does nothing. Go home 
////							UnityEngine.GameObject[] hearthArray = UnityEngine.GameObject.FindGameObjectsWithTag("OCHearth");
////					
////							for (int iHearth = 0; iHearth < hearthArray.Length; iHearth++)
////							{
////								UnityEngine.GameObject hearthObject = hearthArray[iHearth];
////								
////								if (entityID == hearthObject.GetInstanceID())
////								{
////									// This is the one!	
////									actionArguments.EndTarget = hearthObject;
////									
////									break;
////								}
////							}	
//						}

					break;
				case "string":
//						XmlNodeList stringParameterChildren = actionParameterElement.GetElementsByTagName(OCEmbodimentXMLTags.VECTOR_ELEMENT);
//						XmlElement stringElement = (XmlElement)stringParameterChildren.Item (0);
					
					if(actionName == "say")
					{
						string toSay = actionParameterElement.GetAttribute(OCEmbodimentXMLTags.VALUE_ATTRIBUTE);
						
						if(toSay != string.Empty)
						{
							UnityEngine.Debug.Log("Robot say: " + toSay + "(actionPlan = " + _currentPlanId + ", sequence = " + sequence);
												
							console.AddConsoleEntry(toSay, "AGI Robot", OpenCog.Utility.Console.Console.ConsoleEntry.Type.SAY);
						}

						// We need to set the target to the avatar I guess....
						UnityEngine.GameObject[] agiArray = UnityEngine.GameObject.FindGameObjectsWithTag("OCAGI");
						
						for(int iAGI = 0; iAGI < agiArray.Length; iAGI++)
						{
							UnityEngine.GameObject agiObject = agiArray[iAGI];
							
							endPointStub.transform.position = agiObject.transform.position;
							
							actionArguments.EndTarget = endPointStub;
						}
					}

					
					break;

				} // end switch actionParameterType
			} // end foreach actionParameterNode
			
			if(_actionController == null)
			{
				_actionController = GameObject.FindGameObjectWithTag("OCAGI").GetComponent<OCActionController>();
			}
			
			actionArguments.ActionName = actionName;
			actionArguments.ActionPlanID = _currentPlanId;
			actionArguments.SequenceID = sequence;
			actionArguments.Source = UnityEngine.GameObject.FindGameObjectWithTag("OCAGI");
			//actionArguments.Source.transform.SetY(actionArguments.Source.transform.position.y - 0.5f);
			
			// Lake's function here.
			if(actionName != "say")
			{
				_actionController.LoadActionPlanStep(actionName, actionArguments);
			}
			
			// Just for fun, I'm going to send success for everything for a while.
			
			//this.SendActionStatus(_currentPlanId, sequence, actionName, true);
			
			//actionPlan.Add((XmlElement)node);
		} // end foreach actionPlanElement 
		
		// And again for fun, send a whole action plan successful message:
		//this.SendActionPlanStatus(_currentPlanId, true);
				
		// Start to perform an action in front of the action list.
		//_actionController.ReceiveActionPlan(actionPlan);// SendMessage("receiveActionPlan", actionPlan);
		//processNextAvatarAction();
	}
	//---------------------------------------------------------------------------

	#endregion

	//---------------------------------------------------------------------------

	#region Public Member Functions

	//---------------------------------------------------------------------------

	public void Start()
	{
		_AnimationEffects = 
			gameObject.GetComponentsInChildren<OCAnimationEffect>().ToList();

		_CreateBlockEffects =
			gameObject.GetComponentsInChildren<OCCreateBlockEffect>().ToList();

		_DestroyBlockEffects =
			gameObject.GetComponentsInChildren<OCDestroyBlockEffect>().ToList();

		_TransferBlockEffects =
			gameObject.GetComponentsInChildren<OCTransferBlockEffect>().ToList();

		_Map = OCMap.Instance;//(OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).LastOrDefault();

		_ActionController = _Source.GetComponent<OCActionController>();

//		foreach(OCDelegate del in _Preconditions)
//		{
//			PreCondition += (OCActionCondition)del.Delegate;
//		}
//
//		foreach(OCDelegate del in _Invariants)
//		{
//			InvariantCondition += (OCActionCondition)del.Delegate;
//		}
//
//		foreach(OCDelegate del in _Postconditions)
//		{
//			PostCondition += (OCActionCondition)del.Delegate;
//		}

		foreach(string condition in _Preconditions)
		{
			PreCondition += (OCActionCondition)Delegate.CreateDelegate(typeof(OCActionCondition), typeof(OCAction).GetMethod(condition));
		}

		foreach(string condition in _Invariants)
		{
			InvariantCondition += (OCActionCondition)Delegate.CreateDelegate(typeof(OCActionCondition), typeof(OCAction).GetMethod(condition));
		}

		foreach(string condition in _Postconditions)
		{
			PostCondition += (OCActionCondition)Delegate.CreateDelegate(typeof(OCActionCondition), typeof(OCAction).GetMethod(condition));
		}

//		PreCondition += IsEndTarget;
//		InvariantCondition += IsSourceAnimating;
//		InvariantCondition += IsSourceNotRunningOtherActionsIgnoreIdle;
//		PostCondition += IsSourceRunningOtherActionsIgnoreIdle;
				
//		if(_EndTarget == null)
//			_EndTarget = GameObject.Find("EndPointStub");
//		if(_StartTarget == null)
//			_StartTarget = GameObject.Find("StartPointStub");
				
		DontDestroyOnLoad(this);
	}
        private IEnumerator LoadAgent(string agentName)
        {
            UnityEngine.GameObject agentClone;

            UnityEngine.GameObject playerObject = GameObject.FindGameObjectWithTag("Player");
            if (playerObject == null)
            {
                Debug.Log("No object tagged with player.");
                yield return("No object tagged with player.");
            }

            // Record the player's position and make the OCAvatar spawn near it.
            UnityEngine.Vector3 playerPos = playerObject.transform.position;

            //Debug.Log ("PlayerPos = [" + playerPos.x + ", " + playerPos.y + ", " + playerPos.z + "]");

            // Calculate the player's forward direction
            UnityEngine.Vector3 eulerAngle = playerObject.transform.rotation.eulerAngles;

            //Debug.Log ("eulerAngle = [" + eulerAngle.x + ", " + eulerAngle.y + ", " + eulerAngle.z + "]");

            float zFront = 3.0f * (float)Math.Cos((eulerAngle.y / 180) * Math.PI);
            float xFront = 3.0f * (float)Math.Sin((eulerAngle.y / 180) * Math.PI);

            UnityEngine.Vector3 spawnPosition = new UnityEngine.Vector3(playerPos.x + xFront, playerPos.y + 2, playerPos.z + zFront);
            spawnPosition.x = (float)((int)spawnPosition.x);
            spawnPosition.y = (float)((int)spawnPosition.y);
            spawnPosition.z = (float)((int)spawnPosition.z);

            //Debug.Log ("spawnPosition = [" + spawnPosition.x + ", " + spawnPosition.y + ", " + spawnPosition.z + "]");

            // Instantiate an OCAvatar in front of the player.

            //Debug.Log ("_NPCAgent is" + (_NPCAgent == null ? " null " : " not null"));

            agentClone = (GameObject)UnityEngine.Object.Instantiate(_NPCAgent, spawnPosition, Quaternion.identity);
            agentClone.transform.parent = GameObject.Find("Characters").transform;
            OCActionController agiAC = agiAC = agentClone.GetComponent <OCActionController>();

            agiAC.DefaultEndTarget   = GameObject.Find("EndPointStub");
            agiAC.DefaultStartTarget = GameObject.Find("StartPointStub");

            //Debug.Log ("agentClone is" + (agentClone == null ? " null " : " not null"));

            OCConnectorSingleton connector = OCConnectorSingleton.Instance;

            UnityEngine.Debug.Log("The GUID of our OCC instance in LoadAgent is " + connector.VerificationGuid);

            //Debug.Log ("connector is" + (connector == null ? " null " : " not null"));

            if (agentName == "")
            {
                agentName = CreateRandomAgentName();
            }

            //Debug.Log("We shall name him '" + agentName + "'");

            agentClone.name = agentName;

//			if (agentClone != null) {
//				if (!OCARepository.AddOCA (agentClone)) {
//					// An avatar with given name is already there.
//					yield break;
//				}
//				Debug.Log ("Add avatar[" + agentName + "] to avatar map.");
//			}

            // Get the player id as the master id of the avatar.
            // TODO Currently we use the tag "player". However, when there are multiple
            // players in the world, we need to figure out a way to identify.
            string masterId   = playerObject.GetInstanceID().ToString();
            string masterName = playerObject.name;

            // TODO Set agentType and agentTraits in the future.
            // leave agentType and agentTraits to null just for test.
            connector.Init(agentName, null, null, masterId, masterName);

            yield return(StartCoroutine(connector.ConnectOAC()));

            if (!connector.IsInitialized)
            {
                // OAC is not loaded normally, destroy the avatar instance.
                Debug.LogError("Cannot connect to the OAC, avatar loading failed.");
                connector.SaveAndExit();
                Destroy(agentClone);
                yield break;
            }
        }
        public override string Run(ArrayList arguments)
        {
            //if (arguments.Count != 2) return "Wrong number of arguments";
            string sourceName    = (string)arguments [0];
            string targetName    = (string)arguments [1];         //also targetStartName
            string actionName    = (string)arguments [2];
            string targetEndName = (string)arguments [3];

            // Get the appropriate agent and gameobject
            OCActionController actionController =
                GameObject.FindSceneObjectsOfType(typeof(OCActionController))
                .Where(ac => (ac as OCActionController).gameObject.name == sourceName)
                .Cast <OCActionController>()
                .FirstOrDefault()
            ;

            if (actionController == null)
            {
                return("No Action Controller script on agent \"" + sourceName + "\".");
            }
            if (actionController.gameObject.tag == "Player")
            {
                return("Agent \"" + sourceName + "\" is controlled by the player!");
            }

            OCID sourceID = actionController.ID;

            // Get the object
            // if objectName is "self" then assume the script is on the agent
            OCID targetStartID;

            if (targetName != null && targetName != "self")
            {
                GameObject target = GameObject.Find(targetName);
                if (target == null)
                {
                    return("No object called " + targetName);
                }
                targetStartID = target.GetComponent <OCActionController>().ID;
            }
            else
            {
                targetStartID = actionController.ID;
            }

            OCID targetEndID;

            if (targetEndName != null && targetEndName != "self")
            {
                GameObject targetEnd = GameObject.Find(targetEndName);
                if (targetEnd == null)
                {
                    return("No object called " + targetEndName);
                }
                targetEndID = targetEnd.GetComponent <OCActionController>().ID;
            }
            else
            {
                targetEndID = actionController.ID;
            }

            // Get the action from the Action Controller
            OCAction action =
                actionController.GetComponentsInChildren <OCAction>()
                .Where(a => a.name == actionName)
                .Cast <OCAction>()
                .FirstOrDefault()
            ;

            if (action == null)
            {
                return("No action called \"" + actionName + "\".");
            }

            actionController.StartAction(action, sourceID, targetStartID, targetEndID);

//			System.Reflection.ParameterInfo[] pinfo = action.pinfo; //getFreeArguments();
//
//			if (pinfo.Length > 0) {
//				ArrayList args = new ArrayList ();
//				int i = 0;
//				int jmod = 3;
//				if (action.componentType == typeof(Avatar)) {
//					// Check we don't have too many arguments
//					if (pinfo.Length < arguments.Count - 3)
//						return "Expected " + pinfo.Length + " arguments, got " + (arguments.Count - 3) + ".";
//				} else {
//					// Check we don't have too many arguments, we don't need to
//					// provide the avatar
//					if (pinfo.Length - 1 < arguments.Count - 3)
//						return "Expected " + (pinfo.Length - 1) + " arguments, got " + (arguments.Count - 3) + ".";
//					i = 1;
//					jmod = 2;
//				}
//				// ignore last parameter if action uses a callback
//				int lengthModififer = 0;
//				if (action.usesCallback)
//					lengthModififer = 1;
//				for (; i < pinfo.Length-lengthModififer; i++) {
//					// do type checking and conversion from strings to the expected type
//					// ignore 3 console arguments: the action name, avatar name,
//					//    and the object with the action (from console arguments)
//					int j = i + jmod;
//					if (j >= arguments.Count) {
//						// Not enough arguments, so must be a default argument
//						if (!pinfo [i].IsOptional)
//							return "Missing parameter " + pinfo [i].Name + " is not optional.";
//						args.Add (pinfo [i].DefaultValue);
//					} else {
//						arguments [j] = ((string)arguments [j]).Replace ("\"", "");
//						// Depending on the expected type we convert it differently
//						if (pinfo [i].ParameterType == typeof(GameObject)) {
//							// Parameters that are gameobjects... we just search for
//							// the name.
//							args.Add (GameObject.Find ((string)arguments [j]));
//							if (((GameObject)args [i]) == null) {
//								return "No game object called \"" + (string)arguments [j] + "\".";
//							}
//						} else if (pinfo [i].ParameterType == typeof(Avatar)) {
//							// Parameters that are Avatars... we just search for
//							// the name.
//							args.Add (OCARepository.GetOCA ((string)arguments [j]).GetComponent ("Avatar") as Avatar);
//							if ((Avatar)args [i] == null) {
//								return "No Avatar called \"" + (string)arguments [j] + "\".";
//							}
//						} else if (pinfo [i].ParameterType == typeof(int)) {
//							try {
//								args.Add (System.Int32.Parse ((string)arguments [j]));
//							} catch (System.FormatException ex) {
//								return "Error parsing string as int32: " + (string)arguments [j];
//							}
//						} else if (pinfo [i].ParameterType == typeof(float)) {
//							try {
//								args.Add (float.Parse ((string)arguments [j]));
//							} catch (System.FormatException ex) {
//								return "Error parsing string as float: " + (string)arguments [j];
//							}
//						} else if (pinfo [i].ParameterType == typeof(string)) {
//							args.Add ((string)arguments [j]);
//						} else {
//							return "Method " + actionName + " at slot " + i + " has argument of unsupported type \"" + pinfo [i].ParameterType +
//                            "\". Ask Joel how to implement support or ask him nicely to do it ;-).";
//						}
//					}
//				}
//				// even if this action supports callbacks, we don't pass our actionComplete callback because
//				// it's already called by the global event (which the Console class listens for).
//				AM.doAction (actionObjectID, actionName, args);
//			}

            return("Told avatar \"" + sourceName + "\" to do action \"" + actionName + "\"");
        }
Example #8
0
            //DEPRECATED: This was useful once;
            //if (!OCARepository.AddOCA (agentClone)) {

            // Note, lambda expressions (ie myLamb = (x) => successBool = (bool)(x == "true")) are *terrifying* to look at
            // and can use up a lot of memory, but they're really good for returning values from IEnumerators/coroutines;
            // especially ones we don't expect will be called frquently

            /// <summary>
            /// Allows entities to be loaded to the screen at any point while the game is running
            /// </summary>
            /// <returns>Failure, success, or a coroutine concerned with making a connection to the embodiment.</returns>
            /// <param name="spawnPosition">The position at which to instantiate the agent.</param>
            /// <param name="agentPrefab">The prefab to instantiate.</param>
            /// <param name="agentName">The name of the agent to instantiate.</param>
            /// <param name="masterName">The owner of the instance</param>
            /// <param name="masterId">The id of the instance</param>
            /// <param name="report">An Action that can be constructed easily with a lambda expression which will report back the string "true" if it successfully
            ///  created the agent and the string "false" if it was unsuccessful in creating the agent.</param>
            public IEnumerator AtRunTime(UnityEngine.Vector3 spawnPosition, GameObject agentPrefab, string agentName = "", string masterName = "", string masterId = "",
                                         System.Action <string> report = null)             //The lambda expression enter-er gets its own line, because it's SCARY!
            {
                //get the spawn position in terms of the grid
                spawnPosition.x = (float)((int)spawnPosition.x);
                spawnPosition.y = (float)((int)spawnPosition.y);
                spawnPosition.z = (float)((int)spawnPosition.z);

                //Debug.Log ("_NPCAgent is" + (_NPCAgent == null ? " null " : " not null"));

                //instantiate the game object, specified by NPCAgent at  point spawn position and rotated as per the identity Quaternion (that is, not at all)
                UnityEngine.GameObject agentClone = (GameObject)UnityEngine.Object.Instantiate(agentPrefab, spawnPosition, Quaternion.identity);

                //All agents belong to the Characters parent game object.
                agentClone.transform.parent = GameObject.Find("Characters").transform;

                //the _NPCAgent should have come with an OCActionController
                OCActionController agiAC = agentClone.GetComponent <OCActionController>();

                //
                agiAC.DefaultEndTarget   = GameObject.Find("EndPointStub");
                agiAC.DefaultStartTarget = GameObject.Find("StartPointStub");

                //Debug.Log ("agentClone is" + (agentClone == null ? " null " : " not null"));

                OCConnectorSingleton connector = OCConnectorSingleton.Instance;

                //Debug.Log ("connector is" + (connector == null ? " null " : " not null"));

                //Ensure our agent is properly named
                if (agentName == "")
                {
                    agentName = CreateRandomAgentName();
                }
                agentClone.name = agentName;


                //initialize the connector
                connector.InitAvatar(agentName, null, null, masterId, masterName);

                //and try to connect
                yield return(StartCoroutine(connector.ConnectOAC()));

                //if we failed to initialize the connector
                if (!connector.IsInitialized)
                {
                    // OAC is not loaded normally, destroy the avatar instance.
                    Debug.LogError(OCLogSymbol.ERROR + "Could not connect to Embodiment");
                    System.Console.WriteLine(OCLogSymbol.DETAILEDINFO + "LoadMethods.AtRunTime is reporting !connector.Initialize. Cannot connect to the OAC, avatar loading failed.");
                    connector.SaveAndExit();
                    Destroy(agentClone);

                    if (report != null)
                    {
                        report("false");
                    }
                }
                else
                {
                    Debug.Log(OCLogSymbol.CLEARED + "LoadMethods.AtRunTime is reporting connector.Initialized");
                    if (report != null)
                    {
                        report("true");
                    }
                }

                yield break;
            }