// IComponent
        public void Init(DeltinScript deltinScript)
        {
            DeltinScript = deltinScript;

            _waitAsyncQueue = DeltinScript.VarCollection.Assign("waitAsync_queue", true, false);
            DeltinScript.InitialGlobal.ActionSet.AddAction(_waitAsyncQueue.SetVariable(Element.EmptyArray()));

            // Rule creator.
            var rule = new TranslateRule(DeltinScript, "waitAsync", RuleEvent.OngoingGlobal);

            rule.Conditions.Add(new Condition(
                                    Element.Any(_waitAsyncQueue.Get(), ArrayElementTimeSurpassed(Element.ArrayElement()))
                                    ));

            // Get the affected item.
            var item = DeltinScript.VarCollection.Assign("waitAsync_item", true, false);

            rule.ActionSet.AddAction(item.SetVariable(Element.FirstOf(Element.Filter(
                                                                          Element.Map(_waitAsyncQueue.Get(), Element.ArrayIndex()),
                                                                          ArrayElementTimeSurpassed(_waitAsyncQueue.Get()[Element.ArrayElement()])
                                                                          ))));

            // Activate item lambda.
            DeltinScript.WorkshopConverter.LambdaBuilder.Call(rule.ActionSet.New(Element.LastOf(_waitAsyncQueue.Get()[item.Get()])), new Functions.Builder.CallInfo(), null);

            // Remove from queue.
            rule.ActionSet.AddAction(_waitAsyncQueue.ModifyVariable(Operation.RemoveFromArrayByIndex, item.Get()));

            // Loop if another item needs to execute on the same tick.
            rule.ActionSet.AddAction(Element.LoopIfConditionIsTrue());

            // Get the rule.
            DeltinScript.WorkshopRules.Add(rule.GetRule());
        }
Ejemplo n.º 2
0
 public CompletionRange(DeltinScript deltinScript, Scope scope, CodeType getter, DocRange range, CompletionRangeKind kind)
 {
     _deltinScript = deltinScript;
     _scope        = scope ?? throw new ArgumentNullException(nameof(scope));
     _getter       = getter;
     Kind          = kind;
     Range         = range;
 }
Ejemplo n.º 3
0
        private Rule GetStartRule(DeltinScript deltinScript)
        {
            var condition = new Condition(
                Element.Part <V_CountOf>(Path.GetVariable()),
                Operators.GreaterThan,
                0
                );

            Element eventPlayer    = new V_EventPlayer();
            Element eventPlayerPos = Element.Part <V_PositionOf>(eventPlayer);

            TranslateRule rule = new TranslateRule(deltinScript, Constants.INTERNAL_ELEMENT + "Pathfinder: Move", RuleEvent.OngoingPlayer);

            IfBuilder isBetween = new IfBuilder(rule.ActionSet,
                                                Element.Part <V_And>(
                                                    Element.Part <V_CountOf>(Path.GetVariable()) >= 2,
                                                    IsBetween(eventPlayerPos, NextPosition(eventPlayer), PositionAt(eventPlayer, 1))
                                                    )
                                                );

            isBetween.Setup();
            rule.ActionSet.AddAction(Next());
            isBetween.Finish();

            rule.ActionSet.AddAction(ArrayBuilder <Element> .Build
                                     (
                                         LastUpdate.SetVariable(new V_TotalTimeElapsed()),
                                         DistanceToNext.SetVariable(Element.Part <V_DistanceBetween>(Element.Part <V_PositionOf>(new V_EventPlayer()), NextPosition(new V_EventPlayer()))),
                                         // Element.Part<A_StartFacing>(
                                         //     new V_EventPlayer(),
                                         //     Element.Part<V_DirectionTowards>(
                                         //         new V_EyePosition(),
                                         //         NextPosition()
                                         //     ),
                                         //     new V_Number(700),
                                         //     EnumData.GetEnumValue(Relative.ToWorld),
                                         //     EnumData.GetEnumValue(FacingRev.DirectionAndTurnRate)
                                         // ),

                                         // Move to the next node.
                                         Element.Part <A_StartThrottleInDirection>(
                                             new V_EventPlayer(),
                                             Element.Part <V_DirectionTowards>(
                                                 new V_EyePosition(),
                                                 NextPosition(new V_EventPlayer()) // Because of ThrottleRev this will be reevaluated so 'Start Throttle In Direction' only needs to run once.
                                                 ),
                                             new V_Number(1),
                                             EnumData.GetEnumValue(Relative.ToWorld),
                                             EnumData.GetEnumValue(ThrottleBehavior.ReplaceExistingThrottle),
                                             EnumData.GetEnumValue(ThrottleRev.DirectionAndMagnitude)
                                             )
                                     ));

            var result = rule.GetRule();

            result.Conditions = new Condition[] { condition };
            return(result);
        }
