Esempio n. 1
0
 public MainForm()
 {
     InitializeComponent();
     string[] args = Environment.GetCommandLineArgs();
     if (args.Length <= 1)
     {
         Reset(true);
     }
     else
     {
         _saveFileName = args[1];
         try
         {
             _rpcAsset = RolePlayCharacterAsset.LoadFromFile((args[1]));
             if (_rpcAsset.ErrorOnLoad != null)
             {
                 MessageBox.Show(_rpcAsset.ErrorOnLoad, Resources.ErrorDialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             Reset(false);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, Resources.ErrorDialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
             Reset(true);
         }
     }
 }
Esempio n. 2
0
        private void buttonCreateCharacter_Click(object sender, EventArgs e)
        {
            _rpcForm = new RolePlayCharacterWF.MainForm();
            var asset = _rpcForm.CreateAndSaveEmptyAsset(false);

            if (asset == null)
            {
                return;
            }

            var rpcAsset = RolePlayCharacterAsset.LoadFromFile(asset.AssetFilePath);

            FormHelper.ShowFormInContainerControl(this.tabControlIAT.TabPages[1], _rpcForm);
            this.tabControlIAT.SelectTab(1);
            this.currentRPCTabIndex = 1;
            _rpcForm.LoadedAsset    = rpcAsset;

            LoadedAsset.AddNewCharacterSource(new CharacterSourceDTO()
            {
                Source = asset.AssetFilePath
            });
            _characterSources.DataSource = LoadedAsset.GetAllCharacterSources().ToList();
            _characterSources.Refresh();
            SetModified();
        }
        public static IntegratedAuthoringToolAsset LoadFromFile(string filename)
        {
            IntegratedAuthoringToolAsset iat;

            using (var f = File.Open(filename, FileMode.Open, FileAccess.Read))
            {
                var serializer = new JSONSerializer();
                iat = serializer.Deserialize <IntegratedAuthoringToolAsset>(f);
            }

            iat.Characters = new List <RolePlayCharacterAsset>();
            try
            {
                foreach (var source in iat.CharacterSources)
                {
                    iat.CurrentRpcSource = source;
                    var character = RolePlayCharacterAsset.LoadFromFile(source.Source);
                    iat.Characters.Add(character);
                }
            }
            catch (Exception ex)
            {
                iat.ErrorOnLoad = "An error occured when trying to load the RPC " + iat.CurrentRpcSource.Name + " at " + iat.CurrentRpcSource.Source + ". Please check if the path is correct.";
                return(iat);
            }


            return(iat);
        }
Esempio n. 4
0
        /// <summary>
        /// Adds a new role-play character asset to the scenario.
        /// </summary>
        /// <param name="character">The instance of the Role Play Character asset</param>
        public void AddNewCharacterSource(CharacterSourceDTO dto)
        {
            string errorsOnLoad;
            var    asset = RolePlayCharacterAsset.LoadFromFile(dto.Source, out errorsOnLoad);

            if (errorsOnLoad != null)
            {
                throw new Exception(errorsOnLoad);
            }
            dto.Id     = m_characterSources.Count;
            dto.Source = ToRelativePath(dto.Source);
            m_characterSources.Add(dto);
        }
 private void ChooseCharacterMenu(SingleCharacterDemo.ScenarioData data)
 {
     ClearButtons();
     foreach (var agent in data.IAT.GetAllCharacterSources())
     {
         var rpc = RolePlayCharacterAsset.LoadFromFile(agent.Source);
         AddButton(rpc.CharacterName.ToString(), () =>
         {
             _chosenCharacter = rpc.CharacterName;
             LoadScenario(data);
         });
     }
 }
Esempio n. 6
0
    // Use this for initialization
    private void Start()
    {
        AssetManager.Instance.Bridge = new AssetManagerBridge();

        var streamingAssetsPath = Application.streamingAssetsPath;

#if UNITY_EDITOR || UNITY_STANDALONE
        streamingAssetsPath = "file://" + streamingAssetsPath;
#endif
        if (string.IsNullOrEmpty(IATScenario))
        {
            Debug.LogError("Please specify an IAT scenario file!");
            return;
        }

        iat = IntegratedAuthoringToolAsset.LoadFromFile(IATScenario);
        var characterSources = iat.GetAllCharacterSources().ToList();

        //AGENT 1
        agent1RPC = RolePlayCharacterAsset.LoadFromFile(characterSources[1].Source);
        agent1RPC.LoadAssociatedAssets();
        iat.BindToRegistry(agent1RPC.DynamicPropertiesRegistry);

        //AGENT 2
        agent2RPC = RolePlayCharacterAsset.LoadFromFile(characterSources[2].Source);
        agent2RPC.LoadAssociatedAssets();
        iat.BindToRegistry(agent2RPC.DynamicPropertiesRegistry);

        //PLAYER
        playerRPC = RolePlayCharacterAsset.LoadFromFile(characterSources[0].Source);
        playerRPC.LoadAssociatedAssets();
        iat.BindToRegistry(playerRPC.DynamicPropertiesRegistry);

        playerDialogues = DeterminePlayerDialogues();
        UpdatePlayerDialogOptions(true);

        AgentUtterance.text = String.Empty;

        StartCoroutine(UpdateEmotionalState(1f));
        StartCoroutine(DetermineAgentDialogue(0.2f));

        NextPageButton.onClick.RemoveAllListeners();
        NextPageButton.onClick.AddListener(() => OnNextPage());

        PreviousPageButton.onClick.RemoveAllListeners();
        PreviousPageButton.onClick.AddListener(() => OnPreviousPage());

        RestartButton.onClick.RemoveAllListeners();
        RestartButton.onClick.AddListener(() => RestartScene());
    }
Esempio n. 7
0
        internal ConfigStore(Platform platform = Platform.Windows)
        {
            Platform     = platform;
            ConfigValues = new Dictionary <ConfigKey, float>();
            var configText       = Templates.ResourceManager.GetString("config");
            var contractResolver = new PrivatePropertyResolver();
            var settings         = new JsonSerializerSettings
            {
                ContractResolver = contractResolver
            };

            ConfigValues = JsonConvert.DeserializeObject <Dictionary <ConfigKey, float> >(configText, settings);
            foreach (var key in (ConfigKey[])Enum.GetValues(typeof(ConfigKey)))
            {
                if (!ConfigValues.ContainsKey(key))
                {
                    throw new Exception("Config key " + key + " not included in config!");
                }
            }
            BoatTypes = new Dictionary <string, List <Position> >();
            var boatText = Templates.ResourceManager.GetString("boat_config");

            BoatTypes     = JsonConvert.DeserializeObject <Dictionary <string, List <Position> > >(boatText);
            GameConfig    = new GameConfig().GetConfig();
            NameConfig    = new NameConfig().GetConfig();
            Avatar.Config = new AvatarGeneratorConfig().GetConfig();

            AssetManager.Instance.Bridge = new TemplateBridge();
            RolePlayCharacter            = RolePlayCharacterAsset.LoadFromFile("template_rpc");
            EmotionalAppraisal           = EmotionalAppraisalAsset.LoadFromFile("template_ea");
            EmotionalDecisionMaking      = EmotionalDecisionMakingAsset.LoadFromFile("template_edm");
            SocialImportance             = SocialImportanceAsset.LoadFromFile("template_si");
            IntegratedAuthoringTool      = IntegratedAuthoringToolAsset.LoadFromFile("template_iat");

            switch (Platform)
            {
            case Platform.Android:
                AssetManager.Instance.Bridge = new AndroidBaseBridge();
                break;

            case Platform.iOS:
                AssetManager.Instance.Bridge = new IOSBaseBridge();
                break;

            case Platform.Windows:
                AssetManager.Instance.Bridge = new BaseBridge();
                break;
            }
        }
    private void LoadScenario(SingleCharacterDemo.ScenarioData data)
    {
        ClearButtons();

        _iat = data.IAT;

        _introPanel.SetActive(true);
        _introText.text = string.Format("<b>{0}</b>\n\n\n{1}", _iat.ScenarioName, _iat.ScenarioDescription);


        var characterSources = _iat.GetAllCharacterSources().ToList();
        int CharacterCount   = 0;

        foreach (var source in characterSources)
        {
            var rpc = RolePlayCharacterAsset.LoadFromFile(source.Source);
            rpc.LoadAssociatedAssets();
            _iat.BindToRegistry(rpc.DynamicPropertiesRegistry);
            rpcList.Add(rpc);
            var body = m_bodies.FirstOrDefault(b => b.BodyName == rpc.BodyName);
            _agentController = new MultiCharacterAgentController(data, rpc, _iat, body.CharaterArchtype, m_characterAnchors[CharacterCount], m_dialogController);
            StopAllCoroutines();

            _agentControllers.Add(_agentController);
            CharacterCount++;
        }


        AddButton("Back to Scenario Selection Menu", () =>
        {
            _iat = null;
            LoadScenarioMenu();
        });

        foreach (var actor in rpcList)
        {
            foreach (var anotherActor in rpcList)
            {
                if (actor != anotherActor)
                {
                    var changed = new[] { EventHelper.ActionEnd(anotherActor.CharacterName.ToString(), "Enters", "Room") };
                    actor.Perceive(changed);
                }
            }
        }

        RandomizeNext();
        SetCamera();
    }
    private IEnumerator LoadScenario(ScenarioData data)
    {
        ClearButtons();

        _iat = data.IAT;

        _introPanel.SetActive(true);
        _introText.text = string.Format("<b>{0}</b>\n\n\n{1}", _iat.ScenarioName, _iat.ScenarioDescription);
        previousState   = "";
        var characterSources = _iat.GetAllCharacterSources().ToList();
        var addedDialogs     = new List <string>();

        _wm = WorldModelAsset.LoadFromFile(_iat.GetWorldModelSource().Source);
        foreach (var source in characterSources)
        {
            var rpc = RolePlayCharacterAsset.LoadFromFile(source.Source);
            rpc.LoadAssociatedAssets();
            if (rpc.CharacterName.ToString() == "Player")
            {
                Player = rpc;
                _iat.BindToRegistry(Player.DynamicPropertiesRegistry);
                continue;
            }
            _iat.BindToRegistry(rpc.DynamicPropertiesRegistry);
            AddButton(characterSources.Count <= 2 ? "Start" : rpc.CharacterName.ToString(),
                      () =>
            {
                Debug.Log("Interacted with the start button");
                var body         = m_bodies.FirstOrDefault(b => b.BodyName == rpc.BodyName);
                _agentController = new AgentControler(data, rpc, _iat, body.CharaterArchtype, m_characterAnchor, m_dialogController);
                StopAllCoroutines();
                _agentController.storeFinalScore(_finalScore);
                _agentController.Start(this, VersionMenu);
                _agentController.startingTime = this.startingTime;

                InstantiateScore();
            });
        }
        if (m_scenarios.Length > 1)
        {
            AddButton("Back to Scenario Selection Menu", () =>
            {
                _iat = null;
                LoadScenarioMenu();
            });
        }
        yield return(nextframe);
    }
Esempio n. 10
0
        static void Main(string[] args)
        {
            //Loading the asset
            var rpc = RolePlayCharacterAsset.LoadFromFile("../../../Examples/MCTS-Tutorial/RPC-MCTS.rpc");

            rpc.LoadAssociatedAssets();
            Console.WriteLine("Starting Mood: " + rpc.Mood);
            var actions = rpc.Decide();
            var action  = actions.FirstOrDefault();

            foreach (var a in actions)
            {
                Console.WriteLine(a.Name.ToString() + " p: " + a.Utility);
            }
            Console.ReadKey();
        }
        public RolePlayCharacterAsset AddCharacter(string filename)
        {
            var character = RolePlayCharacterAsset.LoadFromFile(filename);

            if (this.Characters.Any(c => c.CharacterName == character.CharacterName))
            {
                throw new Exception("A character with the same name already exists.");
            }

            this.Characters.Add(character);
            this.CharacterSources.Add(new CharacterSourceDTO {
                Name = character.CharacterName, Source = filename
            });

            return(character);
        }
Esempio n. 12
0
    public void NextLevel()
    {
        CurrentLevel++;

        _feedbackScores.Clear();
        GetFeedbackEvent?.Invoke(_feedbackScores, FeedbackLevel);
        if (_scenarios.Any(data => data.LevelId.Equals(CurrentLevel)))
        {
            CurrentScenario = _scenarios.First(data => data.LevelId.Equals(CurrentLevel));
        }
        else
        {
            var validPaths = _allScenarioPaths.Where(p => p.Contains('#')).ToArray();
            var prefixes = validPaths.Select(p => p.Substring(0, p.IndexOf('-', p.IndexOf('-') + 1) + 1)).ToList();
            var character = new List <string> {
                "Positive", "Neutral", "Negative"
            }.OrderBy(dto => random.Next()).First();

            var prefix = _isDemo
                                ? _demoScenarioPrefix + _demoUtterance
                                : prefixes.OrderBy(dto => random.Next()).First();

            // MaxPoints currently hardcoded to 8 for random scenarios.
            // TODO Review validity/balance of MaxPoints = 8
            CurrentScenario = new ScenarioData(CurrentLevel, _allScenarioPaths.Where(x => x.Contains(prefix)).ToArray(), character, 8, prefix);
        }
        if (CurrentScenario != null)
        {
            var index = random.Next(CurrentScenario.ScenarioPaths.Length);
            Debug.Log(CurrentScenario.ScenarioPaths[index]);
            string error;

            ScenarioCode = _isDemo
                                ? _demoUtterance.Split('#')[0]
                                : CurrentScenario.ScenarioPaths[index].Replace(CurrentScenario.Prefix, string.Empty).Split('#')[0];

            _integratedAuthoringTool = IntegratedAuthoringToolAsset.LoadFromFile(Path.Combine("Scenarios", CurrentScenario.ScenarioPaths[index]), out error);
            if (!string.IsNullOrEmpty(error))
            {
                Debug.LogError(error);
            }
            CurrentCharacter = RolePlayCharacterAsset.LoadFromFile(_integratedAuthoringTool.GetAllCharacterSources().First(c => c.Source.Contains(CurrentScenario.Character)).Source);
            CurrentCharacter.LoadAssociatedAssets();
            _integratedAuthoringTool.BindToRegistry(CurrentCharacter.DynamicPropertiesRegistry);
            CurrentCharacter.BodyName = random.NextDouble() >= 0.5 ? "Male" : "Female";
        }
    }
Esempio n. 13
0
    public void NextQuestionnaire()
    {
        // Pilot logic to set level id to match CurrentLevel divided by 5, as questionnaires occur every 5 levels. Needs changing if occurance rate of questionnaires change
        CurrentScenario = new ScenarioData(CurrentLevel / 5, _allScenarioPaths.Where(x => x.Contains("Questions")).ToArray(), "Neutral", 0, "Questionnaire");
        string error;

        // Pilot logic to set different questionnaire depending on how many levels have been played. Needs changing if expected appearence of questionnaire changes
        ScenarioCode             = (CurrentLevel < LevelMax && LevelMax > 0 ? 1 : 2).ToString();
        _integratedAuthoringTool = IntegratedAuthoringToolAsset.LoadFromFile(Path.Combine("Scenarios", _allScenarioPaths.First(x => x.Contains("Questions" + ScenarioCode))), out error);
        if (!string.IsNullOrEmpty(error))
        {
            Debug.LogError(error);
        }
        CurrentCharacter = RolePlayCharacterAsset.LoadFromFile(_integratedAuthoringTool.GetAllCharacterSources().First(c => c.Source.Contains("Neutral")).Source);
        CurrentCharacter.LoadAssociatedAssets();
        _integratedAuthoringTool.BindToRegistry(CurrentCharacter.DynamicPropertiesRegistry);
    }
Esempio n. 14
0
        private void buttonTest_Click(object sender, System.EventArgs e)
        {
            var rpcAsset = RolePlayCharacterAsset.LoadFromFile(rpcSource);

            rpcAsset.LoadAssociatedAssets();
            iat.BindToRegistry(rpcAsset.DynamicPropertiesRegistry);

            string[] eventStrings = this.textBoxEvents.Text.Split(
                new[] { Environment.NewLine },
                StringSplitOptions.None).Select(s => s.Trim()).ToArray();

            foreach (var s in eventStrings)
            {
                if (string.IsNullOrWhiteSpace(s))
                {
                    continue;
                }

                if (s.StartsWith("-"))
                {
                    var count = s.Count(c => c == '-');
                    for (int i = 0; i < count; i++)
                    {
                        rpcAsset.Update();
                    }
                }
                else
                {
                    try
                    {
                        var evt = WellFormedNames.Name.BuildName(s);
                        AM.AssertEventNameValidity(evt);
                        rpcAsset.Perceive(evt);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            textBoxMood.Text    = rpcAsset.Mood.ToString();
            textBoxTick.Text    = rpcAsset.Tick.ToString();
            emotions.DataSource = rpcAsset.GetAllActiveEmotions().ToList();
            actions.DataSource  = rpcAsset.Decide(wfNameActionLayer.Value).ToList();
        }
Esempio n. 15
0
        private void dataGridViewCharacters_SelectionChanged(object sender, EventArgs e)
        {
            var rpcSource = EditorTools.GetSelectedDtoFromTable <CharacterSourceDTO>(dataGridViewCharacters);

            if (rpcSource != null)
            {
                var rpc            = RolePlayCharacterAsset.LoadFromFile(rpcSource.Source);
                var selectedRPCTab = _rpcForm.SelectedTab;
                _rpcForm.Close();
                _rpcForm             = new RolePlayCharacterWF.MainForm();
                _rpcForm.LoadedAsset = rpc;
                FormHelper.ShowFormInContainerControl(this.tabControlIAT.TabPages[1], _rpcForm);
                this.tabControlIAT.SelectTab(1);
                _rpcForm.SelectedTab          = selectedRPCTab;
                buttonRemoveCharacter.Enabled = true;
                buttonInspect.Enabled         = true;
            }
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            AssetManager.Instance.Bridge = new BasicIOBridge();

            Console.Write("Loading Character from file... ");
            Walter = RolePlayCharacterAsset.LoadFromFile("./walter.rpc");
            Walter.LoadAssociatedAssets();
            Console.WriteLine("Complete!");

            WebServer ws = new WebServer(SendResponse, "http://localhost:8080/");

            ws.Run();
            Console.WriteLine("Press a key to quit.");
            Console.ReadKey();
            ws.Stop();

            Walter.SaveToFile("./walter-final.rpc");
        }
Esempio n. 17
0
        private void loadScenario(string agentType)
        {
            System.IO.Directory.CreateDirectory(LOGS_PATH);

            var characterSources = _iat.GetAllCharacterSources().ToList();

            foreach (var source in characterSources)
            {
                RolePlayCharacterAsset character = RolePlayCharacterAsset.LoadFromFile(source.Source);
                character.LoadAssociatedAssets();
                if (character.BodyName.ToString() == agentType)
                {
                    _iat.BindToRegistry(character.DynamicPropertiesRegistry);
                    _rpc = character;
                    break;
                }
            }
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            var iat = IntegratedAuthoringToolAsset.LoadFromFile("../../../Examples/CiF-Tutorial/JobInterview.iat");

            rpcList = new List <RolePlayCharacterAsset>();

            foreach (var source in iat.GetAllCharacterSources())
            {
                var rpc = RolePlayCharacterAsset.LoadFromFile(source.Source);


                //rpc.DynamicPropertiesRegistry.RegistDynamicProperty(Name.BuildName("Volition"),cif.VolitionPropertyCalculator);
                rpc.LoadAssociatedAssets();

                iat.BindToRegistry(rpc.DynamicPropertiesRegistry);

                rpcList.Add(rpc);
            }


            foreach (var actor in rpcList)
            {
                foreach (var anotherActor in rpcList)
                {
                    if (actor != anotherActor)
                    {
                        var changed = new[] { EventHelper.ActionEnd(anotherActor.CharacterName.ToString(), "Enters", "Room") };
                        actor.Perceive(changed);
                    }
                }
            }


            foreach (var actor in rpcList)
            {
                if (actor.Decide().FirstOrDefault() != null)
                {
                    Console.WriteLine(actor.CharacterName.ToString() + " decided to perform  " + actor.Decide().FirstOrDefault().Name);
                }
            }


            Console.ReadKey();
        }
Esempio n. 19
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    _rpcAsset     = RolePlayCharacterAsset.LoadFromFile(ofd.FileName);
                    _saveFileName = ofd.FileName;
                    if (_rpcAsset.ErrorOnLoad != null)
                    {
                        MessageBox.Show(_rpcAsset.ErrorOnLoad, Resources.ErrorDialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    Reset(false);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "-" + ex.StackTrace, Resources.ErrorDialogTitle, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }
            }
        }
    private void ChooseCharacterMenu(SingleCharacterDemo.ScenarioData data)
    {
        ClearButtons();

        if (skipCharacterSelection)
        {
            var rpc = RolePlayCharacterAsset.LoadFromFile(data.IAT.GetAllCharacterSources().FirstOrDefault().Source);
            _player = rpc;
            LoadScenario(data);
        }

        else
        {
            foreach (var agent in data.IAT.GetAllCharacterSources())
            {
                var rpc = RolePlayCharacterAsset.LoadFromFile(agent.Source);
                AddButton(rpc.CharacterName.ToString(), () =>
                {
                    _player = rpc;
                    LoadScenario(data);
                });
            }
        }
    }
Esempio n. 21
0
    void Start()
    {
        isStopped = false;

        string rpcPath = GameGlobals.FAtiMAIat.GetAllCharacterSources().FirstOrDefault().Source;

        //Application.ExternalEval("console.log(\"rpcPath: " + rpcPath + "\")");
        rpc = RolePlayCharacterAsset.LoadFromFile(rpcPath);


        rpc.LoadAssociatedAssets();
        GameGlobals.FAtiMAIat.BindToRegistry(rpc.DynamicPropertiesRegistry);

        //start update thread
        StartCoroutine(UpdateCoroutine());

        speechBalloonDelayPerWordInSeconds = 0.5f;
        currSpeeches = new List <string>();


        float speechCheckDelayInSeconds = 0.1f;

        StartCoroutine(ConsumeSpeeches(speechCheckDelayInSeconds));
    }
Esempio n. 22
0
        static void Main(string[] args)
        {
            // A lock to proccess requests non concurrently
            // FAtiMA-Toolkit is not thread safe
            Object l = new Object();

            AssetManager.Instance.Bridge = new BasicIOBridge();

            // FAtiMA stuff
            IntegratedAuthoringToolAsset IAT;
            Dictionary <string, RolePlayCharacterAsset> RPCs = new Dictionary <string, RolePlayCharacterAsset>();

            // Ensure that the save directory exists
            Directory.CreateDirectory("Saved Characters");

            // Loading the Scenario
            // Need to use fullpaths for everything due to FAtiMA's handling of paths
            Console.Write("Loading Scenario...");
            IAT = IntegratedAuthoringToolAsset.LoadFromFile(Path.GetFullPath("Example Character\\FAtiMA-DST.iat"));
            Console.WriteLine(" Done");

            WebServer ws = new WebServer(
                (HttpListenerRequest request) =>
            {
                lock (l)
                {
                    Char[] delimiters = { '/' };
                    String[] splitted = request.RawUrl.Split(delimiters);

                    if (splitted.Length < 3)
                    {
                        throw new Exception("Invalid number of arguments for the request.");
                    }

                    RolePlayCharacterAsset RPC;

                    // Check if the referenced RPC already exists (either loaded or saved) and create or load it
                    if (!RPCs.ContainsKey(splitted[1]))
                    {
                        try
                        {
                            // Try and load it from a saved file
                            string s = Path.GetFullPath("Saved Characters\\" + splitted[1] + ".rpc");
                            Console.Write("Loading from saved file... ");

                            RPC = RolePlayCharacterAsset.LoadFromFile(s);
                            RPC.LoadAssociatedAssets();
                            // Bind ValidDialogue dynamic property to RPC
                            IAT.BindToRegistry(RPC.DynamicPropertiesRegistry);

                            RPCs.Add(splitted[1], RPC);
                            Console.WriteLine("Done");
                        }
                        catch
                        {
                            // If it fails we need to load it from the default RPC in the scenario
                            string s = IAT.GetAllCharacterSources().FirstOrDefault().Source;
                            Console.Write("No save file found, loading from default character... ");

                            RPC = RolePlayCharacterAsset.LoadFromFile(s);
                            RPC.LoadAssociatedAssets();
                            // Bind ValidDialogue dynamic property to RPC
                            IAT.BindToRegistry(RPC.DynamicPropertiesRegistry);

                            RPCs.Add(splitted[1], RPC);
                            Console.WriteLine("Done");
                        }
                    }
                    else
                    {
                        // The RPC should exist (already checked)
                        // If we get an error it should stop processing the request with the error
                        // So there is no handling for the ArgumentNullException
                        RPCs.TryGetValue(splitted[1], out RPC);
                    }


                    // Process the request
                    switch (splitted[2])
                    {
                    case "perceptions":
                        if (request.HasEntityBody)
                        {
                            using (System.IO.Stream body = request.InputStream)             // here we have data
                            {
                                using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding))
                                {
                                    string e = reader.ReadToEnd();
                                    var p    = JsonConvert.DeserializeObject <Perceptions>(e);
                                    p.UpdatePerceptions(RPC);
                                    return(JsonConvert.True);
                                }
                            }
                        }
                        return(JsonConvert.Null);

                    case "decide":
                        // If there is a layer for the decision, use it
                        IEnumerable <ActionLibrary.IAction> decision;
                        if (splitted.Count() > 3 && splitted[3] != "")
                        {
                            decision = RPC.Decide((Name)splitted[3]);
                        }
                        else
                        {
                            decision = RPC.Decide();
                        }

                        if (decision.Count() < 1)
                        {
                            return(JsonConvert.Null);
                        }

                        Action action = Action.ToAction(decision.First(), IAT);

                        string t = decision.Count().ToString() + ": ";
                        foreach (ActionLibrary.IAction a in decision)
                        {
                            t += a.Name + " = (" + a.Target + ", " + a.Utility + "); ";
                        }
                        Debug.WriteLine(t);

                        return(JsonConvert.SerializeObject(action));

                    case "events":
                        if (request.HasEntityBody)
                        {
                            using (System.IO.Stream body = request.InputStream)             // here we have data
                            {
                                using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding))
                                {
                                    string s = reader.ReadToEnd();
                                    var e    = JsonConvert.DeserializeObject <Event>(s);
                                    e.Perceive(RPC);
                                    return(JsonConvert.True);
                                }
                            }
                        }
                        return(JsonConvert.Null);

                    default:
                        return(JsonConvert.Null);
                    }
                }
            }
                , "http://localhost:8080/");

            ws.Run();
            Console.WriteLine("Press a key to stop the server and save currently loaded characters.");
            Console.ReadKey();
            Console.WriteLine("Stopping Server...");
            ws.Stop();

            Console.Write("Saving Characters to files... ");
            foreach (KeyValuePair <string, RolePlayCharacterAsset> pair in RPCs)
            {
                pair.Value.SaveToFile(Path.GetFullPath("Saved Characters\\" + pair.Key + ".rpc"));
            }
            Console.WriteLine("Saved {0} characters successfuly.", RPCs.Count);
            Console.WriteLine("Press a key to exit the application...");
            Console.ReadKey();
        }
