private static LoopNode <int>[] GetArray(LinkedLoop <int> list) { var node = list.first; var items = new LoopNode <int> [list.size]; for (int i = 0; i < list.size; i++) { items[i] = node; node = node.next; } return(items); }
/// <summary> /// Create json string from LoopNode. /// </summary> /// <param name="node"></param> /// <returns></returns> public static string ToJson(this LoopNode node) { return(Object(null, true, Field("type", node.NodeName), Field("ID", node.Id), Field("functionID", node.FuncIndex), //Field("functionName", node.FuncNames[node.FuncIndex]), Field("functionName", node.ConditionGroup != ConditionGroup.Time ? node.FunctionName : node.FormattedTime), Field("conditionGroup", node.ConditionGroup), Field("reverse", node.Reverse), Field("minTime", node.MinTime), Field("maxTime", node.MaxTime), node.Rect.ToJson())); }
public void Visit(LoopNode node) { AddInstruction(OpCode.EVAL, 1); int loc = CurrentLoc; var jf = AddInstruction(OpCode.JF, 1); foreach (var child in node.Nodes) { child.Accept(this); } AddInstruction(OpCode.JUMP, loc); jf.Argument = NextLoc; }
/// <summary> /// Create LoopNode from json string. /// </summary> /// <param name="node"></param> /// <param name="jObj"></param> /// <returns></returns> private static Node Serialize(this LoopNode node, JsonObject jObj) { node.NodeName = jObj["type"].String; node.Id = jObj["ID"].String; //node.FuncIndex = jObj["functionID"].Int; node.ConditionGroup = jObj["conditionGroup"].ConditionGroup; node.FuncNames = AgentFunctions.GetConditionStrings(node.ConditionGroup); try { node.FunctionName = jObj["functionName"].String; } catch (Exception) { /*Debug.Log("Your behaviour has a deprecated format");*/ } try { node.MinTime = jObj["minTime"].Float; node.MaxTime = jObj["maxTime"].Float; } catch (Exception) { /*Debug.Log("Your behaviour has a deprecated format");*/ } var sortedFunctions = node.FuncNames; System.Array.Sort(sortedFunctions, StringComparer.InvariantCulture); if (node.FunctionName != null) { for (var i = 0; i < node.FuncNames.Length; i++) { if (node.FuncNames[i] == node.FunctionName) { node.FuncIndex = i; } } } if (node.FuncIndex == -1) { node.FuncIndex = jObj["functionID"].Int; } node.Reverse = jObj["reverse"] != null && jObj["reverse"].Bool; var x = jObj["rect"]["posX"].Float; var y = jObj["rect"]["posY"].Float; var w = jObj["rect"]["width"].Float; var h = jObj["rect"]["height"].Float; node.Rect = new Rect(x, y, w, h); return(node); }
public void Move(int step) { if (step < 0) { throw new ArgumentOutOfRangeException("step", "setp < 0"); } if (tail == null) { throw new NullReferenceException("集合中元素为空!"); } for (int i = 0; i < step; i++) { prev = prev.next; } }
public override string ToString() { if (tail == null) { return(string.Empty); } string s = string.Empty; LoopNode temp = tail.next; for (int i = 0; i < _count; i++) { s += temp.ToString() + " "; temp = temp.next; } return(s); }
/** * Recursive method which executes a node but the node method might execute its own nodes first */ private INode Execute(INode node) { try { return(node switch { DeclareIntVarNode declarerNode => declarerNode.Execute(declarerNode.Left as ReferenceNode, Execute(declarerNode.Right) as IntNode), IntOpNode opNode => opNode.Execute(Execute(opNode.Left) as IntNode, Execute(opNode.Right) as IntNode), ReferenceNode identity => new IntNode(identity.Value), FuncCallNode call => ExecuteFunctionCall(call), IntNode intNode => intNode, MethodNode method => ExecuteDeclareMethod(method), LoopNode loop => ExecuteLoopNode(loop), ConditionalNode conditional => ExecuteConditional(conditional), _ => new IntNode(-1) }); }
/// <summary> /// 增加元素 /// </summary> /// <param name="value"></param> public void Add(object value) { LoopNode node = new LoopNode(value); if (tail == null) { tail = node; tail.next = node; prev = node; } else { node.next = tail.next; tail.next = node; if (prev == tail) { prev = node; } tail = node; } this._count++; }
/// <summary> /// 删除当前元素 /// </summary> public void RemoveCurrNode() { //为空 if (tail == null) { throw new NullReferenceException("集合中元素为空!"); } else if (_count == 1) { tail = null; prev = null; } else { if (prev.next == tail) { tail = prev; } prev.next = prev.next.next; } _count--; }
public override void VisitLoopNode(LoopNode node) { node.Count.Visit(this); var counterVar = VariableDeclarator("#loopCounter" + (++loopCountInd)); var counterId = IdentifierName("#loopCounter" + loopCountInd); blocks.Push(Block()); if (node.Statement is BlockNode) { (node.Statement as BlockNode).Statements.ForEach(st => st.Visit(this)); } else { node.Statement.Visit(this); } var forCondition = GetNodeWithAnnotation(BinaryExpression( SyntaxKind.LessThanExpression, counterId, expressions.Pop() ), node.Count.Location) as ExpressionSyntax; var @for = ForStatement(blocks.Pop() as BlockSyntax) .WithDeclaration( VariableDeclaration(ParseTypeName("long")) .AddVariables(counterVar.WithInitializer(EqualsValueClause( LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)) ))) ) .WithCondition(forCondition) .AddIncrementors(PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, counterId)); @for = GetNodeWithAnnotation(@for, node.Location) as ForStatementSyntax; AddStatementToCurrentBlock(@for); }
private static BaseNode __addNode(NodeType node_type, Vector2 mousePosition) { BaseNode node = null; switch (node_type) { case NodeType.BehaviourNode: node = new BehaviourNode(); node.Init(mousePosition, OnClickNode); NodeDataManager.CreateNodeData <BaseNodeData>(node); nodes_list.Add(node); break; case NodeType.ExcelNode: node = new ExcelNode(); node.Init(mousePosition, OnClickNode); NodeDataManager.CreateNodeData <ExcelNodeData>(node); nodes_list.Add(node); break; case NodeType.ActionNode: node = new ActionNode(); node.Init(mousePosition, OnClickNode); NodeDataManager.CreateNodeData <BaseNodeData>(node); nodes_list.Add(node); break; case NodeType.ConditionNode: node = new ConditionNode(); node.Init(mousePosition, OnClickNode); NodeDataManager.CreateNodeData <BaseNodeData>(node); nodes_list.Add(node); break; case NodeType.WaitNode: node = new WaitNode(); node.Init(mousePosition, OnClickNode); NodeDataManager.CreateNodeData <BaseNodeData>(node); nodes_list.Add(node); break; case NodeType.SequenceNode: node = new SequenceNode(); node.Init(mousePosition, OnClickNode); NodeDataManager.CreateNodeData <BaseNodeData>(node); nodes_list.Add(node); break; case NodeType.SelectorNode: node = new SelectorNode(); node.Init(mousePosition, OnClickNode); NodeDataManager.CreateNodeData <BaseNodeData>(node); nodes_list.Add(node); break; case NodeType.LoopNode: node = new LoopNode(); node.Init(mousePosition, OnClickNode); NodeDataManager.CreateNodeData <BaseNodeData>(node); nodes_list.Add(node); break; } if (node != null && nodes_list.Count == 1) { rootNode = node; } return(node); }
public INode GenerateTree(IParseTree tree, Declaration declaration) { INode node = default; switch (tree) { case VBAParser.ForNextStmtContext _: case VBAParser.ForEachStmtContext _: case VBAParser.WhileWendStmtContext _: case VBAParser.DoLoopStmtContext _: node = new LoopNode(tree); break; case VBAParser.IfStmtContext _: case VBAParser.ElseBlockContext _: case VBAParser.ElseIfBlockContext _: case VBAParser.SingleLineIfStmtContext _: case VBAParser.SingleLineElseClauseContext _: case VBAParser.CaseClauseContext _: case VBAParser.CaseElseClauseContext _: node = new BranchNode(tree); break; case VBAParser.BlockContext _: node = new BlockNode(tree); break; } if (declaration.Context == tree) { node = new DeclarationNode(tree) { Declaration = declaration }; } var reference = declaration.References.SingleOrDefault(w => w.Context == tree); if (reference != null) { if (reference.IsAssignment) { node = new AssignmentNode(tree) { Reference = reference }; } else { node = new ReferenceNode(tree) { Reference = reference }; } } if (node == null) { node = new GenericNode(tree); } var children = new List <INode>(); for (var i = 0; i < tree.ChildCount; i++) { var nextChild = GenerateTree(tree.GetChild(i), declaration); nextChild.SortOrder = i; nextChild.Parent = node; if (nextChild.Children.Any() || nextChild.GetType() != typeof(GenericNode)) { children.Add(nextChild); } } node.Children = children.ToImmutableList(); return(node); }
public List <KeyValuePair <Type, object> > dfs(BaseNode node) { if (node.GetType() == typeof(LiteralNode)) { LiteralNode n = (LiteralNode)node; if (n.type == LiteralType.Func) { return(dfs((FuncLiteral)n.Value)); } else if (n.type == LiteralType.Tup) { } else { List <KeyValuePair <Type, object> > temp = new List <KeyValuePair <Type, object> >(); KeyValuePair <Type, object> pair = new KeyValuePair <Type, object>(n.getReturnType(), n.Value); temp.Add(pair); return(temp); } } if (node.GetType() == typeof(IfNode)) { IfNode n = (IfNode)node; List <KeyValuePair <Type, object> > ifUslovie = dfs(n.expr); bool uslovie = (bool)ifUslovie[0].Value; if (uslovie) { return(dfs(n.body)); } else { if (n.else_body != null) { return(dfs(n.else_body)); } } } List <BaseNode> children = node.getChildren().ToList(); List <KeyValuePair <Type, object> > returnTypes = new List <KeyValuePair <Type, object> >(); //our return objects for (int i = 0; i < children.Count(); i++) { if (children[i] == null) { continue; } List <KeyValuePair <Type, object> > temp = dfs(children[i]); for (int j = 0; j < temp.Count; j++) { returnTypes.Add(temp[j]); } } if (node.GetType() == typeof(LoopNode)) { LoopNode n = (LoopNode)node; LoopType loopType = n.type; String identifier = n.id; if (loopType == LoopType.For) { int top = (int)returnTypes[1].Value; intVariables[identifier] = (int)returnTypes[0].Value; while (intVariables[identifier] < top) { dfs(n.fields["body"]); intVariables[identifier]++; } while (intVariables[identifier] > top) { dfs(n.fields["body"]); intVariables[identifier]--; } } if (loopType == LoopType.While) { bool uslovie = (bool)dfs(n.fields["expr"])[0].Value; while (uslovie) { dfs(n.fields["body"]); uslovie = (bool)dfs(n.fields["expr"])[0].Value; } } return(returnTypes); } if (node.GetType() == typeof(RelNode)) { RelNode n = (RelNode)node; if (n.getRFactor() != null) { List <KeyValuePair <Type, object> > temp = new List <KeyValuePair <Type, object> >(); KeyValuePair <Type, object> left = returnTypes[0], right = returnTypes[1]; string op = n.Op; bool result = false; if (left.Key == Type.Int && right.Key == Type.Int) { if (op == "lt_t") { result = (int)left.Value < (int)right.Value; } else if (op == "gt_t") { result = (int)left.Value > (int)right.Value; } else if (op == "le_t") { result = (int)left.Value <= (int)right.Value; } else if (op == "ge_t") { result = (int)left.Value >= (int)right.Value; } else if (op == "eq_t") { result = (int)left.Value == (int)right.Value; } else if (op == "neq_t") { result = (int)left.Value != (int)right.Value; } } else if (left.Key == Type.Int && right.Key == Type.Real) { if (op == "lt_t") { result = (int)left.Value < (double)right.Value; } else if (op == "gt_t") { result = (int)left.Value > (double)right.Value; } else if (op == "le_t") { result = (int)left.Value <= (double)right.Value; } else if (op == "ge_t") { result = (int)left.Value >= (double)right.Value; } else if (op == "eq_t") { result = (int)left.Value == (double)right.Value; } else if (op == "neq_t") { result = (int)left.Value != (double)right.Value; } } else if (left.Key == Type.Real && right.Key == Type.Int) { if (op == "lt_t") { result = (double)left.Value < (int)right.Value; } else if (op == "gt_t") { result = (double)left.Value > (int)right.Value; } else if (op == "le_t") { result = (double)left.Value <= (int)right.Value; } else if (op == "ge_t") { result = (double)left.Value >= (int)right.Value; } else if (op == "eq_t") { result = (double)left.Value == (int)right.Value; } else if (op == "neq_t") { result = (double)left.Value != (int)right.Value; } } else if (left.Key == Type.Real && right.Key == Type.Real) { if (op == "lt_t") { result = (double)left.Value < (double)right.Value; } else if (op == "gt_t") { result = (double)left.Value > (double)right.Value; } else if (op == "le_t") { result = (double)left.Value <= (double)right.Value; } else if (op == "ge_t") { result = (double)left.Value >= (double)right.Value; } else if (op == "eq_t") { result = (double)left.Value == (double)right.Value; } else if (op == "neq_t") { result = (double)left.Value != (double)right.Value; } } else { throw new Exception("Wrong types comparison"); } temp.Add(new KeyValuePair <Type, object>(Type.Bool, result)); return(temp); } } if (node.GetType() == typeof(ExprNode)) { ExprNode n = (ExprNode)node; if (n.getRightRelation() != null) { List <KeyValuePair <Type, object> > temp = new List <KeyValuePair <Type, object> >(); string op = n.getOp(); if (returnTypes[0].Key != Type.Bool || returnTypes[1].Key != Type.Bool) { throw new Exception("Wrong or, xor, and operation"); } bool left = (bool)returnTypes[0].Value, right = (bool)returnTypes[1].Value; if (op == "or_t") { temp.Add(new KeyValuePair <Type, object>(Type.Bool, left || right)); } if (op == "xor_t") { temp.Add(new KeyValuePair <Type, object>(Type.Bool, left ^ right)); } if (op == "and_t") { temp.Add(new KeyValuePair <Type, object>(Type.Bool, left && right)); } } return(returnTypes); } if (node.GetType() == typeof(AssNode)) { AssNode n = (AssNode)node; string id = n.prim.id; object v = returnTypes[0].Value; if (intVariables.ContainsKey(id)) { intVariables[id] = (int)v; } else if (stringVariables.ContainsKey(id)) { stringVariables[id] = (string)v; } else if (realVariables.ContainsKey(id)) { realVariables[id] = (double)v; } else if (integerArrays.ContainsKey(id)) { List <KeyValuePair <Type, object> > index = new List <KeyValuePair <Type, object> >(); //our return objects index = dfs(n.prim.indexChildren[0]); integerArrays[id][(int)index[0].Value] = (int)v; } else if (tupleVariables.ContainsKey(id)) { throw new Exception("Tuples are immutable"); } } if (node.GetType() == typeof(LiteralNode)) { LiteralNode n = (LiteralNode)node; if (n.type == LiteralType.Tup) { List <KeyValuePair <Type, object> > finalResult = new List <KeyValuePair <Type, object> >(); //our return objects Dictionary <int, object> v = new Dictionary <int, object>(); for (int i = 0; i < returnTypes.Count; i++) { v.Add(i, returnTypes[i].Value); } finalResult.Add(new KeyValuePair <Type, object>(Type.Tup, v)); return(finalResult); } } if (node.GetType() == typeof(DecNode)) { DecNode d = (DecNode)node; switch (returnTypes[0].Key) { case Type.Int: intVariables.Add(d.id, (int)returnTypes[0].Value); break; case Type.Real: realVariables.Add(d.id, (double)returnTypes[0].Value); break; case Type.String: stringVariables.Add(d.id, (string)returnTypes[0].Value); break; case Type.Arr: if (returnTypes[0].Value != null) { integerArrays.Add(d.id, (Dictionary <int, int>)returnTypes[0].Value); } else { integerArrays.Add(d.id, new Dictionary <int, int>()); } break; case Type.Tup: Dictionary <int, object> v = (Dictionary <int, object>)returnTypes[0].Value; tupleVariables.Add(d.id, v); break; case Type.Bool: boolVariables.Add(d.id, (bool)returnTypes[0].Value); break; } } //получение по id if (node.GetType() == typeof(PrimaryNode)) { PrimaryNode n = (PrimaryNode)node; List <KeyValuePair <Type, object> > temp = new List <KeyValuePair <Type, object> >(); if (n.type == PrimaryType.Id) { string name = n.id; if (intVariables.ContainsKey(name)) { temp.Add(new KeyValuePair <Type, object>(Type.Int, intVariables[name])); } else if (stringVariables.ContainsKey(name)) { temp.Add(new KeyValuePair <Type, object>(Type.String, stringVariables[name])); } else if (realVariables.ContainsKey(name)) { temp.Add(new KeyValuePair <Type, object>(Type.Real, realVariables[name])); } else if (integerArrays.ContainsKey(name)) { if (returnTypes.Count == 0) { temp.Add(new KeyValuePair <Type, object>(Type.Arr, integerArrays[name])); } else { if (!integerArrays[name].ContainsKey((int)returnTypes[0].Value)) { integerArrays[name].Add((int)returnTypes[0].Value, -1); } temp.Add(new KeyValuePair <Type, object>(Type.Int, integerArrays[name][(int)returnTypes[0].Value])); } } else if (boolVariables.ContainsKey(name)) { temp.Add(new KeyValuePair <Type, object>(Type.Bool, boolVariables[name])); } else if (tupleVariables.ContainsKey(name)) { Dictionary <int, object> tuple = tupleVariables[name]; int index = (int)returnTypes[0].Value; object o = tuple[index]; if (IsInt(o)) { temp.Add(new KeyValuePair <Type, object>(Type.Int, tuple[index])); } else if (IsReal(o)) { temp.Add(new KeyValuePair <Type, object>(Type.Real, tuple[index])); } else if (IsString(o)) { temp.Add(new KeyValuePair <Type, object>(Type.String, tuple[index])); } } return(temp); } if (n.type == PrimaryType.readInt) { temp.Add(new KeyValuePair <Type, object>(Type.Int, int.Parse(Console.ReadLine()))); return(temp); } if (n.type == PrimaryType.readReal) { temp.Add(new KeyValuePair <Type, object>(Type.Real, double.Parse(Console.ReadLine()))); return(temp); } if (n.type == PrimaryType.readString) { temp.Add(new KeyValuePair <Type, object>(Type.String, Console.ReadLine())); return(temp); } } //Принт результатов if (node.GetType() == typeof(PrintNode)) { Console.Write("Print :"); for (int i = 0; i < returnTypes.Count; i++) { Console.Write(" " + returnTypes[i].Value); } } // умножение и деление if (node.GetType() == typeof(TermNode)) { TermNode n = (TermNode)node; if (n.getTail() != null) { KeyValuePair <Type, object> result = returnTypes[0]; List <KeyValuePair <Type, object> > finalResult = new List <KeyValuePair <Type, object> >(); for (int i = 1; i < returnTypes.Count; i++) { Type temp = returnTypes[i].Key; object value = returnTypes[i].Value; ComplexUnary tempUnary = (ComplexUnary)children[i]; TermOp sign = tempUnary.getOp(); if (sign == TermOp.Div) { if (result.Key == Type.Int && temp == Type.Int) { result = new KeyValuePair <Type, object>(Type.Int, (int)result.Value / (int)value); } else if (result.Key == Type.Int && temp == Type.Real) { result = new KeyValuePair <Type, object>(Type.Real, (int)result.Value / (int)value); } else if (result.Key == Type.Real && temp == Type.Int) { result = new KeyValuePair <Type, object>(Type.Real, (int)result.Value / (int)value); } else if (result.Key == Type.Real && temp == Type.Real) { result = new KeyValuePair <Type, object>(Type.Real, (int)result.Value / (int)value); } else { throw new Exception("Wrong division found"); } } else if (sign == TermOp.Mult) { if (result.Key == Type.Int && temp == Type.Int) { result = new KeyValuePair <Type, object>(Type.Int, (int)result.Value * (int)value); }//result stays the same else if (result.Key == Type.Int && temp == Type.Real) { result = new KeyValuePair <Type, object>(Type.Real, (int)result.Value * (int)value); } else if (result.Key == Type.Real && temp == Type.Int) { result = new KeyValuePair <Type, object>(Type.Real, (int)result.Value * (int)value); } else if (result.Key == Type.Real && temp == Type.Real) { result = new KeyValuePair <Type, object>(Type.Real, (int)result.Value * (int)value); } else { throw new Exception("Wrong multiplication found"); } } } finalResult.Add(result); return(finalResult); } } //сумма и вычитание if (node.GetType() == typeof(FactorNode)) { FactorNode n = (FactorNode)node; if (n.getTail() != null) { KeyValuePair <Type, object> result = returnTypes[0]; List <KeyValuePair <Type, object> > finalResult = new List <KeyValuePair <Type, object> >(); for (int i = 1; i < returnTypes.Count; i++) { Type temp = returnTypes[i].Key; object value = returnTypes[i].Value; ComplexTerm tempTerm = (ComplexTerm)children[i]; FactorOp sign = tempTerm.getop(); if (sign == FactorOp.Minus) { if (result.Key == Type.Int && temp == Type.Int) { result = new KeyValuePair <Type, object>(Type.Int, (int)result.Value - (int)value); } else if (result.Key == Type.Int && temp == Type.Real) { result = new KeyValuePair <Type, object>(Type.Real, (double)result.Value - (double)value); } else if (result.Key == Type.Real && temp == Type.Int) { result = new KeyValuePair <Type, object>(Type.Real, (double)result.Value - (double)value); } else if (result.Key == Type.Real && temp == Type.Real) { result = new KeyValuePair <Type, object>(Type.Real, (double)result.Value - (double)value); } else { throw new Exception("wrong type subtraction"); } } else if (sign == FactorOp.Plus) { if (result.Key == Type.Int && temp == Type.Int) { result = new KeyValuePair <Type, object>(Type.Int, (int)result.Value + (int)value); } else if (result.Key == Type.Int && temp == Type.Real) { result = new KeyValuePair <Type, object>(Type.Real, (double)result.Value + (double)value); } else if (result.Key == Type.Real && temp == Type.Int) { result = new KeyValuePair <Type, object>(Type.Real, (double)result.Value + (double)value); } else if (result.Key == Type.Real && temp == Type.Real) { result = new KeyValuePair <Type, object>(Type.Real, (double)result.Value + (double)value); } else if (result.Key == Type.String && temp == Type.String) { result = new KeyValuePair <Type, object>(Type.String, (string)result.Value + (string)value); } else if (result.Key == Type.Arr && temp == Type.Arr) { Dictionary <int, int> first = (Dictionary <int, int>)result.Value; Dictionary <int, int> second = (Dictionary <int, int>)value; Dictionary <int, int> q = (from e in first.Concat(second) group e by e.Key into g select new { Name = g.Key, Count = g.Sum(kvp => kvp.Value) }) .ToDictionary(item => item.Name, item => item.Count); result = new KeyValuePair <Type, object>(Type.Arr, q); } else { throw new Exception("wrong type summation"); } } } finalResult.Add(result); return(finalResult); } } return(returnTypes); }
public LoopIndex(BzPolyLoop loop, LoopNode <int> indexPointer, Vector2 vector2d) { this.loop = loop; this.indexPointer = indexPointer; this.vector2d = vector2d; }
public virtual void VisitLoopNode(LoopNode node) { }
public void SetProgram(List<Loop> loops, List<BasicBlock> blocks) { // build DAG of basic blocks // excluding backedges Graph g = new Graph(); Dictionary<BasicBlock, Node> NodeMap = new Dictionary<BasicBlock, Node>(); foreach (BasicBlock b in blocks) { Node n = new LeafNode(b); g.AddNode(n); NodeMap.Add(b,n); } foreach (BasicBlock b in blocks) foreach (BasicBlock s in b.Successors) if (!s.Dominates(b)) g.AddEdge(NodeMap[b], NodeMap[s]); // walk over loops inner to outer // for each loop, replace its contents with a single "super-node" foreach( Loop l in loops ) { Node[] loopNodes = new Node[l.BlockCount]; int n = 0; foreach (BasicBlock b in l.Blocks) loopNodes[n++] = NodeMap[b]; LoopNode superNode = new LoopNode(new Graph(), l); g.CombineNodes(loopNodes,superNode,superNode.SubGraph ); } BuildBranchNodes(g); // now populate the tree view with loops and branches TreeNode root = new TreeNode("program"); BuildTree(root, g); treeView1.Nodes.Add(root); }
private bool GetShortestConnection(LoopIndexCollection outerData, LoopIndexCollection innerData, BzPolyLoop[] allLoops, out LoopNode <LoopIndex> minOliNode, out LoopNode <LoopIndex> minIliNode) { minOliNode = null; minIliNode = null; float curDist = float.MaxValue; var oliNode = outerData.items.first; for (int oli = 0; oli < outerData.items.size; oli++) { var oliData = oliNode.value; var iliNode = innerData.items.first; for (int ili = 0; ili < innerData.items.size; ili++) { var iliNodeCurr = iliNode; iliNode = iliNode.next; var iliData = iliNodeCurr.value; Vector2 currOVector = iliData.vector2d - oliData.vector2d; float dist = currOVector.sqrMagnitude; if (dist >= curDist) { continue; } if (HaveLineSegmentsIntersection(allLoops, oliData, iliData)) { continue; } Vector2 center = oliData.vector2d; Vector2 vA = oliNode.previous.value.vector2d - center; Vector2 vB = iliData.vector2d - center; Vector2 vC = oliNode.next.value.vector2d - center; float angleA = Mathf.Atan2(vA.y, vA.x); float angleB = Mathf.Atan2(vB.y, vB.x); float angleC = Mathf.Atan2(vC.y, vC.x); float _2pi = 2 * Mathf.PI; if (angleA > angleB) { angleB += _2pi; } if (angleA > angleC) { angleC += _2pi; } if (angleB <= angleA | angleB >= angleC) { continue; } minOliNode = oliNode; minIliNode = iliNodeCurr; curDist = dist; } oliNode = oliNode.next; } return(minOliNode != null); }
/// <summary> /// clone /// </summary> /// <returns></returns> public IBehaviourNode Clone() { var behaviourNode = new LoopNode(this.count); base.CopyToCompositeNode(behaviourNode); return behaviourNode; }
private void ExecuteImpl(LoopNode loopNode, IEnumerator <byte> inputEnumerator, ICollection <byte> output, CancellationToken cancellationToken, ref int instructions) { foreach (var node in loopNode.Children) { if (cancellationToken.IsCancellationRequested) { throw new InvalidBFProgramException("Cancellation requested", false); } switch (node) { case MoveRightNode moveRightNode: instructions++; Memory.MoveRight(); break; case MoveLeftNode moveLeftNode: instructions++; Memory.MoveLeft(); break; case IncrementNode incrementNode: instructions++; Memory.Increment(); break; case DecrementNode decrementNode: instructions++; Memory.Decrement(); break; case InputNode inputNode: instructions++; if (!inputEnumerator.MoveNext()) { throw new InvalidBFProgramException("No input available anymore", false); } Memory.SetValue(inputEnumerator.Current); break; case OutputNode outputNode: instructions++; output.Add(Memory.GetValue()); break; case LoopNode innerLoopNode: while (Memory.GetValue() > 0) { instructions++; if (cancellationToken.IsCancellationRequested) { throw new InvalidBFProgramException("Cancellation requested", false); } ExecuteImpl(innerLoopNode, inputEnumerator, output, cancellationToken, ref instructions); } instructions++; break; default: throw new InvalidBFProgramException("Unexpected child node", false); } } }
/// <summary> /// Calculate triangle list /// </summary> /// <param name="right">Clockwise if True</param> /// <returns>True if polygon was created</returns> private List <int> GetTriangles() { if (_loopPoints.Length < 3) { return(new List <int>()); } var newTriangles = new List <int>((_loopPoints.Length - 2) * 3); var linkList = new LinkedLoop <int>(); for (int i = 0; i < _loopPoints.Length; ++i) { linkList.AddLast(i); } while (linkList.size > 2) { int counter = 0; float minDist = float.MaxValue; int minI1 = 0; LoopNode <int> minNode2 = null; int minI3 = 0; var node = linkList.first; while (counter < linkList.size) { var node1 = node; var node2 = node1.next; var node3 = node2.next; var i1 = node1.value; var i2 = node2.value; var i3 = node3.value; ++counter; float dist = GetDistance(i1, i3); bool allowed = minDist > dist && IsAllowedToCreateTriangle(linkList, i1, i2, i3); if (allowed & minDist > dist) { minDist = dist; minNode2 = node2; minI1 = i1; minI3 = i3; //if (!optimization enabled) // TODO // break; } node = node2; } if (minNode2 == null) { break; } minNode2.Remove(); CreateTriangle(newTriangles, minI1, minNode2.value, minI3); } return(newTriangles); }
public void Parse(string input) { // clear unwanted characters string program = new string(input.ToCharArray().Where(x => AllowedCharacters.Contains(x)).ToArray()); // search clear loop [-] and replace them with precompiler instruction C program = program.Replace("[-]", "C"); // search for scan left loop [<] and replace them with precompiler instruction L program = program.Replace("[<]", "L"); // search for scan right loop [>] and replace them with precompiler instruction R program = program.Replace("[>]", "R"); // parse program and convert to instructions WithChildrenNodeBase currentParentNode = Root; int loopDepthCount = 0; int programPtr = 0; while (programPtr < program.Length) { char instruction = program[programPtr]; // check RLE int instructionCount = 1; while (true) { programPtr++; if (programPtr >= program.Length) { break; } char nextInstruction = program[programPtr]; if (nextInstruction == instruction && instructionCount < 255 && (nextInstruction == '+' || nextInstruction == '-' || nextInstruction == '>' || nextInstruction == '<')) { instructionCount++; } else { break; } } // instruction + count -> create instruction switch (instruction) { case '[': loopDepthCount++; LoopNode loopNode = new LoopNode { Children = new List <NodeBase> { new InstructionNode { Instruction = new OpenInstruction(), Parent = currentParentNode, } }, Parent = currentParentNode //--// Don't add OpenInstruction, it's implicit in LoopNode (CloseInstructionPtr will be next in PreOrder) }; currentParentNode.Children.Add(loopNode); currentParentNode = loopNode; break; case ']': if (loopDepthCount == 0) { throw new InvalidOperationException($"Unmatched ']' at position {programPtr}."); } loopDepthCount--; //--// Don't add CloseInstruction, it's implicit in LoopNode (OpenInstructionPtr is Parent.Children.First()) currentParentNode.Children.Add(new InstructionNode { Instruction = new CloseInstruction(), Parent = currentParentNode }); currentParentNode = (WithChildrenNodeBase)currentParentNode.Parent; break; case '+': currentParentNode.Children.Add(new InstructionNode { Instruction = new AddInstruction { X = (byte)instructionCount }, Parent = currentParentNode }); break; case '-': currentParentNode.Children.Add(new InstructionNode { Instruction = new SubInstruction { X = (byte)instructionCount }, Parent = currentParentNode }); break; case '>': currentParentNode.Children.Add(new InstructionNode { Instruction = new RightInstruction { X = (byte)instructionCount }, Parent = currentParentNode }); break; case '<': currentParentNode.Children.Add(new InstructionNode { Instruction = new LeftInstruction { X = (byte)instructionCount }, Parent = currentParentNode }); break; case '.': currentParentNode.Children.Add(new InstructionNode { Instruction = new OutInstruction(), Parent = currentParentNode }); break; case ',': currentParentNode.Children.Add(new InstructionNode { Instruction = new InInstruction(), Parent = currentParentNode }); break; // precompiler-instruction case 'C': currentParentNode.Children.Add(new InstructionNode { Instruction = new ClearInstruction(), Parent = currentParentNode }); break; case 'L': currentParentNode.Children.Add(new InstructionNode { Instruction = new ScanLeftInstruction(), Parent = currentParentNode }); break; case 'R': currentParentNode.Children.Add(new InstructionNode { Instruction = new ScanRightInstruction(), Parent = currentParentNode }); break; } } if (loopDepthCount > 0) { throw new InvalidOperationException("Unmatched ']'"); // TODO: display original programPtr } // Search copy loop and multiplication loop Stack <LoopNode> nodes = new Stack <LoopNode>(); foreach (LoopNode loopNode in Root.Children.OfType <LoopNode>()) // don't need to reverse order { nodes.Push(loopNode); } while (nodes.Count > 0) { LoopNode loopNode = nodes.Pop(); if (loopNode.Children.OfType <LoopNode>().Any()) { foreach (LoopNode node in loopNode.Children.OfType <LoopNode>()) // don't need to reverse order { nodes.Push(node); } } else if (loopNode.Children.Count >= 6 && loopNode.Children.OfType <InstructionNode>().Skip(1).Take(loopNode.Children.Count - 2) /*skip Open/Close*/.All(x => x.Instruction is AddInstruction || x.Instruction is SubInstruction || x.Instruction is LeftInstruction || x.Instruction is RightInstruction)) // terminal loop node (with only +-<>), potentially optimisable { List <InstructionNode> sequence = loopNode.Children.OfType <InstructionNode>().Skip(1).Take(loopNode.Children.Count - 2).ToList(); // copy loop // [>+<-] or [->+<] => mem[p+1] += mem[p] and mem[p] = 0 // [>>+<<-] or [->>+<<] => mem[p+2] += mem[p] and mem[p] = 0 // [>>>>>>>>>+<<<<<<<<<-] or [->>>>>>>>>+<<<<<<<<<] => mem[p+9] += mem[p] and mem[p] = 0 // can be more complex // [->+>+<<] => mem[p+1] += mem[p] and mem[p+2] += mem[p] and mem[p] = 0 // [>+>>>+>+<<<<<-] => mem[p+1] += mem[p] and mem[p+4] += mem[p] and mem[p+5] += mem[p] and mem[p] = 0 // [->>>>+<+<+<+<] => mem[p+4] += mem[p] and mem[o+3] += mem[p] and mem[p+2] += mem[p] and mem[p+1] += mem[p] and mem[p] = 0 // > and < can be interchanged => mem[p-x] instead if mem[p+x] // multiply loop // [>+++++<-] => mem[p+1] += 5*mem[p] and mem[p] = 0 // [>++++>++>>>+++>+<<<<<<-] => mem[p+1] += 4*mem[p] and mem[p+2] += 2*mem[p] and mem[p+5] += 3*mem[p] and mem[p] = 0 // a sequence of >{+} followed by a sequence of < (same number as >) followed by a - // same as - followed by a sequence of >{+} followed by a sequence of < (same number as >) // a sequence of <{+} followed by a sequence of > (same number as <) followed by a - // same as - followed by a sequence of <{+} followed by a sequence of > (same number as <) if (sequence.First().Instruction is SubInstruction || sequence.Last().Instruction is SubInstruction) { } } } }
public virtual XzaarExpression Visit(LoopNode loop) { return(null); }
public virtual LoopNode Visit(LoopNode loop) { return(loop); }