Ejemplo n.º 4
0
        public static void Add(DeltinScript deltinScript, Scope scope)
        {
            var functions = GetFunctions(deltinScript);

            foreach (var function in functions)
            {
                scope.AddNativeMethod(function);
            }
        }
Ejemplo n.º 5
0
        public void Init(DeltinScript deltinScript)
        {
            Pathmap     = new PathmapClass(deltinScript);
            PathResolve = new PathResolveClass(deltinScript);
            Bakemap     = new BakemapClass(deltinScript);

            deltinScript.Types.AddType(Pathmap.Provider);
            deltinScript.Types.AddType(PathResolve.Provider);
            deltinScript.Types.AddType(Bakemap.Provider);
        }
        public static void Add(DeltinScript deltinScript, Scope scope)
        {
            var functions = GetFunctions(deltinScript);

            foreach (var function in functions)
            {
                scope.AddNativeMethod(function);
            }
            scope.AddNativeMethod(Parse.Lambda.WaitAsyncComponent.Method(deltinScript.Types));
        }
        public PathfinderInfo(DeltinScript translateInfo)
        {
            Path           = translateInfo.VarCollection.Assign("Pathfinder: Path", false, false);
            LastUpdate     = translateInfo.VarCollection.Assign("Pathfinder: Last Update", false, true);
            DistanceToNext = translateInfo.VarCollection.Assign("Pathfinder: Distance To Next Node", false, true);

            translateInfo.WorkshopRules.Add(GetStartRule(translateInfo));
            translateInfo.WorkshopRules.Add(GetUpdateRule());
            translateInfo.WorkshopRules.Add(GetStopRule());
        }