Esempio n. 23
0
        private void CalculateEmotions(object sender, EventArgs e)
        {
            Dictionary <string, Dictionary <string, int> > emotionList = new Dictionary <string, Dictionary <string, int> >();

            IntegratedAuthoringToolAsset loadedIAT = this.LoadedAsset;

            List <RolePlayCharacterAsset> rpcList = new List <RolePlayCharacterAsset>();

            List <WellFormedNames.Name> _eventList = new List <WellFormedNames.Name>();

            foreach (var rpc in loadedIAT.GetAllCharacterSources())
            {
                var actor = RolePlayCharacterAsset.LoadFromFile(rpc.Source);
                ;

                actor.LoadAssociatedAssets();

                loadedIAT.BindToRegistry(actor.DynamicPropertiesRegistry);

                rpcList.Add(actor);
            }

            foreach (var actor in rpcList)
            {
                foreach (var anotherActor in rpcList)
                {
                    if (actor != anotherActor)
                    {
                        var changed = new[]
                        { EventHelper.ActionEnd(anotherActor.CharacterName.ToString(), "Enters", "Room") };
                        actor.Perceive(changed);
                    }
                }

                emotionList.Add(actor.CharacterName.ToString(), new Dictionary <string, int>());
                // actor.SaveToFile("../../../Tests/" + actor.CharacterName + "-output1" + ".rpc");
            }

            string validationMessage = "";

            var rpcActions = new Dictionary <IAction, RolePlayCharacterAsset>();

            var act = rpcList.FirstOrDefault().Decide();

            if (act == null)
            {
                foreach (var r in rpcList)
                {
                    act = r.Decide();
                    if (act != null)
                    {
                        rpcActions.Add(act.FirstOrDefault(), r);
                        break;
                    }
                }
            }

            int timestamp = 0;

            while (rpcActions.Keys != null)
            {
                // Stopping condition kinda shaky
                rpcActions = new Dictionary <ActionLibrary.IAction, RolePlayCharacterAsset>();

                foreach (var rpc in rpcList)
                {
                    act = rpc.Decide();

                    if (act.FirstOrDefault() == null)
                    {
                        continue;
                    }

                    foreach (var action in act)
                    {
                        rpcActions.Add(action, rpc);
                    }
                }

                // COPY the rpc list without linked refereces

                var newList =
                    new List <RolePlayCharacterAsset>(); // mmm is the new list linked to the other? to be tested

                foreach (var action in rpcActions)
                {
                    // COPY the rpc list without linked refereces

                    var newListAux =
                        new List <RolePlayCharacterAsset>(
                            rpcList); // mmm is the new list linked to the other? to be tested

                    foreach (var rpctoPerceive in newListAux)
                    {
                        _eventList = new List <WellFormedNames.Name>();

                        if (rpctoPerceive.CharacterName != action.Value.CharacterName)
                        {
                            if (action.Key.Name.ToString().Contains("Speak") &&
                                action.Key.Target == rpctoPerceive.CharacterName)
                            {
                                _eventList.Add(EventHelper.PropertyChange(
                                                   "DialogueState(" + action.Value.CharacterName.ToString() + ")",
                                                   action.Key.Parameters.ElementAt(1).ToString(),
                                                   action.Value.CharacterName.ToString()));
                            }

                            _eventList.Add(EventHelper.ActionEnd(action.Value.CharacterName.ToString(),
                                                                 action.Key.Name.ToString(), action.Key.Target.ToString()));

                            rpctoPerceive.Perceive(_eventList);

                            newList.Add(rpctoPerceive);
                        }
                    }
                }

                rpcList.Clear();
                rpcList = newList;

                foreach (var rpc in rpcList)
                {
                    foreach (var emot in rpc.GetAllActiveEmotions())
                    {
                        if (!emotionList[rpc.CharacterName.ToString()].Keys.Contains(emot.Type))
                        {
                            emotionList[rpc.CharacterName.ToString()].Add(emot.Type, (timestamp + 1));
                        }
                    }
                }

                timestamp++;
                if (timestamp > 1)
                {
                    break;
                }
            }

            if (emotionList.Count > 0)
            {
                validationMessage = "Simulation result:                " + "\n";

                foreach (var rpc in emotionList.Keys)
                {
                    validationMessage += rpc + " felt: " + "\n";

                    foreach (var emot in emotionList[rpc])
                    {
                        var    lastFor        = timestamp - emot.Value;
                        double timePercentage = ((double)lastFor / (double)timestamp) * 100;
                        validationMessage += "Emotion: " + emot.Key + " ( " + timePercentage +
                                             "% of total scenario time)\n";
                    }
                }
            }
            else
            {
                validationMessage += "No emotions detected";
            }

            MessageBox.Show(validationMessage);
        }
