//TODO Make this thing recursive. /// <summary> /// Adds a new branch to the tree. /// </summary> /// <param name="currentNode">Node (branch) that is currently processed. New node will be attached to it.</param> /// <param name="sideBranch">True if the node will start a new branch. /// False (default) if node will continue current branch.</param> /// <returns>New node.</returns> public static Node AddBranch(Node currentNode, bool sideBranch = false) { // Create new node which extend current branch. Node n = new Node(new SFML.Window.Vector2f(5, 0)); n.Origin = currentNode.Origin; n.FillColor = currentNode.FillColor; n.Generation = currentNode.Generation + 1; // Offset for new node's position. Will make it grow at the end of current node. double offsetX = Math.Abs(currentNode.Size.Y) * Math.Sin(currentNode.Rotation * (Math.PI / 180)); double offsetY = Math.Abs(currentNode.Size.Y) * Math.Cos(currentNode.Rotation * (Math.PI / 180)); n.Position = currentNode.Position + new Vector2f((float)offsetX, -(float)offsetY); if (!sideBranch) { n.Rotation = rnd. Next(((int)(currentNode.Rotation) - 5), ((int)(currentNode.Rotation) + 5)); return n; } else { n.Rotation = rnd.Next(((int)(currentNode.Rotation) - 50), ((int) (currentNode.Rotation) + 50)); return n; } }
static void Main(string[] args) { RenderWindow window = new RenderWindow(new SFML.Window.VideoMode(800, 600), "Title"); RenderTexture treeTexture = new RenderTexture(800, 600); Sprite treeSprite = new Sprite(treeTexture.Texture); // List of tree nodes. List<Node> nodes = new List<Node>(); List<Node> dividedNodes = new List<Node>(); DateTime timeOfLastDraw = DateTime.Now; // Create root node. Node root = new Node(new SFML.Window.Vector2f(5, 2)); root.Origin = new SFML.Window.Vector2f(1, 0); root.Position = new SFML.Window.Vector2f(400, 600); root.FillColor = new Color(0, 200, 50); root.Generation = 1; nodes.Add(root); DateTime timeOfLastUpdate = DateTime.Now; // Loop while (window.IsOpen()) { window.Clear(Color.White); for (int i = 0; i < nodes.Count; i++) { treeTexture.Draw(nodes[i]); if (nodes[i].Divided) { dividedNodes.Add(nodes[i]); nodes.RemoveAt(i); continue; } // Grow the node until it meets its max size. else if (nodes[i].Size.Y > -25) { nodes[i].Size += new SFML.Window.Vector2f(0, -100 * (float)(Utilities.GetTimeDifference(timeOfLastUpdate))); } else // Node reached maximum size and can be cloned. { // Mark current node as divided, meaning it won't get any more branches and will be ignored by the loop. nodes[i].Divided = true; // Decide if current branch will extend. if (rnd.Next(0, 101) > 20) { nodes.Add(AddBranch(nodes[i])); } // Devide if the branch will split. if (rnd.Next(0, 101) > 40) { nodes.Add(AddBranch(nodes[i], true)); } } } timeOfLastUpdate = DateTime.Now; treeTexture.Display(); window.Draw(treeSprite); foreach (Node node in dividedNodes) { treeTexture.Draw(node); } window.Display(); } }