Exemple #1
0
 public YarnState(
     String ConversationFile,
     String StartNode,
     Yarn.MemoryVariableStore Memory) :
     base(Game, "YarnState", GameState.Game.StateManager)
 {
     YarnEngine = new YarnEngine(ConversationFile, StartNode, Memory, this);
 }
Exemple #2
0
 private static void _pick(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
 {
     State.EnterQueueingAction((list) =>
     {
         if (list.Count > 0)
         {
             State.PlayerInterface.Speak(list[Random.Next(list.Count)] + "\n");
         }
     });
 }
Exemple #3
0
 public YarnState(
     WorldManager world,
     String ConversationFile,
     String StartNode,
     Yarn.MemoryVariableStore Memory) :
     base(Game)
 {
     World      = world;
     YarnEngine = new YarnEngine(ConversationFile, StartNode, Memory, this);
 }
        // Validates a single script.
        ValidationMessage[] ValidateFile(TextAsset script, Analysis.Context analysisContext, out CheckerResult.State result)
        {
            var messageList = new List <ValidationMessage>();

            var variableStorage = new Yarn.MemoryVariableStore();

            var dialog = new Dialogue(variableStorage);

            bool failed = false;

            dialog.LogErrorMessage = delegate(string message) {
                var msg = new ValidationMessage();
                msg.type    = MessageType.Error;
                msg.message = message;
                messageList.Add(msg);

                // any errors means this validation failed
                failed = true;
            };

            dialog.LogDebugMessage = delegate(string message) {
                var msg = new ValidationMessage();
                msg.type    = MessageType.Info;
                msg.message = message;
                messageList.Add(msg);
            };

            try {
                dialog.LoadString(script.text, script.name);
            } catch (System.Exception e) {
                dialog.LogErrorMessage(e.Message);
            }

            dialog.Analyse(analysisContext);

            if (failed)
            {
                result = CheckerResult.State.Failed;
            }
            else
            {
                result = CheckerResult.State.Passed;
            }

            return(messageList.ToArray());
        }
Exemple #5
0
        public YarnEngine(
            String ConversationFile,
            String StartNode,
            Yarn.MemoryVariableStore Memory,
            IYarnPlayerInterface PlayerInterface)
        {
            this.PlayerInterface = PlayerInterface;
            this.Memory          = Memory;

            CommandGrammar = new YarnCommandGrammar();

            foreach (var method in AssetManager.EnumerateModHooks(typeof(YarnCommandAttribute), typeof(void), new Type[]
            {
                typeof(YarnEngine),
                typeof(List <Ancora.AstNode>),
                typeof(Yarn.MemoryVariableStore)
            }))
            {
                var attribute = method.GetCustomAttributes(false).FirstOrDefault(a => a is YarnCommandAttribute) as YarnCommandAttribute;
                if (attribute == null)
                {
                    continue;
                }
                CommandHandlers[attribute.CommandName] = new CommandHandler
                {
                    Action   = (state, args, mem) => method.Invoke(null, new Object[] { state, args, mem }),
                    Settings = attribute
                };
            }

            Dialogue = new Yarn.Dialogue(Memory);

            Dialogue.LogDebugMessage = delegate(string message) { Console.WriteLine(message); };
            Dialogue.LogErrorMessage = delegate(string message) { Console.WriteLine("Yarn Error: " + message); };

            //try
            {
                Dialogue.LoadFile(AssetManager.ResolveContentPath(ConversationFile), false, false, null);
            }
            //catch (Exception e)
            {
                //  Console.Error.WriteLine(e.ToString());
            }

            Runner = Dialogue.Run(StartNode).GetEnumerator();
        }
 private static void _end_trade(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
 {
     State.PlayerInterface.EndTrade();
 }
Exemple #7
0
 private static void _end_conversation(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
 {
     State.EndConversation();
 }
 private static void _hide_portrait(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
 {
     State.PlayerInterface.HidePortrait();
 }
        private static void _end_strike(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var employee = Memory.GetValue("$employee");
            var creature = employee.AsObject as CreatureAI;

            if (creature == null)
            {
                return;
            }
            creature.Stats.IsOnStrike = false;

            if (creature.GetRoot().GetComponent <DwarfThoughts>().HasValue(out var thoughts))
            {
                thoughts.Thoughts.RemoveAll(t => t.Description.Contains("paid"));
                creature.Creature.AddThought("I got paid recently.", new TimeSpan(1, 0, 0, 0), 10.0f);
            }

            if (creature is DwarfAI dorf)
            {
                dorf.OnPaid();
            }
        }
        // Validates a single script.
        ValidationMessage[] ValidateFile(TextAsset script, Analysis.Context analysisContext, out CheckerResult.State result)
        {
            var messageList = new List<ValidationMessage>();

            var variableStorage = new Yarn.MemoryVariableStore();

            var dialog = new Dialogue(variableStorage);

            bool failed = false;

            dialog.LogErrorMessage = delegate (string message) {
                var msg = new ValidationMessage();
                msg.type = MessageType.Error;
                msg.message = message;
                messageList.Add(msg);

                // any errors means this validation failed
                failed = true;
            };

            dialog.LogDebugMessage = delegate (string message) {
                var msg = new ValidationMessage();
                msg.type = MessageType.Info;
                msg.message = message;
                messageList.Add(msg);
            };

            try {
                dialog.LoadString(script.text,script.name);
            } catch (System.Exception e) {
                dialog.LogErrorMessage(e.Message);
            }

            dialog.Analyse(analysisContext);

            if (failed) {
                result = CheckerResult.State.Failed;
            } else {
                result = CheckerResult.State.Passed;
            }

            return messageList.ToArray();
        }
Exemple #11
0
 public ConsoleRunnerImplementation(bool waitForLines = false)
 {
     this.variableStore = new MemoryVariableStore();
     this.waitForLines = waitForLines;
 }
Exemple #12
0
        private static void _set_portrait(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var frames = new List <int>();

            for (var i = 4; i < Arguments.Count; ++i)
            {
                frames.Add((int)((float)Arguments[i].Value));
            }
            State.PlayerInterface.SetPortrait((string)Arguments[0].Value, (int)((float)Arguments[1].Value), (int)((float)Arguments[2].Value), (float)Arguments[3].Value, frames);
        }
        private static void _wait_for_trade(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            State.Pause();
            State.PlayerInterface.WaitForTrade((tradeResult, transaction) =>
            {
                if (tradeResult == Play.Trading.TradeDialogResult.Cancel)
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("cancelled"));
                }
                else if (tradeResult == Play.Trading.TradeDialogResult.RejectProfit)
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("unprofitable"));
                }
                else if (envoy.OwnerFaction.Race.HasValue(out var race0) && transaction.PlayerItems.Select(i => Library.GetResourceType(i.TypeName))
                         .SelectMany(i => { if (i.HasValue(out var t))
                                            {
                                                return(t.Tags);
                                            }
                                            return(new List <String>()); })
                         .Any(tag => race0.HatedResources.Contains(tag)))
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("hated"));
                }
Exemple #14
0
        private static void _end_strike(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var employee = Memory.GetValue("$employee");
            var creature = employee.AsObject as CreatureAI;

            if (creature == null)
            {
                return;
            }
            creature.Status.IsOnStrike = false;
        }
Exemple #15
0
        private static void _add_thought(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var employee = Memory.GetValue("$employee");
            var creature = employee.AsObject as CreatureAI;

            if (creature == null)
            {
                return;
            }
            creature.Creature.AddThought(new Thought()
            {
                Description       = (string)Arguments[0].Value,
                TimeLimit         = new TimeSpan((int)(float)Arguments[2].Value, 0, 0),
                HappinessModifier = (float)Arguments[1].Value,
                Type      = Thought.ThoughtType.Other,
                TimeStamp = creature.World.Time.CurrentDate
            }, false);
        }
Exemple #16
0
        private static void _pay_employee(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var employee = Memory.GetValue("$employee");
            var creature = employee.AsObject as CreatureAI;

            if (creature == null)
            {
                return;
            }
            var bonus = Memory.GetValue("$employee_bonus").AsNumber;

            creature.AddMoney((decimal)(float)bonus);
            creature.Faction.AddMoney(-(decimal)(float)bonus);
        }
Exemple #17
0
        private static void _wait_for_market(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            State.Pause();
            State.PlayerInterface.WaitForMarket((tradeResult, transaction) =>
            {
                if (tradeResult == Gui.Widgets.MarketDialogResult.Cancel)
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("cancelled"));
                }
                else
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("acceptable"));
                }

                Memory.SetValue("$trade_transaction", new Yarn.Value(transaction));
                State.CancelSpeech();
                State.Unpause();
            });
        }