Esempio n. 24
0
        private void buttonStart_Click(object sender, EventArgs e)
        {
            try
            {
                this.saveToolStripMenuItem_Click(sender, e);
            }
            catch (Exception ex)
            {
                EditorTools.WriteText(richTextBoxChat, "The IAT asset must be saved", Color.Red, true);
                return;
            }

            var sources = LoadedAsset.GetAllCharacterSources();

            if (sources.Count() <= 1)
            {
                EditorTools.WriteText(richTextBoxChat, "At least two characters are needed.", Color.Red, true);
                return;
            }

            agentsInChat = new List <RolePlayCharacterAsset>();
            foreach (var s in sources)
            {
                var rpc = RolePlayCharacterAsset.LoadFromFile(s.Source);
                rpc.LoadAssociatedAssets();
                LoadedAsset.BindToRegistry(rpc.DynamicPropertiesRegistry);
                if (rpc.CharacterName.ToString().ToLower().Contains("player"))
                {
                    rpc.IsPlayer = true;
                }

                agentsInChat.Add(rpc);
            }

            richTextBoxChat.Clear();
            listBoxPlayerDialogues.DataSource = new List <string>();
            comboBoxAgChat.DataSource         = agentsInChat.Select(a => a.CharacterName.ToString()).ToList();

            EditorTools.WriteText(richTextBoxChat, "Characters were loaded with success (" + DateTime.Now + ")",
                                  Color.Blue, true);
            var enterEvents = new List <WellFormedNames.Name>();

            foreach (var ag in agentsInChat)
            {
                enterEvents.Add(EventHelper.ActionEnd(ag.CharacterName.ToString(), "Enters", "-"));
            }

            foreach (var ag in agentsInChat)
            {
                ag.Perceive(enterEvents);

                EditorTools.WriteText(richTextBoxChat, ag.CharacterName + " enters the chat.", Color.Black, false);
                EditorTools.WriteText(richTextBoxChat,
                                      " (" + ag.GetInternalStateString() + " | " + ag.GetSIRelationsString() + ")", Color.DarkRed, true);
            }

            EditorTools.WriteText(richTextBoxChat, "", Color.Black, true);

            buttonContinue.Enabled = true;
            textBoxTick.Text       = agentsInChat[0].Tick.ToString();
            this.buttonContinue_Click(sender, e);
        }
