public static void GenerateSkills(PlayerExporter exporter, CodeGenerator output)
        {
            SkillGeneratorEnv env = (SkillGeneratorEnv)exporter.GenEnv;

            for (int i = 0; i < exporter.Skills.Count; ++i)
            {
                var skill         = exporter.Skills[i];
                var skillFuncName = "skill_" + i.ToString();
                if (skill is NormalSkill)
                {
                    var cskill = (NormalSkill)skill;
                    env.CurrentSkillKeyName = cskill.Key.GetKeyName();
                    env.CurrentActionName   = cskill.ActionID;

                    var functionContent = GenerateNormalSkillFunction(exporter, env, cskill.ActionID, false);
                    functionContent = new ILineObject[] {
                        new ControlBlock(ControlBlockType.If, "!(\"uu\" in this.u)", new ILineObject[] {
                            new SimpleLineObject("this.u.uu <- { uuu = this.u.weakref() };"),
                        }).Statement(),
                    }.Concat(functionContent);

                    var func = new FunctionBlock(skillFuncName, new string[0], functionContent);
                    output.WriteStatement(func.Statement());
                }
            }
        }
Beispiel #2
0
    public T FindStatement <T> (Func <T, bool> predicate) where T : class
    {
        T             statement = null;
        FunctionBlock curBlock  = this;

        while (curBlock != null && statement == null)
        {
            bool found = false;
            for (int i = curBlock.Statements.Count - 1; i >= 0; i--)
            {
                var stmt = curBlock.Statements [i];
                statement = stmt as T;
                if (statement == null)
                {
                    continue;
                }
                if (predicate(statement))
                {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                statement = null;
            }
            curBlock = curBlock.Parent;
        }
        return(statement);
    }
Beispiel #3
0
        public bool CreateBaseInfo(Vector3 blockPos, FunctionBlock blockBase, FunctionBlockModifier modifier)
        {
            BlockID   = blockBase.FunctionBlockID;
            block     = blockBase;
            blockType = FunctionBlockModule.GetFunctionBlockType(BlockID);
            dataModel = new FunctionBlockDataModel();
            dataModel.Create(BlockID);
            BlockPos = blockPos;

            blockModifier          = modifier;
            modifierRootType       = FunctionBlockModule.FetchBlockModifierRootType(blockType);
            districtUnlockDataList = FunctionBlockModule.GetBlockDistrictUnlockData(blockBase.FunctionBlockID);

            levelInfo = new FunctionBlockLevelInfo(blockBase);

            //District



            //Set active district build
            for (int i = 0; i < districtUnlockDataList.Count; i++)
            {
                if (districtUnlockDataList[i].UnlockDefault == true)
                {
                    ActiveDistrictBuildList.Add(DistrictModule.GetDistrictDataByKey(districtUnlockDataList[i].DistrictID));
                }
            }
            //TODO
            return(true);
        }
Beispiel #4
0
        public void InitData(int blockID, int posX, int posZ)
        {
            functionBlock = FunctionBlockModule.GetFunctionBlockByBlockID(blockID);

            UIinfo = UIUtility.SafeGetComponent <BlockUIScriptInfo>(transform);
            UIinfo.SetData(this);
            ModelRoot       = UIUtility.FindTransfrom(transform, "Root/ModelRoot").gameObject;
            gameObject.name = instanceID + "[Block]";

            SetPosition(new Vector3(posX, transform.localScale.y / 2, posZ));
            info = new FunctionBlockInfoData();
            info.CreateBaseInfo(transform.position, functionBlock,
                                new FunctionBlockModifier(ModifierTarget.FunctionBlock, instanceID));

            var blockType = info.dataModel.BlockType;

            if (blockType == FunctionBlockType.ElementCapsule)
            {
                var manuBase = transform.SafeAddCmpt <ManufactoryBase>();
                manuBase.SetData();
            }
            else if (blockType == FunctionBlockType.EnergyStorageUnit)
            {
                var normalBase = transform.SafeAddCmpt <BlockNormalBase>();
                normalBase.SetData();
            }

            InitBase();
        }
            public string GenerateActionAsActorInit(string name)
            {
                string ret;

                if (_GeneratedActorInit.TryGetValue(name, out ret))
                {
                    return(ret);
                }

                var action = Exporter.GetAction(name);

                var lastActionName = CurrentActionName;

                CurrentActionName = name;
                List <ILineObject> funcContent = new List <ILineObject>();

                funcContent.AddRange(GenerateNormalSkillFunction(Exporter, this, name, true));
                CurrentActionName = lastActionName;

                ret = "InitAction_" + name;
                var func = new FunctionBlock(ret, new string[] { "t" }, funcContent);

                Output.WriteStatement(func.Statement());

                _GeneratedActorInit.Add(name, ret);
                return(ret);
            }
Beispiel #6
0
    public override void Construction()
    {
        AllFunctionBlockList = new List <FunctionBlock>();
        for (int i = 0; i < 2; i++)
        {
            FunctionBlock fac = new FunctionBlock();
            fac.FunctionBlockID   = i;
            fac.BlockName         = "";
            fac.BlockBG           = "";
            fac.BlockIcon         = "";
            fac.BlockDesc         = "";
            fac.PreLevelBlock     = i;
            fac.FunctionBlockType = "";
            AllFunctionBlockList.Add(fac);
        }

        AllFunctionBlockTypeDataList = new List <FunctionBlockTypeData>();
        for (int i = 0; i < 2; i++)
        {
            FunctionBlockTypeData type = new FunctionBlockTypeData();
            type.Type        = "";
            type.DefaultShow = true;
            type.TypeName    = "";
            type.TypeDesc    = "";
            type.TypeIcon    = "";
            AllFunctionBlockTypeDataList.Add(type);
        }
    }
Beispiel #7
0
    public override void Interpret(Expression[] args, FunctionBlock block, Type contextType, string exprVal, out string newExprVal, out FunctionBlock newCurBlock, out Type newContextType, bool isLast)
    {
        var thisVar = block.FindStatement <DeclareVariableStatement> (v => v.IsContext && !v.IsTemp);

        newExprVal     = thisVar.Name;
        newCurBlock    = block;
        newContextType = thisVar.Type;
    }
Beispiel #8
0
    public Operator InterpretScope(Scope scope, FunctionBlock block)
    {
        Operator op = new Operator();

        op.Identifier = scope;
        op.Context    = new Context();

        return(op);
    }
Beispiel #9
0
    public Expr InterpretClosure(Expression expression, FunctionBlock block, Type closureType)
    {
        //Debug.LogFormat ("Interpret {0} as closure", expression);
        StringBuilder closureBuilder = new StringBuilder();
        var           methodInfo     = closureType.GetMethod("Invoke");
        var           args           = methodInfo.GetParameters();
        FunctionBlock lambdaBlock    = new FunctionBlock(block, block.Method, block.Type);

        if (args.Length > 0)
        {
            lambdaBlock.DefaultScope = args[0].Name;
        }
        else
        {
            lambdaBlock.DefaultScope = block.FindStatement <DeclareVariableStatement>(v => v.Type == typeof(GameObject) && v.IsContext && !v.IsTemp).Name;
        }
        closureBuilder.Append("(");
        DeclareVariableStatement lastArg = null;

        foreach (var param in args)
        {
            var argVar = new DeclareVariableStatement();
            lastArg      = argVar;
            argVar.Name  = param.Name;
            argVar.IsArg = true;
            argVar.Type  = param.ParameterType;
            lambdaBlock.Statements.Add(argVar);
            closureBuilder.Append(param.ParameterType).Append(" ").Append(param.Name).Append(",");
        }
        if (lastArg != null)
        {
            lastArg.IsContext = true;
        }
        if (closureBuilder [closureBuilder.Length - 1] == ',')
        {
            closureBuilder.Length -= 1;
        }
        closureBuilder.Append(")=>{");
        var internals = InterpretExpression(expression, lambdaBlock);

        foreach (var statement in lambdaBlock.Statements)
        {
            closureBuilder.Append(statement).Append(";").Append(Environment.NewLine);
        }
        if (methodInfo.ReturnType != null)
        {
            closureBuilder.Append("return ");
        }
        closureBuilder.Append(internals.ExprString).Append(";");
        closureBuilder.Append("}");

        return(new Expr()
        {
            ExprString = closureBuilder.ToString()
        });
        //return InterpretExpression (expression, block);
    }
Beispiel #10
0
    public override void Interpret(Expression[] args, FunctionBlock block, Type contextType, string exprVal, out string newExprVal, out FunctionBlock newCurBlock, out Type newContextType, bool isLast)
    {
        var valueExpr = args [0];
        var exprData  = Engine.GetPlugin <ExpressionInterpreter> ().InterpretExpression(valueExpr, block);

        newExprVal     = exprData.ExprString;
        newCurBlock    = block;
        newContextType = exprData.Type;
    }
Beispiel #11
0
    public override void Interpret(Expression[] args, FunctionBlock block, Type contextType, string exprVal, out string newExprVal, out FunctionBlock newCurBlock, out Type newContextType, bool isLast)
    {
        var retVar = block.FindStatement <DeclareVariableStatement> (v => v.IsReturn);

        newExprVal = retVar.Name;
        block.Statements.Add(String.Format("{0} = true;", retVar.Name));
        newCurBlock    = block;
        newContextType = typeof(bool);
    }
Beispiel #12
0
        /**
         * Create a new function, and use the provided block to fill it with code.
         */
        public MethodInfo CreateFunction(string name, FunctionBlock block)
        {
            var generator = CreateFunctionGenerator(name, false);

            block(generator, generator.InitialSourceReference, generator.InitialContext, generator.InitialSelfFrame, generator.InitialContainerFrame);
            generator.GenerateSwitchBlock();

            return(generator.Initialiser);
        }
Beispiel #13
0
    void Awake()
    {
        origin              = GetComponent <Transform> ();
        circCol             = GetComponent <CircleCollider2D> ();
        parentFunctionBlock = GetComponentInParent <FunctionBlock> ();

        GameObject.FindGameObjectWithTag("funcBlockPanel");
        splitter = GameObject.FindGameObjectWithTag("splitter").GetComponent <BoxCollider2D>();
    }
Beispiel #14
0
 public Expr InterpretExpression(Expression expression, FunctionBlock block, Type type)
 {
     if (type.IsSubclassOf(typeof(Delegate)))
     {
         return(InterpretClosure(expression, block, type));
     }
     else
     {
         return(InterpretExpression(expression, block));
     }
 }
Beispiel #15
0
        public static FunctionBlock GetFunctionBlockByBlockID(int functionBlockID)
        {
            FunctionBlock functionBlock = null;

            FunctionBlockDic.TryGetValue(functionBlockID, out functionBlock);
            if (functionBlock == null)
            {
                Debug.LogError("Get FunctionBlock Error , ID=" + functionBlockID);
            }
            return(functionBlock);
        }
    public override void Interpret(Expression[] args, CodeMemberMethod filterFunction)
    {
        if (args != null)
        {
            Debug.Log("Somehow has component filter has arguments");
        }
        FunctionBlock block = new FunctionBlock(null, filterFunction, null);
        var           expr  = Engine.GetPlugin <ExpressionInterpreter> ().InterpretExpression(args [0], block);

        filterFunction.Statements.Add(new CodeSnippetStatement(String.Format(expr.ExprString, expr.ExprString)));
        //filterFunction.Statements.Add ();
    }
 public override void Interpret(Operator op, FunctionBlock block)
 {
     try
     {
         block.Statements.Add(String.Format("{0} = {1};", Var.Name, Inter.InterpretExpression(op.Context as Expression, block).ExprString));
     }
     catch (Exception e)
     {
         Debug.LogFormat("Something gone wrong in {0} with the variable operator {1}, {2}, {3}", block, op, Var, Inter);
         Debug.LogError(e);
     }
 }
Beispiel #18
0
    public override void Interpret(Operator op, FunctionBlock block)
    {
        if (exprInterpreter == null)
        {
            exprInterpreter = Engine.GetPlugin <ExpressionInterpreter> ();
            ops             = Engine.GetPlugin <EventFunctionOperators> ();
        }
        if (op.Args.Count == 1)
        {
            //Shouldn't declare variable
            IfStatement ifStatement = new IfStatement();
            ifStatement.CheckExpression = exprInterpreter.InterpretExpression(op.Args [0], block).ExprString;
            ifStatement.TrueBlock       = new FunctionBlock(block, block.Method, block.Type);

            block.Statements.Add(ifStatement);
            foreach (var entry in (op.Context as Context).Entries)
            {
                var subOp = entry as Operator;
                if (subOp == null)
                {
                    continue;
                }
                var subInter = ops.GetInterpreter(subOp, ifStatement.TrueBlock);
                if (subInter == null)
                {
                    Debug.LogFormat("Can't interpret operator {0} in {1}", subOp.Identifier, block.Method.Name);
                    continue;
                }
                subInter.Interpret(subOp, ifStatement.TrueBlock);
            }
        }
        else if (op.Args.Count == 2)
        {
            DeclareVariableStatement declareVar = new DeclareVariableStatement();
            if (op.Args [1].Operands [0] is IdWrapper)
            {
                var id = ((IdWrapper)op.Args [1].Operands [0]).ToString();
                declareVar.Name           = id;
                declareVar.Type           = typeof(bool);
                declareVar.InitExpression = "false";
            }
            else
            {
                Debug.Log("Wrong definition of an if operator with a variable - variable is not an identifier");
                return;
            }

            block.Statements.Add(declareVar);

            //Should declare variable
        }
    }
        public void UndeclaredSetTargetsWithinFunctionsAreScopeRestrictedToThatFunction()
        {
            // The ValueSettingStatementsTranslator wasn't using the ScopeAccessInformation's GetNameOfTargetContainerIfAnyRequired extension method and
            // was incorrectly applying the logic that it should have gotten for free by using that method - if an undeclared variable was being accessed
            // within a method (for the to-set target) then it was being mapped back to the "Environment References" class instead of being treated as
            // local to the function.
            var expressionToSet = new Expression(new IToken[]
            {
                new NameToken("a", 0)
            });
            var expressionToSetTo = new Expression(new IToken[]
            {
                new NumericValueToken("1", 0)
            });
            var valueSettingStatement = new ValueSettingStatement(
                expressionToSet,
                expressionToSetTo,
                ValueSettingStatement.ValueSetTypeOptions.Let
                );

            var containingFunction = new FunctionBlock(
                isPublic: true,
                isDefault: false,
                name: new NameToken("F1", 0),
                parameters: new AbstractFunctionBlock.Parameter[0],
                statements: new[] { valueSettingStatement }
                );

            var expected = new TranslatedStatementContentDetails(
                "a = (Int16)1",
                new NonNullImmutableList <NameToken>(new[] { new NameToken("a", 0) })
                );
            var scopeAccessInformation = GetEmptyScopeAccessInformation();

            scopeAccessInformation = new ScopeAccessInformation(
                containingFunction,   // parent
                containingFunction,   // scopeDefiningParent
                new CSharpName("F1"), // parentReturnValueName
                scopeAccessInformation.ErrorRegistrationTokenIfAny,
                scopeAccessInformation.DirectedWithReferenceIfAny,
                scopeAccessInformation.ExternalDependencies,
                scopeAccessInformation.Classes,
                scopeAccessInformation.Functions.Add(new ScopedNameToken("F1", 0, ScopeLocationOptions.WithinFunctionOrPropertyOrWith)),
                scopeAccessInformation.Properties,
                scopeAccessInformation.Constants,
                scopeAccessInformation.Variables,
                scopeAccessInformation.StructureExitPoints
                );
            var actual = GetDefaultValueSettingStatementTranslator().Translate(valueSettingStatement, scopeAccessInformation);

            Assert.Equal(expected, actual, new TranslatedStatementContentDetailsComparer());
        }
Beispiel #20
0
    public override void Interpret(Expression[] args, FunctionBlock block, Type contextType, string exprVal, out string newExprVal, out FunctionBlock newCurBlock, out Type newContextType, bool isLast)
    {
        if (ScriptEngine.AnalyzeDebug)
        {
            Debug.Log("fit scope");
        }
        IfStatement ifStatement = new IfStatement();
//		DeclareVariableStatement cmpStmt = new DeclareVariableStatement ();
//		ExprInter.CleanUpContextes.Add (cmpStmt);
//		cmpStmt.Name = "cmp" + DeclareVariableStatement.VariableId++;
//		cmpStmt.Type = Type;
        //cmpStmt.IsContext = true;
        string varName = block.FindStatement <DeclareVariableStatement> (v => v.IsContext).Name;
//		cmpStmt.InitExpression = String.Format ("{0}.GetComponent<{1}>()", varName, Type);
//		ifStatement.CheckExpression = String.Format ("{0} != null", cmpStmt.Name);
        FunctionBlock newBlock = new FunctionBlock(block, block.Method, block.Type);

        DeclareVariableStatement ifValue = new DeclareVariableStatement();

        ifValue.Name   = "ifResult" + DeclareVariableStatement.VariableId++;
        ifValue.IsTemp = true;
        ifValue.Type   = typeof(bool);
        block.Statements.Add(ifValue);
        ifStatement.CheckExpression = (ifValue.Name + " = ") + ExprInter.InterpretExpression(args [0], block).ExprString;

        ifStatement.TrueBlock = newBlock;
        //block.Statements.Add (cmpStmt);
        block.Statements.Add(ifStatement);
        newCurBlock    = newBlock;
        newExprVal     = exprVal;
        newContextType = contextType;
        if (isLast)
        {
            var res = block.FindStatement <DeclareVariableStatement> (v => v.IsResult);
            if (res != null)
            {
                res.Type           = typeof(List <>).MakeGenericType(contextType);
                res.InitExpression = String.Format("new {0}()", TypeName.NameOf(res.Type));
                newExprVal         = res.Name;
                newBlock.Statements.Add(String.Format("{0}.Add({1});", res.Name, varName));
            }
            else
            {
                newExprVal     = ifValue.Name;
                newContextType = typeof(bool);
            }
        }

        //ifStatement.CheckExpression = String.Format("{0}.GetComponen")
        //ifStatement.CheckExpression =
    }
Beispiel #21
0
    public Expr InterpretScopedList(Scope scope, FunctionBlock block)
    {
        FunctionBlock listBlock = new FunctionBlock(block, block.Method, block.Type);

        block.Statements.Add(listBlock);
        var listVar = new DeclareVariableStatement();

        listVar.Name = "scopedList" + DeclareVariableStatement.VariableId++;
        //listVar.InitExpression =



        return(new Expr());
    }
Beispiel #22
0
    public override void Interpret(Operator op, FunctionBlock block)
    {
        DeclareVariableStatement stmt = new DeclareVariableStatement();

        stmt.Name = op.Identifier as string;
        var expr = Inter.InterpretExpression(op.Context as Expression, block);

        stmt.InitExpression = expr.ExprString;
        stmt.Type           = expr.Type;
        if (ScriptEngine.AnalyzeDebug)
        {
            Debug.Log(stmt);
        }
        block.Statements.Add(stmt);
    }
Beispiel #23
0
 public FunctionBlock(FunctionBlock parent)
 {
     if (parent == null)
     {
         Ident = 3;
     }
     else
     {
         Ident = parent.Ident + 1;
     }
     Parent       = parent;
     Method       = parent.Method;
     Type         = parent.Type;
     DefaultScope = parent.DefaultScope;
 }
Beispiel #24
0
    void AddFcnBlockToUI(FunctionBlock block, Transform parent)
    {
        Transform spawnedBlock = Instantiate(block.BlockPrefab, parent).transform;

        spawnedBlock.name = block.Name;
        spawnedBlock.GetChild(0).GetComponent <Text>().text = block.Name;
        //Debug.Log(block.GetType());
        if (block.GetType() == typeof(FcnFolder))
        {
            FcnFolder folder = block as FcnFolder;
            foreach (FunctionBlock insideBlock in folder.functionBlocks)
            {
                AddFcnBlockToUI(insideBlock, spawnedBlock);
            }
        }
    }
Beispiel #25
0
        public ManufactoryInfo(FunctionBlock block)
        {
            var config = Config.ConfigData.BlockConfigData.configData.Find(x => x.configName == block.BlockConfig);

            if (config != null)
            {
                if (config.manuConfig == null)
                {
                    Debug.LogError("ManuConfig is null! configName= " + config.configName);
                    return;
                }
                AddWorkerNum(config.manuConfig.workBase);
                AddEnergyCostNormal(config.manuConfig.energyConsumptionBase);
                AddMaintain(config.manuConfig.maintainBase);
                AddCurrentSpeed((float)config.manuConfig.speedBase);
            }
        }
Beispiel #26
0
    public void TransformScopedOperator(Operator op, FunctionBlock block)
    {
        var      scope      = op.Identifier as Scope;
        var      endContext = op.Context;
        Operator curOp      = null;

        for (int i = 0; i < scope.Parts.Count; i++)
        {
            var      part  = scope.Parts [i];
            Operator subOp = new Operator();
            if (part is string)
            {
                var opId = part as string;
                subOp.Identifier = opId;
            }
            else
            {
                var call = part as FunctionCall;
                subOp.Identifier = call.Name;
                subOp.Args       = new List <Expression> ();
                for (int j = 0; j < call.Args.Length; j++)
                {
                    subOp.Args.Add(call.Args [j]);
                }
            }
            if (curOp == null)
            {
                op.Args       = subOp.Args;
                op.Context    = subOp.Context;
                op.Identifier = subOp.Identifier;
                curOp         = op;
            }
            else
            {
                var ctx = new Context();
                curOp.Context = ctx;
                ctx.Entries.Add(subOp);
                curOp = subOp;
            }



            subOp.Init();
        }
        curOp.Context = endContext;
    }
Beispiel #27
0
 public FunctionBlock(FunctionBlock parent, CodeMemberMethod method, CodeTypeDeclaration type)
 {
     if (parent == null)
     {
         Ident = 3;
     }
     else
     {
         Ident = parent.Ident + 1;
     }
     Parent = parent;
     Method = method;
     Type   = type;
     if (parent != null)
     {
         DefaultScope = parent.DefaultScope;
     }
 }
Beispiel #28
0
        public ManufactFormulaInfo(int currentFormulaID, FunctionBlock block)
        {
            CurrentFormulaID   = currentFormulaID;
            FormulaChooseList  = FunctionBlockModule.GetBlockFormulaList(block.FunctionBlockID);
            currentFormulaData = FormulaModule.GetFormulaDataByID(currentFormulaID);
            currentInputItem   = FormulaModule.GetFormulaItemList(currentFormulaID, FormulaModule.MaterialProductType.Input);
            currentOutputItem  = FormulaModule.GetFormulaOutputMaterial(currentFormulaID);
            currentEnhanceItem = FormulaModule.GetFormulaEnhanceMaterial(currentFormulaID);
            MaxNeedTime        = currentFormulaData.ProductSpeed;

            for (int i = 0; i < currentInputItem.Count; i++)
            {
                realInputItem.Add(new FormulaItem(currentInputItem[i].model, 0));
            }

            realOutputItem  = new FormulaItem(currentOutputItem.model, 0);
            realEnhanceItem = new FormulaItem(currentEnhanceItem.model, 0);
            NotChoose       = false;
        }
        public override ILineObject Generate(GenerationEnvironment env)
        {
            var func = new FunctionBlock("", new string[0], new ILineObject[] { Effect.Generate(env) });

            switch (Label)
            {
            case Simulation.ActorLabelType.Fall:
                return(ThisExpr.Instance.MakeIndex("fallLabel").Assign(func.AsExpression()).Statement());

            case Simulation.ActorLabelType.Sit:
                return(ThisExpr.Instance.MakeIndex("sitLabel").Assign(func.AsExpression()).Statement());

            case Simulation.ActorLabelType.Hit:
                return(ThisExpr.Instance.MakeIndex("hitEvent").Assign(func.AsExpression()).Statement());

            default:
                throw new Exception();
            }
        }
Beispiel #30
0
 public override void Interpret(Operator op, FunctionBlock block)
 {
     if (exprInter == null)
     {
         exprInter = Engine.GetPlugin <ExpressionInterpreter>();
     }
     if (op.Args.Count == 2)
     {
         block.Method.ReturnType = new CodeTypeReference(typeof(IEnumerator));
         block.Method.Attributes = MemberAttributes.Public;
         block.Method.Name       = "ActionCoroutine";
         if (!block.Method.UserData.Contains("has_transformed_action"))
         {
             var newActionMethod = new CodeMemberMethod();
             newActionMethod.Name       = "Action";
             newActionMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
             newActionMethod.Statements.Add(new CodeSnippetStatement("Coroutine = ActionCoroutine(); state = ActionState.Started;"));
             block.Type.Members.Add(newActionMethod);
             block.Method.UserData.Add("has_transformed_action", "has_transformed_action");
         }
         var    whileArg       = exprInter.InterpretExpression(op.Args[0], block);
         var    failArg        = exprInter.InterpretExpression(op.Args[1], block);
         string operatorString = null;
         operatorString = string.Format("while({0}){{ if({1}) {{ this.state = EventAction.ActionState.Failed; yield break; }} yield return null; }}",
                                        whileArg.ExprString, failArg.ExprString);
         if (op.Context is Expression)
         {
             var timeArg = exprInter.InterpretExpression(op.Context as Expression, block);
             if (timeArg.Type != typeof(bool))
             {
                 operatorString =
                     string.Format("float time{2} = UnityEngine.Time.realtimeSinceStartup; while({0}){{ if ((UnityEngine.Time.RealtimeSinceStartup - time{2} > {3}) || ({1})) {{ this.state = EventAction.ActionState.Failed; yield break; }} yield return null; }}",
                                   whileArg.ExprString, failArg.ExprString, DeclareVariableStatement.VariableId++, timeArg.ExprString);
             }
         }
         if (operatorString != null)
         {
             block.Statements.Add(operatorString);
         }
     }
 }
Beispiel #31
0
        private List<int> colorFunction(FunctionBlock<SparcInstruction> f)
        {
            var uncolorableRegs = new List<int>();

            var dg = allDepGraphs[f];
            var map = colorMapping[f.Name];

            var stack = new Stack<NodeAndEdges>(numRegs);

            var notConstrained = Enumerable.Range(0, numRegs).Where(r => !isConstrained(r, dg[r])).ToList();
            var constrained = Enumerable.Range(0, numRegs).Where(r => isConstrained(r, dg[r])).ToList();
            var constrainedAndUncolorable = new List<int>(constrained);

            //Push all unconstrained nodes first
            foreach (var r in notConstrained)
            {
                var bits = dg[r];

                stack.Push(new NodeAndEdges() { Reg = r, Edges = new BitArray(bits) });
                removeEdges(dg, r, bits);
            }

            //Console.WriteLine("\t{0}:{1} reg constr", f.Name, constrained.Count);

            //While there still exists constrained registers
            while (constrained.Count != 0)
            {
                var constrainedNdx = constrained.MaxIndex(r => dg[r].NumberOfBitsSet());
                var reg = constrained[constrainedNdx];
                var bits = dg[reg];

                stack.Push(new NodeAndEdges() { Reg = reg, Edges = new BitArray(bits) });
                removeEdges(dg, reg, bits);

                constrained.Remove(reg);
            }

            while (stack.Count != 0)
            {
                var val = stack.Pop();
                var bits = val.Edges;
                SparcRegister reg = getSparcRegister(val.Reg);

                if (reg == null)
                {
                    var cans = new BitArray(candidateColors);
                    for (int i = 0; i < bits.Length; i++)
                    {
                        if (bits[i])
                            cans[map[i].IntVal] = false;
                    }
                    reg = virtToSparc[cans.FirstTrueIndex()];
                }

                if (reg == null)
                {
                    break;
                }

                constrainedAndUncolorable.Remove(val.Reg);

                map[val.Reg] = reg;
                addEdges(dg, val.Reg, bits);
            }

            constrainedAndUncolorable.Sort((r1, r2) => compareConstrainedness(dg, r1, r2));
            return constrainedAndUncolorable;
        }