Search code examples
c++turtle-graphicsfractals

L-System tree won't branch correctly


I have tried to implement the L-System in c++ with SFML, but for some reason it doesn't work as expected.

I tried replicating this program: https://www.youtube.com/watch?v=E1B4UoSQMFw?t=1256 And everything works fine except the branching. At the timestamp(20:56) you can see the tree branching off into two branches, and these two branches branch off individually.

However, this shouldn't be possible due to the rules(the turtle can save position/rotation to make a new branch, but it can only save one position at a time so branching off inside a branch multiple times isn't possible)

In my program instead of branching off in two branches that are branching off individually only one of the branches(right one) branches of further, as should be expected. But why then does his code produce a completely different result, that shouldn't be possible with this ruleset?


Solution

  • You implemented an L system with the following alphabet:

    Alphabet: F+-[]

    And the following rule:

    Rule 1: FFF+[+F-F-F]-[-F+F+F]

    The meanings of the alphabet characters are very turtle-graphic-like and are as follows:

    • F Move forward 1 unit and draw a line as you go.
    • + Turn Clockwise
    • - Turn Counter-Clockwise
    • [ Push the current state onto the stack.
    • ] Pop state from the stack and make it the current state.

    This requires that you know what a stack is.

    You can see, because there is an F inside the square brackets in the rule, how in the second generation there will be nested square brackets.

    (Sorry for the long line below, but it's a long rule and breaking the line would be confusing. Just scroll right. Observe how I have highlighted the outer group of matching nested brackets.)

    FF+[+F-F-F]-[-F+F+F]FF+[+F-F-F]-[-F+F+F]+[+FF+[+F-F-F]-[-F+F+F]-FF+[+F-F-F]-[-F+F+F]-FF+[+F-F-F]-[-F+F+F]]-[-FF+[+F-F-F]-[-F+F+F]+FF+[+F-F-F]-[-F+F+F]+FF+[+F-F-F]-[-F+F+F]]
                                             [...............................................................] [...............................................................]
    

    When applying the turtle-graphics interpretation, when we encounter a second [ before encountering a ], we will now have multiple states saved on the stack. An arbitrary number of states may be saved. The stack is "first in, last out", much like stacking plates, you can only access the plate at the top of the stack. Each time you push state with [ it's like adding a plate to the stack of plates. When you see a ] you remove the top plate from the stack. To remove a plate from the top of the stack in this way is to pop it. Each plate, in this scenario, represents the state of the turtle as it was when it was pushed. Popping a state restores the turtle's position and orientation back to that saved position.