Exemple #18
0
        private static void _finalize_trade(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var transaction   = Memory.GetValue("$trade_transaction").AsObject as Trade.TradeTransaction;
            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            if (transaction == null || envoy == null || playerFaction == null || world == null)
            {
                State.PlayerInterface.Output("Command 'finalize_trade' can only be called from a TradeEnvoy initiated conversation.");
                return;
            }

            transaction.Apply(world);

            world.GoalManager.OnGameEvent(new Goals.Triggers.Trade
            {
                PlayerFaction = playerFaction,
                PlayerGold    = transaction.PlayerMoney,
                PlayerGoods   = transaction.PlayerItems,
                OtherFaction  = envoy.OwnerFaction,
                OtherGold     = transaction.EnvoyMoney,
                OtherGoods    = transaction.EnvoyItems
            });
        }
        private static void _make_peace(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            if (envoy == null || playerFaction == null || world == null)
            {
                State.PlayerInterface.Output("Command 'make_peace' can only be called from a TradeEnvoy initiated conversation.");
                return;
            }

            world.Overworld.GetPolitics(playerFaction.ParentFaction, envoy.OwnerFaction.ParentFaction).IsAtWar = false;
        }
 private static void _set_language(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
 {
     if (Library.GetRace(Arguments[0].Value.ToString()).HasValue(out var race))
     {
         State.PlayerInterface.SetLanguage(race.Language);
     }
     else
     {
         State.PlayerInterface.Output("ERROR setting language: Race not found.");
     }
 }
Exemple #21
0
        private static void _set_language(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var race = RaceLibrary.FindRace(Arguments[0].Value.ToString());

            if (race != null)
            {
                State.PlayerInterface.SetLanguage(race.Speech.Language);
            }
            else
            {
                State.PlayerInterface.Output("ERROR setting language: Race not found.");
            }
        }
Exemple #22
0
        void CompileAllScripts()
        {
            // Start compiling all scripts.

            // First, record when we started - we need
            // to know if it's time to show a progress
            // dialogue
            var startTime = EditorApplication.timeSinceStartup;

            // Have we presented a progress bar?
            var progressBarVisible = false;

            // Start compiling all files; the delegate will be called
            // after each file has been compiled

            int complete = 0;
            int total    = checkResults.Count;


            AssetDatabase.StartAssetEditing();

            foreach (var entry in checkResults)
            {
                // How long have we been at this?
                var timeSinceStart = EditorApplication.timeSinceStartup - startTime;

                // If longer than 'timeBeforeProgressBar', show the progress bar
                if (timeSinceStart > timeBeforeProgressBar)
                {
                    // Figure out how much of the progress bar should be filled
                    var progress = (float)complete / (float)total;

                    // Describe what we're doing
                    var info = string.Format("Compiling file {0} of {1}...", complete, total);

                    // Display or update the bar
                    EditorUtility.DisplayProgressBar("Compiling Yarn Files", info, progress);

                    // Record that we need to clear this bar
                    progressBarVisible = true;
                }

                var variableStorage = new Yarn.MemoryVariableStore();

                var dialog = new Dialogue(variableStorage);

                bool failed = false;

                dialog.LogErrorMessage = delegate(string message) {
                    Debug.LogErrorFormat("Error when compiling: {0}", message);

                    failed = true;
                };

                dialog.LogDebugMessage = delegate(string message) {
                    Debug.LogFormat("{0}", message);
                };

                try {
                    dialog.LoadString(entry.script.text, entry.script.name);
                } catch (System.Exception e) {
                    dialog.LogErrorMessage(e.Message);
                    break;
                }

                if (failed)
                {
                    Debug.LogErrorFormat("Failed to compile script {0}; stopping", entry.script.name);
                    break;
                }

                // Figure out where this will go
                var path = AssetDatabase.GetAssetPath(entry.script);

                path = System.IO.Path.ChangeExtension(path, "yarn.bytes");

                var bytes = dialog.GetCompiledProgram();

                System.IO.File.WriteAllBytes(path, bytes);

                complete++;
            }

            // All done. Get rid of the progress bar if needed.
            if (progressBarVisible)
            {
                EditorUtility.ClearProgressBar();
            }

            AssetDatabase.StopAssetEditing();
        }
        private static void _pay_tribute(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            if (envoy == null || playerFaction == null || world == null)
            {
                State.PlayerInterface.Output("Command 'pay_tribute' can only be called from a TradeEnvoy initiated conversation.");
                return;
            }

            envoy.TributeDemanded = (decimal)0.0f;
            playerFaction.AddMoney(-Math.Min(world.PlayerFaction.Economy.CurrentMoney,
                                             envoy.TributeDemanded));
            Memory.SetValue("$envoy_tribute_demanded", new Yarn.Value(0.0f));
            Memory.SetValue("$envoy_demands_tribute", new Yarn.Value(false));
        }
        private static void _add_thought(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var employee = Memory.GetValue("$employee");
            var creature = employee.AsObject as CreatureAI;

            if (creature == null)
            {
                return;
            }
            creature.Creature.AddThought((string)Arguments[0].Value, new TimeSpan((int)(float)Arguments[2].Value, 0, 0), (float)Arguments[1].Value);
        }
        private static void _political_event(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            if (envoy == null || playerFaction == null || world == null)
            {
                State.PlayerInterface.Output("Command 'political_event' can only be called from a TradeEnvoy initiated conversation.");
                return;
            }

            var politics = world.Diplomacy.GetPolitics(playerFaction, envoy.OwnerFaction);

            politics.RecentEvents.Add(new Diplomacy.PoliticalEvent()
            {
                Description = (string)Arguments[0].Value,
                Change      = (float)Arguments[1].Value,
                Duration    = new TimeSpan((int)((float)Arguments[2].Value), 0, 0, 0),
                Time        = world.Time.CurrentDate
            });
        }
Exemple #26
0
        private static void _recall_envoy(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var envoy = Memory.GetValue("$envoy").AsObject as TradeEnvoy;

            if (envoy == null)
            {
                State.PlayerInterface.Output("Command 'recall_envoy' can only be called from a TradeEnvoy initiated conversation.");
                return;
            }

            Diplomacy.RecallEnvoy(envoy);
        }
Exemple #27
0
        // Validates a single script.
        ValidationMessage[] ValidateFile(TextAsset script, Analysis.Context analysisContext, out CheckerResult.State result)
        {
            // The list of messages we got from the compiler.
            var messageList = new List <ValidationMessage>();

            // A dummy variable storage; it won't be used, but Dialogue
            // needs it.
            var variableStorage = new Yarn.MemoryVariableStore();

            // The Dialog object is the compiler.
            var dialog = new Dialogue(variableStorage);

            // Whether compilation failed or not; this will be
            // set to true if any error messages are returned.
            bool failed = false;

            // Called when we get an error message. Convert this
            // message into a ValidationMessage and store it;
            // additionally, mark that this file failed compilation
            dialog.LogErrorMessage = delegate(string message) {
                var msg = new ValidationMessage();
                msg.type    = MessageType.Error;
                msg.message = message;
                messageList.Add(msg);

                // any errors means this validation failed
                failed = true;
            };

            // Called when we get an error message. Convert this
            // message into a ValidationMessage and store it
            dialog.LogDebugMessage = delegate(string message) {
                var msg = new ValidationMessage();
                msg.type    = MessageType.Info;
                msg.message = message;
                messageList.Add(msg);
            };

            // Attempt to compile this script. Any exceptions will result
            // in an error message
            try {
                dialog.LoadString(script.text, script.name);
            } catch (System.Exception e) {
                dialog.LogErrorMessage(e.Message);
            }

            // Once compilation has finished, run the analysis on it
            dialog.Analyse(analysisContext);

            // Did it succeed or not?
            if (failed)
            {
                result = CheckerResult.State.Failed;
            }
            else
            {
                result = CheckerResult.State.Passed;
            }

            // All done.
            return(messageList.ToArray());
        }
Exemple #28
0
        private static void _finalize_market(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var transaction   = Memory.GetValue("$trade_transaction").AsObject as Trade.MarketTransaction;
            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            if (transaction == null || envoy == null || playerFaction == null || world == null)
            {
                State.PlayerInterface.Output("Command 'finalize_trade' can only be called from a TradeEnvoy initiated conversation.");
                return;
            }

            transaction.Apply(world);
        }
Exemple #29
0
 public ConsoleRunnerImplementation(bool waitForLines = false)
 {
     this.variableStore = new MemoryVariableStore();
     this.waitForLines  = waitForLines;
 }
Exemple #30
0
        private static void _market(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var realState = State.PlayerInterface as YarnState; // THIS IS A HACK.

            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            if (envoy == null || playerFaction == null || world == null)
            {
                State.PlayerInterface.Output("Command 'trade' can only be called from a TradeEnvoy initiated conversation.");
                return;
            }

            State.PlayerInterface.BeginMarket(envoy, playerFaction);
        }
Exemple #31
0
        private static void _wait_for_trade(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            State.Pause();
            State.PlayerInterface.WaitForTrade((tradeResult, transaction) =>
            {
                if (tradeResult == Gui.Widgets.TradeDialogResult.Cancel)
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("cancelled"));
                }
                else if (tradeResult == Gui.Widgets.TradeDialogResult.RejectProfit)
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("unprofitable"));
                }
                else if (transaction.PlayerItems.Select(i => Library.GetResourceType(i.Type))
                         .SelectMany(i => i.Tags)
                         .Any(tag => envoy.OwnerFaction.Race.HatedResources.Contains(tag)))
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("hated"));
                }
                else if (transaction.PlayerItems.Select(i => Library.GetResourceType(i.Type))
                         .SelectMany(i => i.Tags)
                         .Any(tag => envoy.OwnerFaction.Race.LikedResources.Contains(tag)))
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("liked"));
                }
                else
                {
                    Memory.SetValue("$trade_result", new Yarn.Value("acceptable"));
                }

                Memory.SetValue("$trade_transaction", new Yarn.Value(transaction));
                State.CancelSpeech();
                State.Unpause();
            });
        }
Exemple #32
0
        private static void _declare_war(YarnEngine State, List <Ancora.AstNode> Arguments, Yarn.MemoryVariableStore Memory)
        {
            var envoy         = Memory.GetValue("$envoy").AsObject as TradeEnvoy;
            var playerFaction = Memory.GetValue("$player_faction").AsObject as Faction;
            var world         = Memory.GetValue("$world").AsObject as WorldManager;

            if (envoy == null || playerFaction == null || world == null)
            {
                State.PlayerInterface.Output("Command 'declare_war' can only be called from a TradeEnvoy initiated conversation.");
                return;
            }

            world.GoalManager.OnGameEvent(new Goals.Triggers.DeclareWar
            {
                PlayerFaction = playerFaction,
                OtherFaction  = envoy.OwnerFaction
            });
        }