Ejemplo n.º 8
0
        public static Rule Generate(DeltinScript deltinScript)
        {
            DecompilerMeta obj = new DecompilerMeta()
            {
                ExtendedGlobalVariables = deltinScript.VarCollection.ExtendedVariableList(true).Select(v => v.DebugName).ToArray(),
                ExtendedPlayerVariables = deltinScript.VarCollection.ExtendedVariableList(false).Select(v => v.DebugName).ToArray()
            };

            string json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });
            int start = 0;

            // Split the json into strings that are 256 or less bytes.
            List <string> split = new List <string>();

            for (int i = 0; i < json.Length; i++)
            {
                if (i == json.Length - 1 || Encoding.UTF8.GetByteCount(json, start, i + 1 - start) > 256)
                {
                    split.Add(json.Substring(start, i + 1 - start));
                    start = i;
                }
            }

            // Create the actions.
            List <Element> actions = new List <Element>();

            for (int i = 0; i < split.Count; i++)
            {
                Element element;
                if (i < split.Count - 1)
                {
                    element = new A_Continue();
                }
                else
                {
                    element = new A_End();
                }

                element.Disabled = true;                  // Disable the action.
                element.Comment  = split[i]               // Set the comment.
                                   .Replace("\"", "\\\"") // Escape quotes
                ;

                actions.Add(element);
            }

            // Create and return the generated rule.
            return(new Rule(MetaRuleName)
            {
                Disabled = true, Priority = -1, Actions = actions.ToArray()
            });
        }
 public static FuncMethod Midpoint(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "Midpoint",
     Documentation = "The midpoint between 2 vectors.",
     Parameters    = new[] {
         new CodeParameter("value1", "The first value.", NumberOrVector(deltinScript)),
         new CodeParameter("value2", "The second value.", NumberOrVector(deltinScript))
     },
     ReturnType = NumberOrVector(deltinScript),
     Action     = (actionSet, methodCall) => (methodCall.Get(0) + methodCall.Get(1)) / 2
 };
 public static FuncMethod Destination(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "Destination",
     Documentation = "Calculates a destination given a starting point, distance and direction",
     Parameters    = new[] {
         new CodeParameter("startingPoint", "The starting point.", deltinScript.Types.Vector()),
         new CodeParameter("direction", "The direction to move.", deltinScript.Types.Vector()),
         new CodeParameter("distance", "The distance to move.", deltinScript.Types.Number())
     },
     ReturnType = deltinScript.Types.Vector(),
     Action     = (actionSet, methodCall) => methodCall.Get(0) + methodCall.Get(1) * methodCall.Get(2)
 };
 public static FuncMethod DestroyDummyBot(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "DestroyDummyBot",
     Documentation = "Destroys a dummy bot.",
     Parameters    = new[] {
         new CodeParameter("dummy", "The dummy bot to destroy. A reference to this can be obtained with running LastCreatedEntity() after creating a dummy bot.", deltinScript.Types.Player())
     },
     Action = (actionSet, methodCall) => {
         actionSet.AddAction(Element.Part("Destroy Dummy Bot", Element.Part("Team Of", methodCall.Get(0)), Element.Part("Slot Of", methodCall.Get(0))));
         return(null);
     }
 };
 public void InitStatic()
 {
     foreach (var staticVariable in DeltinScript.GetComponent <StaticVariableCollection>().StaticVariables)
     {
         DeltinScript.DefaultIndexAssigner.Add(
             staticVariable.Provider,
             staticVariable
             .GetAssigner(new GetVariablesAssigner(DeltinScript.InitialGlobal.ActionSet))
             .GetValue(new GettableAssignerValueInfo(DeltinScript.InitialGlobal.ActionSet))
             );
     }
 }
        Unit Update()
        {
            SpinWait.SpinUntil(() => {
                lock (_parseLock) return(_typeWait.ElapsedMilliseconds >= TimeToUpdate);
            });

            lock (_parseLock)
            {
                try
                {
                    Diagnostics diagnostics = new Diagnostics();
                    ScriptFile  root;
                    lock (_parseItemLock) root = new ScriptFile(diagnostics, _parseItem.Uri, _parseItem.Text);
                    DeltinScript deltinScript = new DeltinScript(new TranslateSettings(diagnostics, root, _languageServer.FileGetter)
                    {
                        OutputLanguage = _languageServer.ConfigurationHandler.OutputLanguage,
                        OptimizeOutput = _languageServer.ConfigurationHandler.OptimizeOutput
                    });
                    _languageServer.LastParse = deltinScript;

                    // Publish the diagnostics.
                    var publishDiagnostics = diagnostics.GetDiagnostics();
                    foreach (var publish in publishDiagnostics)
                    {
                        _languageServer.Server.Document.PublishDiagnostics(publish);
                    }

                    if (deltinScript.WorkshopCode != null)
                    {
                        _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendWorkshopCode, deltinScript.WorkshopCode);
                        _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendElementCount, deltinScript.ElementCount.ToString());
                    }
                    else
                    {
                        _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendWorkshopCode, diagnostics.OutputDiagnostics());
                        _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendElementCount, "-");
                    }
                }
                catch (Exception ex)
                {
                    Serilog.Log.Error(ex, "An exception was thrown while parsing.");
                    _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendWorkshopCode, "An exception was thrown while parsing.\r\n" + ex.ToString());
                    _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendElementCount, "-");
                }
                finally
                {
                    _updateTaskIsRunning = false;
                    _typeWait.Stop();
                }
                return(Unit.Value);
            }
        }
Ejemplo n.º 14
0
        public static void Script(string parseFile)
        {
            string       text         = File.ReadAllText(parseFile);
            Diagnostics  diagnostics  = new Diagnostics();
            ScriptFile   root         = new ScriptFile(diagnostics, new Uri(parseFile), text);
            DeltinScript deltinScript = new DeltinScript(new TranslateSettings(diagnostics, root));

            diagnostics.PrintDiagnostics(Log);
            if (deltinScript.WorkshopCode != null)
            {
                WorkshopCodeResult(deltinScript.WorkshopCode);
            }
        }