Esempio n. 25
0
        /// <summary>
        /// Load an existing game
        /// </summary>
        public void LoadGame(string storageLocation, string boatName)
        {
            UnloadGame();
            var valid = CheckIfGameExists(storageLocation, boatName, out var iat);

            if (!valid)
            {
                return;
            }
            EventController = new EventController(iat);
            ValidateGameConfig();
            //get the iat file and all characters for this game
            var characterList = iat.GetAllCharacterSources();
            var crewList      = new List <CrewMember>();
            var nameList      = new List <string>();

            foreach (var character in characterList)
            {
                var rpc      = RolePlayCharacterAsset.LoadFromFile(character.Source);
                var position = rpc.GetBeliefValue(NPCBelief.Position.Description());
                nameList.Add(rpc.BodyName);
                //if this character is the manager, load the game details from this file and set this character as the manager
                if (position == "Manager")
                {
                    var person = new Person(rpc);
                    var boat   = new Boat(person.LoadBelief(NPCBelief.BoatType));
                    var nation = person.LoadBelief(NPCBelief.Nationality);
                    ShowTutorial              = bool.Parse(person.LoadBelief(NPCBelief.ShowTutorial));
                    TutorialStage             = Convert.ToInt32(person.LoadBelief(NPCBelief.TutorialStage));
                    _customTutorialAttributes = new Dictionary <int, Dictionary <string, string> >();
                    QuestionnaireCompleted    = bool.Parse(person.LoadBelief(NPCBelief.QuestionnaireCompleted) ?? "false");
                    Team = new Team(iat, storageLocation, iat.ScenarioName, nation, boat);
                    if (boat.Type == "Finish")
                    {
                        Team.Finished = true;
                    }
                    ActionAllowance          = Convert.ToInt32(person.LoadBelief(NPCBelief.ActionAllowance));
                    CrewEditAllowance        = Convert.ToInt32(person.LoadBelief(NPCBelief.CrewEditAllowance));
                    RaceSessionLength        = ShowTutorial ? ConfigKey.TutorialRaceSessionLength.GetIntValue() : ConfigKey.RaceSessionLength.GetIntValue();
                    Team.TeamColorsPrimary   = new Color(Convert.ToInt32(person.LoadBelief(NPCBelief.TeamColorRedPrimary)), Convert.ToInt32(person.LoadBelief(NPCBelief.TeamColorGreenPrimary)), Convert.ToInt32(person.LoadBelief(NPCBelief.TeamColorBluePrimary)));
                    Team.TeamColorsSecondary = new Color(Convert.ToInt32(person.LoadBelief(NPCBelief.TeamColorRedSecondary)), Convert.ToInt32(person.LoadBelief(NPCBelief.TeamColorGreenSecondary)), Convert.ToInt32(person.LoadBelief(NPCBelief.TeamColorBlueSecondary)));
                    Team.Manager             = person;
                    continue;
                }
                //set up every other character as a CrewManager, making sure to separate retired and recruits
                var crewMember = new CrewMember(rpc);
                switch (position)
                {
                case "Retired":
                    Team.RetiredCrew.Add(crewMember.Name, crewMember);
                    Team.RetiredCrew.Values.ToList().ForEach(cm => cm.LoadBeliefs(nameList));
                    continue;

                case "Recruit":
                    Team.Recruits.Add(crewMember.Name, crewMember);
                    Team.Recruits.Values.ToList().ForEach(cm => cm.LoadBeliefs(nameList));
                    continue;
                }
                crewList.Add(crewMember);
            }
            crewList.ForEach(cm => Team.AddCrewMember(cm));
            crewList.ForEach(cm => cm.LoadBeliefs(nameList, Team));
            LoadLineUpHistory();
            LoadCurrentEvents();
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            var iat = IntegratedAuthoringToolAsset.LoadFromFile("../../../Examples/CiF-Tutorial/JobInterview.iat");

            rpcList = new List <RolePlayCharacterAsset>();
            var wm = new WorldModelAsset();

            wm.AddActionEffect((Name)"Event(Action-End, *, Speak(*,*,*,*), [t])", new EffectDTO()
            {
                PropertyName  = (Name)"Has(Floor)",
                NewValue      = (Name)"[t]",
                ObserverAgent = (Name)"*"
            });

            wm.AddActionEffect((Name)"Event(Action-End, [i], Speak([cs],[ns],*,*), SELF)", new EffectDTO()
            {
                PropertyName  = (Name)"DialogueState([i])",
                NewValue      = (Name)"[ns]",
                ObserverAgent = (Name)"[t]"
            });


            wm.AddActionEffect((Name)"Event(Action-End, SELF, Speak([cs],[ns],*,*), [t])", new EffectDTO()
            {
                PropertyName  = (Name)"DialogueState([t])",
                NewValue      = (Name)"[ns]",
                ObserverAgent = (Name)"[i]"
            });

            wm.SaveToFile("../../../Examples/WM-Tutorial/WorldModel.wm");
            foreach (var source in iat.GetAllCharacterSources())
            {
                var rpc = RolePlayCharacterAsset.LoadFromFile(source.Source);


                //rpc.DynamicPropertiesRegistry.RegistDynamicProperty(Name.BuildName("Volition"),cif.VolitionPropertyCalculator);
                rpc.LoadAssociatedAssets();

                iat.BindToRegistry(rpc.DynamicPropertiesRegistry);

                rpcList.Add(rpc);
            }


            foreach (var actor in rpcList)
            {
                foreach (var anotherActor in rpcList)
                {
                    if (actor != anotherActor)
                    {
                        var changed = new[] { EventHelper.ActionEnd(anotherActor.CharacterName.ToString(), "Enters", "Room") };
                        actor.Perceive(changed);
                    }
                }
                //         actor.SaveToFile("../../../Examples/" + actor.CharacterName + "-output1" + ".rpc");
            }



            List <Name>    _events  = new List <Name>();
            List <IAction> _actions = new List <IAction>();

            IAction action = null;

            while (true)
            {
                _actions.Clear();
                foreach (var rpc in rpcList)
                {
                    rpc.Tick++;

                    Console.WriteLine("Character perceiving: " + rpc.CharacterName + " its mood: " + rpc.Mood);

                    rpc.Perceive(_events);
                    var decisions = rpc.Decide();
                    _actions.Add(decisions.FirstOrDefault());

                    foreach (var act in decisions)
                    {
                        Console.WriteLine(rpc.CharacterName + " has this action: " + act.Name);
                    }
                    rpc.SaveToFile("../../../Examples/WM-Tutorial/" + rpc.CharacterName + "-output" + ".rpc");
                }

                _events.Clear();

                var randomGen = new Random(Guid.NewGuid().GetHashCode());

                var pos = randomGen.Next(rpcList.Count);
                int i   = 0;

                var initiator = rpcList[pos];


                action = _actions.ElementAt(pos);

                Console.WriteLine();
                if (action == null)
                {
                    Console.WriteLine(initiator.CharacterName + " does not have any action to do ");
                }

                if (action != null)
                {
                    var initiatorName = initiator.CharacterName.ToString();
                    var targetName    = action.Target.ToString();
                    var nextState     = action.Parameters[1].ToString();
                    var currentState  = action.Parameters[0].ToString();

                    Console.WriteLine("Action: " + initiatorName + " does " + action.Name + " to " +
                                      targetName + "\n" + action.Parameters[1]);

                    _events.Add(EventHelper.ActionEnd(initiatorName, action.Name.ToString(),
                                                      action.Target.ToString()));



                    Console.WriteLine();
                    Console.WriteLine("Dialogue:");
                    Console.WriteLine("Current State: " + currentState);
                    if (iat.GetDialogueActions(action.Parameters[0], action.Parameters[1], action.Parameters[2], action.Parameters[3]).FirstOrDefault() != null)
                    {
                        Console.WriteLine(initiator.CharacterName + " says: ''" +
                                          iat.GetDialogueActions(action.Parameters[0], action.Parameters[1], action.Parameters[2], action.Parameters[3]).FirstOrDefault().Utterance + "'' to " + targetName);
                    }
                    else
                    {
                        Console.WriteLine(initiator.CharacterName + " says: " + "there is no dialogue suited for this action");
                    }


                    // WORLD MODEL
                    var effects = wm.Simulate(_events.ToArray());
                    foreach (var ef in effects)
                    {
                        if (ef.ObserverAgent == (Name)"*")
                        {
                            foreach (var rpc in rpcList)
                            {
                                var proChange =
                                    EventHelper.PropertyChange(ef.PropertyName.ToString(), ef.NewValue.ToString(), "World");
                                rpc.Perceive(proChange);
                            }
                        }

                        else
                        {
                            var proChange =
                                EventHelper.PropertyChange(ef.PropertyName.ToString(), ef.NewValue.ToString(), "World");
                            rpcList.Find(x => x.CharacterName == ef.ObserverAgent).Perceive(proChange);
                        }
                    }

                    Console.WriteLine("Next State: " + nextState);
                }
                Console.WriteLine();
                Console.ReadKey();
            }
        }
    private void LoadScenario(SingleCharacterDemo.ScenarioData data)
    {
        ClearButtons();

        _iat = data.IAT;


        if (skipDescription)
        {
            _introPanel.SetActive(true);
            _introText.text = string.Format("<b>{0}</b>\n\n\n{1}", _iat.ScenarioName, _iat.ScenarioDescription);
        }

        if (_iat.m_worldModelSource != null)
        {
            if (_iat.m_worldModelSource.Source != "" && _iat.m_worldModelSource.Source != null)
            {
                _wm = WorldModel.WorldModelAsset.LoadFromFile(_iat.GetWorldModelSource().Source);
            }
        }


        var characterSources = _iat.GetAllCharacterSources().ToList();
        int CharacterCount   = 0;

        foreach (var source in characterSources)
        {
            var rpc = RolePlayCharacterAsset.LoadFromFile(source.Source);
            rpc.LoadAssociatedAssets();
            _iat.BindToRegistry(rpc.DynamicPropertiesRegistry);
            rpcList.Add(rpc);
            var body = m_bodies.FirstOrDefault(b => b.BodyName == rpc.BodyName);

            UnityEngine.Random.InitState((int)System.DateTime.Now.Ticks);

            var r = UnityEngine.Random.Range(0, 30);
            Debug.Log("Going to wait" + r);
            StartCoroutine(JustWait(UnityEngine.Random.Range(0, 3)));

            _agentController = new MultiCharacterAgentController(data, rpc, _iat, body.CharaterArchtype, m_characterAnchors[CharacterCount], m_dialogController);
            // StopAllCoroutines();
            _agentControllers.Add(_agentController);


            if (rpc.CharacterName == _player.CharacterName)
            {
                _player = rpc;
            }

            CharacterCount++;
        }

        foreach (var agent in _agentControllers)
        {
            if (agent.RPC.CharacterName != _player.CharacterName)
            {
                agent.StartBehaviour(this, VersionMenu);
            }
        }


        foreach (var actor in rpcList)
        {
            foreach (var anotherActor in rpcList)
            {
                if (actor != anotherActor)
                {
                    var changed = new[] { EventHelper.ActionEnd(anotherActor.CharacterName.ToString(), "Enters", "Room") };
                    actor.Perceive(changed);
                }
            }
        }
        SetCamera();
        PlayerDecide();
    }