Ejemplo n.º 15
0
 public static FuncMethod CustomColor(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "CustomColor",
     Documentation = "Custom color with specified rgb and alpha values.",
     ReturnType    = deltinScript.Types.EnumType("Color"),
     Parameters    = new CodeParameter[] {
         new CustomColorParameter(0, "red", "The red component of a color.", deltinScript.Types.Number()),
         new CustomColorParameter(1, "green", "The green component of a color.", deltinScript.Types.Number()),
         new CustomColorParameter(2, "blue", "The blue component of a color.", deltinScript.Types.Number()),
         new CustomColorParameter(3, "alpha", "The alpha component of a color.", deltinScript.Types.Number()),
     },
     OnCall = (parseInfo, callRange) => new CustomColorApplier(parseInfo.Script, callRange),
     Action = (actionSet, methodCall) => Element.Part("Custom Color", methodCall.Get(0), methodCall.Get(1), methodCall.Get(2), methodCall.Get(3))
 };
 public static FuncMethod LinearInterpolate(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "LinearInterpolate",
     Documentation = "Gets a point on a line with a fraction.",
     Parameters    = new[] {
         new CodeParameter("value1", "The first value.", NumberOrVector(deltinScript)),
         new CodeParameter("value2", "The second value.", NumberOrVector(deltinScript)),
         new CodeParameter("fraction", "The fraction. 0 will return the first point, 1 will return the second point, 0.5 will return the midpoint, etc.", deltinScript.Types.Number())
     },
     ReturnType = NumberOrVector(deltinScript),
     Action     = (actionSet, methodCall) => {
         Element p1 = methodCall.Get(0), p2 = methodCall.Get(1), fraction = methodCall.Get(2);
         return((p1 * (1 - fraction)) + (p2 * fraction));
     }
 };
 public static FuncMethod LinearInterpolateDistance(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "LinearInterpolateDistance",
     Documentation = "Gets a point on a line by distance.",
     Parameters    = new[] {
         new CodeParameter("value1", "The first value.", NumberOrVector(deltinScript)),
         new CodeParameter("value2", "The second value.", NumberOrVector(deltinScript)),
         new CodeParameter("distance", "The distance along the line.", deltinScript.Types.Number())
     },
     ReturnType = NumberOrVector(deltinScript),
     Action     = (actionSet, methodCall) => {
         Element p1 = methodCall.Get(0), p2 = methodCall.Get(1), distance = methodCall.Get(2);
         Element fraction = distance / Element.DistanceBetween(p1, p2);
         return(p1 * (1 - fraction) + (p2 * fraction));
     }
 };
Ejemplo n.º 18
0
 public static FuncMethod LinePlaneIntersection(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "LinePlaneIntersection",
     Documentation = "Gets the point where a line intersects with an infinite plane.",
     Parameters    = new[] {
         new CodeParameter("linePos", "A point on the line.", deltinScript.Types.Vector()),
         new CodeParameter("lineDirection", "The directional vector of the line.", deltinScript.Types.Vector()),
         new CodeParameter("planePos", "A position on the plane.", deltinScript.Types.Vector()),
         new CodeParameter("planeNormal", "The normal of the plane.", deltinScript.Types.Vector())
     },
     ReturnType = deltinScript.Types.Vector(),
     Action     = (actionSet, methodCall) => {
         Element linePos = methodCall.Get(0), lineDirection = methodCall.Get(1), planePos = methodCall.Get(2), planeNormal = methodCall.Get(3);
         return(linePos + Element.Normalize(lineDirection) * ((Element.DotProduct(planeNormal, planePos) - Element.DotProduct(planeNormal, linePos)) / Element.DotProduct(planeNormal, Element.Normalize(lineDirection))));
     }
 };
 public PathmapClass(DeltinScript deltinScript) : base("Pathmap")
 {
     DeltinScript      = deltinScript;
     this.Constructors = new Constructor[] {
         new PathmapClassConstructor(this),
         new Constructor(this, null, AccessLevel.Public)
         {
             Documentation = "Creates an empty pathmap."
         }
     };
     Description = new MarkupBuilder()
                   .Add("A pathmap can be used for pathfinding.").NewLine()
                   .Add("Pathmaps are imported from ").Code(".pathmap").Add(" files. These files are generated from an ingame editor. Run the ").Code("Copy Pathmap Editor Code").Add(" command by opening the command palette with ").Code("ctrl+shift+p")
                   .Add(". Paste the rules into Overwatch and select the map the pathmap will be created for.")
                   .ToString();
 }
        public static void FromPathmapFile(string file)
        {
            DeltinScript deltinScript = Generate(file, Pathmap.ImportFromFile(file), OutputLanguage.enUS);

            string code = deltinScript.WorkshopCode;

            if (code != null)
            {
                Program.WorkshopCodeResult(code);
            }
            else
            {
                Log.Write(LogLevel.Normal, new ColorMod("Build Failed.", ConsoleColor.Red));
                deltinScript.Diagnostics.PrintDiagnostics(Log);
            }
        }
 // ResolveTo(position, resolveTo, [attributes])
 private static FuncMethod GetResolveTo(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name            = "ResolveTo",
     Documentation   = "Resolves the path to the specified destination. This can be used to precalculate the path to a position, or to reuse the calculated path to a position.",
     DoesReturnValue = true,
     ReturnType      = deltinScript.Types.GetInstance <PathResolveClass>(),
     Parameters      = new CodeParameter[] {
         new CodeParameter("position", "The position to resolve."),
         new CodeParameter("resolveTo", "Resolving will stop once this position is reached."),
         new CodeParameter("attributes", "The attributes of the path.", new ExpressionOrWorkshopValue(new V_Null()))
     },
     Action = (actionSet, call) => {
         ResolveDijkstra resolve = new ResolveDijkstra(actionSet, (Element)call.ParameterValues[0], ContainParameter(actionSet, "_pathfindDestinationStore", call.ParameterValues[1]), (Element)call.ParameterValues[2]);
         resolve.Get();
         return(resolve.ClassReference.GetVariable());
     }
 };
Ejemplo n.º 22
0
        public static FuncMethod RemoveFromArrayAtIndex(DeltinScript deltinScript) => new FuncMethodBuilder()
        {
            Name          = "RemoveFromArrayAtIndex",
            Documentation = "Removes a value from an array by its index.",
            ReturnType    = deltinScript.Types.AnyArray(),
            Parameters    = new[] {
                new CodeParameter("array", "The array to modify.", deltinScript.Types.AnyArray()),
                new CodeParameter("index", "The index to remove.", deltinScript.Types.Number()),
            },
            Action = (actionSet, methodCall) => {
                Element array = methodCall.Get(0), index = methodCall.Get(1);

                return(Element.Append(
                           Element.Slice(array, Element.Num(0), index),
                           Element.Slice(array, index + 1, Element.Num(Constants.MAX_ARRAY_LENGTH))
                           ));
            }
        };
Ejemplo n.º 23
0
 public static FuncMethod WorkshopSettingHero(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "WorkshopSettingHero",
     Documentation = "Provides the value of a new hero setting that will appear in the Workshop Settings card as a combo box.",
     Parameters    = new CodeParameter[] {
         new ConstStringParameter("category", "The name of the category in which this setting can be found.", deltinScript.Types),
         new ConstStringParameter("name", "The name of this setting.", deltinScript.Types),
         new ConstHeroParameter("default", "The default value for this setting.", deltinScript.Types),
         new ConstNumberParameter("sortOrder", "The sort order of this setting relative to other settings in the same category. Settings with a higher sort order will come after settings with a lower sort order.", deltinScript.Types)
     },
     Action = (actionSet, methodCall) => Element.Part("Workshop Setting Hero",
                                                      Element.CustomString((string)methodCall.AdditionalParameterData[0]),
                                                      Element.CustomString((string)methodCall.AdditionalParameterData[1]),
                                                      new AnonymousWorkshopValue(((ConstHeroValueResolver)methodCall.AdditionalParameterData[2]).Hero, true),
                                                      Element.Num((double)methodCall.AdditionalParameterData[3])
                                                      ),
     ReturnType = ((ITypeSupplier)deltinScript.Types).Hero()
 };
Ejemplo n.º 24
0
 public static FuncMethod WorkshopSettingHero(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "WorkshopSettingHero",
     Documentation = "Provides the value of a new hero setting that will appear in the Workshop Settings card as a combo box.",
     Parameters    = new CodeParameter[] {
         new ConstStringParameter("category", "The name of the category in which this setting can be found."),
         new ConstStringParameter("name", "The name of this setting."),
         new ConstHeroParameter("default", "The default value for this setting."),
         new ConstNumberParameter("sortOrder", "The sort order of this setting relative to other settings in the same category. Settings with a higher sort order will come after settings with a lower sort order.")
     },
     DoesReturnValue = true,
     Action          = (actionSet, methodCall) => Element.Part <V_WorkshopSettingHero>(
         new V_CustomString((string)methodCall.AdditionalParameterData[0]),
         new V_CustomString((string)methodCall.AdditionalParameterData[1]),
         EnumData.GetEnumValue(((ConstHeroValueResolver)methodCall.AdditionalParameterData[2]).Hero),
         new V_Number((double)methodCall.AdditionalParameterData[3])
         )
 };