Esempio n. 28
0
        static void Main(string[] args)
        {
            var playerStr = IATConsts.PLAYER;

            //Loading the asset
            var iat          = IntegratedAuthoringToolAsset.LoadFromFile("../../../Examples/IAT-Tutorial/IATTest.iat");
            var currentState = IATConsts.INITIAL_DIALOGUE_STATE;
            var rpc          = RolePlayCharacterAsset.LoadFromFile(iat.GetAllCharacterSources().FirstOrDefault().Source);

            rpc.LoadAssociatedAssets();
            iat.BindToRegistry(rpc.DynamicPropertiesRegistry);

            iat.GetAllCharacterSources().ToList();
            while (currentState != IATConsts.TERMINAL_DIALOGUE_STATE)
            {
                var playerDialogs = iat.GetDialogueActionsByState(currentState);

                Console.WriteLine("Current Dialogue State: " + currentState);
                Console.WriteLine("Available choices: ");

                for (int i = 0; i < playerDialogs.Count(); i++)
                {
                    Console.WriteLine(i + " - " + playerDialogs.ElementAt(i).Utterance);
                }
                int pos = -1;

                do
                {
                    Console.Write("Select Option: ");
                } while (!Int32.TryParse(Console.ReadLine(), out pos) || pos >= playerDialogs.Count() || pos < 0);

                var chosenDialog = playerDialogs.ElementAt(pos);

                var actionName = iat.BuildSpeakActionName(chosenDialog.Id);
                var speakEvt   = EventHelper.ActionEnd(playerStr, actionName.ToString(), rpc.CharacterName.ToString());

                currentState = chosenDialog.NextState;
                var dialogStateChangeEvt = EventHelper.PropertyChange(string.Format(IATConsts.DIALOGUE_STATE_PROPERTY, playerStr), chosenDialog.NextState, playerStr);

                rpc.Perceive(speakEvt);
                rpc.Perceive(dialogStateChangeEvt);
                var characterActions = rpc.Decide();

                var characterAction = characterActions.FirstOrDefault();

                if (characterAction.Key.ToString() == IATConsts.DIALOG_ACTION_KEY)
                {
                    var dialog = iat.GetDialogueActions(
                        characterAction.Parameters[0],
                        characterAction.Parameters[1],
                        characterAction.Parameters[2],
                        characterAction.Parameters[3]).FirstOrDefault();
                    Console.WriteLine("\n" + rpc.CharacterName + ": " + dialog.Utterance + "\n");
                    currentState = characterAction.Parameters[1].ToString();
                    Console.WriteLine("\nMood: " + rpc.Mood);
                }
                else
                {
                    Console.WriteLine("\n" + rpc.CharacterName + ": " + characterAction.Name + "\n");
                }
            }


            // The next step in this tutorrial is to start using the World Model to cause effects in the belief state of the characters

            Console.WriteLine("Dialogue Reached a Terminal State");
            Console.ReadKey();
        }
    private void LoadScenario(ScenarioData data)
    {
        ClearButtons();

        _iat = data.IAT;

        _introPanel.SetActive(true);
        _introText.text = string.Format("<b>{0}</b>\n\n\n{1}", _iat.ScenarioName, _iat.ScenarioDescription);



        if (_iat.m_worldModelSource != null)
        {
            if (!string.IsNullOrEmpty(_iat.m_worldModelSource.Source))
            {
                var wat = _iat.GetWorldModelSource();

                string errorsOnLoad;

                //  _wm = WorldModel.WorldModelAsset.LoadFromFile(_iat.GetWorldModelSource().RelativePath);
                _wm = WorldModel.WorldModelAsset.LoadFromFile(_iat.GetWorldModelSource().Source, out errorsOnLoad);

                if (errorsOnLoad != null)
                {
                    throw new Exception(errorsOnLoad);
                }
            }
        }
        var characterSources = _iat.GetAllCharacterSources().ToList();

        foreach (var source in characterSources)
        {
            var rpc = RolePlayCharacterAsset.LoadFromFile(source.Source);
            rpc.LoadAssociatedAssets();
            _iat.BindToRegistry(rpc.DynamicPropertiesRegistry);

            if (rpc.CharacterName.ToString().Contains("Player"))
            {
                Player = rpc;
                continue;
            }
            AddButton(characterSources.Count <= 2 ? "Start" : rpc.CharacterName.ToString(),
                      () =>
            {
                var body         = m_bodies.FirstOrDefault(b => b.BodyName == rpc.BodyName);
                _agentController = new AgentControler(data, rpc, _iat, body.CharaterArchtype, m_characterAnchor, m_dialogController);
                StopAllCoroutines();
                _agentController.Start(this, VersionMenu);

                _background.SetActive(true);
                if (!backgrounds.IsEmpty())
                {
                    if (!backgrounds.ToList().FindAll(x => x.scenarioName == _iat.ScenarioName).IsEmpty())
                    {
                        _background.GetComponent <Renderer>().material = backgrounds.ToList().Find(x => x.scenarioName == _iat.ScenarioName).mat;
                    }
                    else
                    {
                        _background.GetComponent <Renderer>().material = activeBackgroundMaterial;
                    }
                }
                else
                {
                    _background.GetComponent <Renderer>().material = activeBackgroundMaterial;
                }
            });
        }
        AddButton("Back to Scenario Selection Menu", () =>
        {
            _iat = null;
            LoadScenarioMenu();
        });
    }