Ejemplo n.º 25
0
        public static FuncMethod ChaseVariableAtRate(DeltinScript deltinScript) => new FuncMethodBuilder()
        {
            Name          = "ChaseVariableAtRate",
            Documentation = "Gradually modifies the value of a variable at a specific rate.",
            Parameters    = new CodeParameter[] {
                new VariableParameter("variable", "The variable to manipulate. Player variables will chase the event player's variable. Must be a variable defined on the rule level.", VariableType.Dynamic, deltinScript.Types.Any(), new VariableResolveOptions()
                {
                    CanBeIndexed = false, FullVariable = true
                }),
                new CodeParameter("destination", "The value that the variable will eventually reach. The type of this value may be either a number or a vector, through the variable’s existing value must be of the same type before the chase begins. Can use number or vector based values.", NumberOrVector(deltinScript)),
                new CodeParameter("rate", "The amount of change that will happen to the variable’s value each second.", deltinScript.Types.Number()),
                new CodeParameter("reevaluation", "Specifies which of this action's inputs will be continuously reevaluated. This action will keep asking for and using new values from reevaluated inputs.", deltinScript.Types.EnumType("RateChaseReevaluation"))
            },
            Action = (actionSet, methodCall) => {
                VariableElements elements = ((VariableResolve)methodCall.AdditionalParameterData[0]).ParseElements(actionSet);
                WorkshopVariable variable = ((IndexReference)elements.IndexReference).WorkshopVariable;

                Element       destination  = methodCall.Get(1);
                Element       rate         = methodCall.Get(2);
                IWorkshopTree reevaluation = methodCall.ParameterValues[3];

                if (variable.IsGlobal)
                {
                    actionSet.AddAction(Element.Part("Chase Global Variable At Rate",
                                                     variable,
                                                     destination,
                                                     rate,
                                                     reevaluation
                                                     ));
                }
                else
                {
                    actionSet.AddAction(Element.Part("Chase Player Variable At Rate",
                                                     elements.Target,
                                                     variable,
                                                     destination,
                                                     rate,
                                                     reevaluation
                                                     ));
                }

                return(null);
            }
        };
Ejemplo n.º 26
0
        void Update(Document item)
        {
            try
            {
                Diagnostics  diagnostics  = new Diagnostics();
                ScriptFile   root         = new ScriptFile(diagnostics, item);
                DeltinScript deltinScript = new DeltinScript(new TranslateSettings(diagnostics, root, _languageServer.FileGetter)
                {
                    OutputLanguage = _languageServer.ConfigurationHandler.OutputLanguage,
                    OptimizeOutput = _languageServer.ConfigurationHandler.OptimizeOutput
                });
                _languageServer.LastParse = deltinScript;

                if (!_scriptReady.Task.IsCompleted)
                {
                    _scriptReady.SetResult(Unit.Value);
                }

                // Publish the diagnostics.
                var publishDiagnostics = diagnostics.GetDiagnostics();
                foreach (var publish in publishDiagnostics)
                {
                    _languageServer.Server.TextDocument.PublishDiagnostics(publish);
                }

                if (deltinScript.WorkshopCode != null)
                {
                    _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendWorkshopCode, deltinScript.WorkshopCode);
                    _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendElementCount, deltinScript.ElementCount.ToString());
                }
                else
                {
                    _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendWorkshopCode, diagnostics.OutputDiagnostics());
                    _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendElementCount, "-");
                }
            }
            catch (Exception ex)
            {
                Serilog.Log.Error(ex, "An exception was thrown while parsing.");
                _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendWorkshopCode, "An exception was thrown while parsing.\r\n" + ex.ToString());
                _languageServer.Server.SendNotification(DeltintegerLanguageServer.SendElementCount, "-");
            }
        }
Ejemplo n.º 27
0
 public static FuncMethod WorkshopSettingCombo(DeltinScript deltinScript) => new FuncMethodBuilder()
 {
     Name          = "WorkshopSettingCombo",
     Documentation = "Proves the value (a choice of strings) of a new option setting that will appear in the Workshop Seettings card as a combo box. This value returns the index of the selected choice.",
     Parameters    = new CodeParameter[] {
         new ConstStringParameter("category", "The name of the category in which this setting can be found."),
         new ConstStringParameter("name", "The name of this setting."),
         new ConstNumberParameter("default", "The default value for this setting."),
         new ConstStringArrayParameter("options", "The options for this setting."),
         new ConstNumberParameter("sortOrder", "The sort order of this setting relative to other settings in the same category. Settings with a higher sort order will come after settings with a lower sort order.")
     },
     DoesReturnValue = true,
     Action          = (actionSet, methodCall) => Element.Part <V_WorkshopSettingCombo>(
         new V_CustomString((string)methodCall.AdditionalParameterData[0]),
         new V_CustomString((string)methodCall.AdditionalParameterData[1]),
         new V_Number((double)methodCall.AdditionalParameterData[2]),
         Element.CreateArray(((List <string>)methodCall.AdditionalParameterData[3]).Select(a => new V_CustomString(a)).ToArray()),
         new V_Number((double)methodCall.AdditionalParameterData[4])
         )
 };
Ejemplo n.º 28
0
        public static FuncMethod DoesLineIntersectSphere(DeltinScript deltinScript) => new FuncMethodBuilder()
        {
            Name          = "DoesLineIntersectSphere",
            Documentation = "Determines if a point intersects with a sphere.",
            Parameters    = new[] {
                new CodeParameter("linePos", "The starting point of the line", deltinScript.Types.Vector()),
                new CodeParameter("lineDirection", "The direction of the line.", deltinScript.Types.Vector()),
                new CodeParameter("spherePos", "The position of the sphere.", deltinScript.Types.Vector()),
                new CodeParameter("sphereRadius", "The radius of a sphere.", deltinScript.Types.Number())
            },
            ReturnType = deltinScript.Types.Boolean(),
            Action     = (actionSet, methodCall) => {
                Element linePos = methodCall.Get(0), lineDirection = methodCall.Get(1), spherePos = methodCall.Get(2), sphereRadius = methodCall.Get(3);

                Element distanceToSphere = Element.DistanceBetween(linePos, spherePos);
                Element checkPos         = linePos + Element.Normalize(lineDirection) * distanceToSphere;

                return(Element.DistanceBetween(checkPos, spherePos) < sphereRadius);
            }
        };
Ejemplo n.º 29
0
        public static FuncMethod ModifyVariable(DeltinScript deltinScript) => new FuncMethodBuilder()
        {
            Name          = "ModifyVariable",
            Documentation = "Modifies the value of a variable.",
            Parameters    = new CodeParameter[] {
                new VariableParameter("variable", "The variable to modify. Player variables will modify the event player's variable.", deltinScript.Types.Any()),
                new CodeParameter("operation", "The way in which the variable’s value will be changed. Options include standard arithmetic operations as well as array operations for appending and removing values.", deltinScript.Types.EnumType("Operation")),
                new CodeParameter("value", "The value used for the modification. For arithmetic operations, this is the second of two operands, with the other being the variable’s existing value. For array operations, this is the value to append or remove.", deltinScript.Types.Any())
            },
            Action = (actionSet, methodCall) => {
                VariableResolve variableResolve = (VariableResolve)methodCall.AdditionalParameterData[0];
                Operation       operation       = ((ElementEnumMember)methodCall.ParameterValues[1]).GetOperation();
                IWorkshopTree   value           = methodCall.ParameterValues[2];

                VariableElements variableElements = variableResolve.ParseElements(actionSet);

                variableElements.IndexReference.Modify(actionSet, operation, value, variableElements.Target, variableElements.Index);
                return(null);
            }
        };
Ejemplo n.º 30
0
        public static FuncMethod CompareMap(DeltinScript deltinScript) => new FuncMethodBuilder()
        {
            Name          = "CompareMap",
            Documentation = "Compares the current map to a map value. Map variants are considered as well.",
            ReturnType    = deltinScript.Types.Boolean(),
            Parameters    = new[] { new MapParameter(deltinScript.Types) },
            Action        = (actionSet, methodCall) => {
                var     enumData = (ElementEnumMember)methodCall.ParameterValues[0];
                string  map      = enumData.Name;
                MapLink mapLink  = MapLink.GetMapLink(map);

                if (mapLink == null)
                {
                    return(Element.Compare(Element.Part("Current Map"), Operator.Equal, enumData.ToElement()));
                }
                else
                {
                    return(Element.Contains(mapLink.GetArray(), Element.Part("Current Map")));
                }
            }
        };