Esempio n. 30
0
        static void Main(string[] args)
        {
            //Loading the asset
            var rpc = RolePlayCharacterAsset.LoadFromFile("../../../Examples/RPC-Tutorial/RPCTest.rpc");

            rpc.LoadAssociatedAssets();
            rpc.ActivateIdentity(new Identity((Name)"Portuguese", (Name)"Culture", 1));
            Console.WriteLine("Starting Mood: " + rpc.Mood);
            var actions = rpc.Decide();
            var action  = actions.FirstOrDefault();

            rpc.SaveToFile("../../../Examples/RPC-Tutorial/RPCTest-Output.rpc");
            rpc.Update();

            Console.WriteLine("The name of the character loaded is: " + rpc.CharacterName);
            //  Console.WriteLine("The following event was perceived: " + event1);
            Console.WriteLine("Mood after event: " + rpc.Mood);
            Console.WriteLine("Strongest emotion: " + rpc.GetStrongestActiveEmotion()?.EmotionType + "-" + rpc.GetStrongestActiveEmotion()?.Intensity);
            Console.WriteLine("First Response: " + action?.Name + ", Target:" + action?.Target.ToString());

            rpc.SaveToFile("../../../Examples/RPC-Tutorial/RPCTest-Output.rpc");

            var busyAction = rpc.Decide().FirstOrDefault();

            Console.WriteLine("Second Response: " + busyAction?.Name + ", Target:" + action?.Target.ToString());

            var event3 = EventHelper.ActionEnd(rpc.CharacterName.ToString(), action?.Name.ToString(), "Player");

            rpc.Perceive(new[] { event3 });
            action = rpc.Decide().FirstOrDefault();

            Console.WriteLine("Third Response: " + action?.Name + ", Target:" + action?.Target.ToString());


            int x = 0;

            while (true)
            {
                Console.WriteLine("Mood after tick: " + rpc.Mood + " x: " + x + " tick: " + rpc.Tick);
                Console.WriteLine("Strongest emotion: " + rpc.GetStrongestActiveEmotion()?.EmotionType + "-" + rpc.GetStrongestActiveEmotion()?.Intensity);
                rpc.SaveToFile("../../../Examples/RPC-Tutorial/RPCTest-Output.rpc");
                rpc.Update();
                Console.ReadLine();


                if (x == 10)
                {
                    var event1 = EventHelper.ActionEnd("Player", "Kick", rpc.CharacterName.ToString());

                    rpc.Perceive(new[] { event1 });
                    action = rpc.Decide().FirstOrDefault();
                    rpc.SaveToFile("../../../Examples/RPC-Tutorial/RPCTest-OutputEvent.rpc");
                    rpc.Update();
                }


                if (x == 11)
                {
                    rpc.ResetEmotionalState();
                }
                if (x == 25)
                {
                    var event1 = EventHelper.ActionEnd("Player", "Kick", rpc.CharacterName.ToString());

                    rpc.Perceive(new[] { event1 });
                    action = rpc.Decide().FirstOrDefault();
                    rpc.SaveToFile("../../../Examples/RPC-Tutorial/RPCTest-OutputEvent.rpc");
                    rpc.Update();
                }


                else if (x == 30)
                {
                    Console.WriteLine("Reloading " + rpc.GetStrongestActiveEmotion().Intensity + " " + rpc.GetStrongestActiveEmotion().EmotionType + " mood: " + rpc.Mood);
                    rpc.SaveToFile("RPCTestReload.rpc");

                    rpc = RolePlayCharacterAsset.LoadFromFile("RPCTestReload.rpc");
                    Console.WriteLine("Reloading result: " + rpc.GetStrongestActiveEmotion().Intensity + " " + rpc.GetStrongestActiveEmotion().EmotionType + " mood: " + rpc.Mood);
                }

                x++;
            }
            Console.WriteLine("Mood after tick: " + rpc.Mood);
            Console.ReadKey();
        }