# Difference between revisions of "LSystem SOP"

• Invalid title: ""

## Summary

The Lsystem SOP implements L-systems (Lindenmayer-systems, named after Aristid Lindenmayer (1925-1989)), allow definition of complex shapes through the use of iteration. They use a mathematical language in which an initial string of characters is evaluated repeatedly, and the results are used to generate geometry. The result of each evaluation becomes the basis for the next iteration of geometry, giving the illusion of growth.

You begin building an L-system by defining a sequence of rules which are evaluated to produce a new string of characters. Each character of the new string represents one command which affects an imaginary stylus, or "turtle". Repeating this process will grow your geometry.

You can use L-systems to create things such as:

• Create organic objects such as trees, plants, flowers over time.
• Create animated branching objects such as lightning and snowflakes.

The file can be read in from disk or from the web. Use http:// when specifying a URL.

### The Algorithmic Beauty of Plants

The descriptions located here should be enough to get you started in writing your own L-system rules, however, if you have any serious interests in creating L-systems, you should obtain the book:

```The Algorithmic Beauty of Plants
Przemyslaw Prusinkiewicz & Aristid Lindenmayer
Springer-Verlag, New York, Phone: 212.460.1500
ISBN: 0-387-94676-4, 1996.
```

which is the definitive reference on the subject. It contains a multitude of L-systems examples complete with descriptions of the ideas and theories behind modelling realistic plant growth.

[[{{{opClass}}}]]

## Rule Substitution

You create the highly structured organic and branching objects using L-systems grammar. An L-system is a process in which a sequence of rules are applied to an initial string of characters to create a new string. To build the geometry, each character of the final string represents one command which affects an imaginary stylus, or "turtle".

The process begins by examining the first character of the premise string. All sixteen rules are searched sequentially until an applicable rule is found. The current character is then replaced with one or more characters as defined by the rule. The remaining characters in the premise string are replaced in a similar fashion. The entire process is repeated once for each generation.

### Limitations to Rules

• Polygon {} and branch [] operators can be nested 30 levels deep
• Rules can be 256 characters in length
• Variables can have up to 5 parameters
• Up to 25 rules can be defined

### Turtle Operators

`F` Move forward (creating geometry)

`H` Move forward half the length (creating geometry)

`G` Move forward but don't record a vertex

`f` Move forward (no geometry created)

`h` Move forward a half length (no geometry created)

`J K M` Copy geometry source J, K or M at the turtle's position
after rescaling and reorienting the geometry.

`T` Apply tropism vector

`+` Turn right

`-` Turn left (minus sign)

`&` Pitch up

`^` Pitch down

`\` Roll clockwise

`/` Roll counter-clockwise

`|` Turn 180 degrees

`*` Roll 180 degrees

`~` Pitch / Roll / Turn random amount

`"` Multiply current length

`!` Multiply current thickness

`;` Multiply current angle

`_` Divide current length (underscore)

`?` Divides current width

`@` Divide current angle

`'` Increment color index U (single quote)

`#` Increment color index V

`%` Cut off remainder of branch

`\$` Rotate `up' towards the sun about heading

`[` Push turtle state (start a branch)

`]` Pop turtle state (end a branch)

`{` Start a polygon

`.` Make a polygon vertex

`}` End a polygon

`g` Create a new primitive group to which subsequent geometry is added

## Production Rule Syntax

A Touch L-system rule is specified as:

[lc<] pred [>rc] [:cond]=succ [:prob]

where:

• lc - Optional left context
• pred - predecessor symbol to be replaced
• rc - Optional right context
• cond - Condition expression (optional)
• succ - Replacement string
• prob - Probability of rule execution (optional)

### Context Sensitivity

The most basic type of rule is:

pred = succ

In this case, a character is replaced with the characters of succ if, and only if, it matches pred.

For example:

Premise: `ABC`
Rule 1: `B=DOG`

will result in `ADOGC`

pred can only specify one letter, but left and right context symbols can be specified. The general syntax is [lc<] pred [>rc] = succ.

For example:

Premise: `ABC`
Rule 1: `A<B=DOG`

again results in `ADOGC` because `B` is preceded by `A`. If the rule were: `Z<B=DOG` or `B>A=DOG` the rule would not be applied.

## Parameter Symbols

Each symbol can have up to five user-defined variables associated with it which can be referenced or assigned in expressions. Variables in the predecessor are instanced while variables in the successor are assigned.

For example:

The rule `A(i, j) = A(i+1, j-1)`, will replace each `A` with a new `A` in which the first parameter has been incremented and the second parameter decremented.

Note that the variables in the predecessor can also be referenced by the condition or probability portions of the rule.

For example:

The rule `A(i):i<5 = A(i+1) A(i+1)`, will double each `A` a maximum of five times (assuming a Premise of `A(0)`).

Parameters assigned to geometric symbols (e.g. `F`, `+`, or `!`) are interpreted geometrically.

For example:

The rule `F(i, j) = F(0.5*i, 2*j)`, will again replace each `F` with a new `F` containing modified parameters. In addition to this, the new `F` will now be drawn at half the length and twice the width.

## Operator Override

Normally turtle symbols use the current length/angle/thickness etc. to determine their effect. By providing a turtle operator with an explicit parameter, it will override the value normally used by the turtle operator.

Override parameters for `F`, `f`, `G`, `h`, `H` take the form of:

`F(i,j,k,l,m)`

• `i` - Override Length.
• `j` - Override Thickness.
• `k` - Override # Tube Segments.
• `l` - Override # Tube Rows.
• `m` - User parameter.

The k and l override parameters allow dynamic resolution of tube segments.

### Examples

`F` - Moves forward current length creating geometry.

`H` - Moves forward half current length creating geometry.

`F(i, j)` - Moves forward a distance of `i,` creating geometry of thickness `j`.

`H(i, j)` - Move forward half the distance of `i`, creating geometry of thickness half of `j`.

`+` - Turn by current angle amount.
`~` - Rotate by random angle.

`+(i)` - Turn by i degrees.
`~(i)` - Override random angle with value of `i`.

`\$(x0,y0,z0)` - Points the turtle to location `(x0,y0,z0)`.

Given the above, the Premise:

`F(1) +(90) F(1) +(90) F(1) +(90) F(1)`

generates a unit box regardless of the default Step Size or Angle settings.

### List of Operator Overrides

The following list describes the geometric interpretation of parameters assigned to certain turtle symbols:

## Edge Rewriting

In The Algorithmic Beauty of Plants, many examples use a technique called Edge Rewriting which involve left and right subscripts. A typical example might look like:

Generations `10`
Angle `90`
Premise `F(l)`
Rules
`F(l) = F(l)+F(r)+ F(r) = -F(l)-F(r)`

However, Touch doesn't know what `F(l)` and `F(r)` are. In this case, we can modify the rules to use parameter passing. For the `F` turtle symbol, the first four parameters are length, width, tubesides, and tubesegs, leaving the last parameter user-definable. We can define this last parameter such that `0` is left, and `1` is right:

Generations `10`
Angle `90`
Premise `F(1,1,3,3,0)`
Rules

After two generations this produces: `Fl+Fr+-Fl-Fr`. There should not be any difference between this final string and `F+F+-F-F.`

Another approach is to use two new variables, and use a conditional statement on the final step to convert them to `F`:

Variable b `ch("generations")`
Premise `l`
Rules
`l:t<b=l+r+ r:t<b=-l-r l=F r=F`
Output `l`
`F`
`F+F+`
`F+F++-F-F+`

## Expressions

In the earlier example, the expressions `0.5*i` and `2*j` are used. In fact, expressions can be used anywhere a numeric field is expected. Currently the following symbols can be used in expressions:

`( )` - brackets for nesting priority

`^ + - * / %` - arithmetic operators

`min() max() sin() cos() asin() acos() pic() in()` - supported functions

`== != = < <= > >=` - logical operators

`& | !` - logical operators: and, or, not

`b c d` - SOP b, c, d parameters after expansion

`x y z` - current turtle position

`g` - age of symbol

`t` - time (generations) of L-system

`a` - SOP angle parameter

`T` - SOP tropism (gravity) parameter

The pre-defined variables above should not be used in the arguments of the predecessor.

For example: `A(a,b) = B(a*2,b*2)` is wrong (a is the SOP Angle parameter). `a<b (A,B) = b(A+1,B)` is right.

The last statement is correct because `a` and `b` are used as symbols and not variable names. `A` and `B` are correct because variable names are case sensitive.

### L-System Specific Expression Functions

• `pic(u, v, c)` - Using the image specified with Pic Image File, this function returns a normalized value (between `0` and `1`) of the pixel at the normalized coordinates `(u,v)`; `c` selects one of four channels to examine:
`0`
`1`
`2`
`3`
• `in(q, r, s)` - Given a MetaTest input source containing a metaball geometry, this function returns a `1` if the point `(q, r, s)` is contained within the metaball, and `0` if not. Use `in(x, y, z)` (the letters `x`, `y`, and `z` are special and contain the X, Y, and Z location of the turtle) to test whether or not the turtle is currently inside the metaball to create pruned outputs.

### Conditions

Each rule may have an optional condition specified. The syntax is:

[lc<] pred [>rc]:cond = succ

For example:

The Rule1 `A:y>2=J` includes source `J` at all `A`'s above the height of `2`.

### Probability

Each rule can specify the probability that it is used (provided it is otherwise applicable). The syntax is:

[lc<] pred [>rc]:cond=succ=prob

For example:

Rule1 `A=B:0.5`
Rule2 `A=C:0.5 `

will replace `A` with either `B` or ` C` with equal probability.

## Creating Groups with L-Systems

There is a group operator '`g`' which lumps all geometry currently being built into group g.

For example: `g[F]` lumps geometry from F into a group called `lsys0`. You can set the lsys prefix from the Funcs page.

### Optional Group Parameters

`g` takes an optional parameter as well.

For example: `g(1)[F]` lumps geometry from `f` into a group called `lsys1`. If no parameter is given, the default index is bumped up appropriately.

The current group container is pushed/popped with the turtle state so you can do things like:

`gF [ gFF] F `- The first and last `F`'s are put into group `0`, and the middle `FF`'s are put into group `1`.

`gF [ FF] F` - The geometry from all four `F`'s are put into group `0`, (pushing the turtle adopts the parent's group).

To exclude the middle `FF` from the parent's group type: `gF [ g(-1)FF ] F`

## Controlling the Length over Time

To create an L-system which goes forward X percent less for each iteration, you need to start your Premise with a value, and then within a rule, multiply that value by the percentage you want to remain:

Premise `A(1)`
Rule `A(i) = F(i)A(i*0.5)`

This way "`i`" is scaled before `A` is again evaluated. The important part is the Premise. You need to start with a value to be able to scale that value.

## Example

Step 1) Place a Circle SOP, and set the Number of Divisions to`: param("lsys", 3`)

It then displays a triangle (3 is default value).

Step 2) Pipe this into the J input of a L-System SOP. If the L-system Premise is:

`J A`
`J(,,4) A`
`J(,,5) A`

This way, you can customize each leaf before it gets copied.

Step 3) Change the Premise and Rule to:

Premise`A(0)`
Rule1`A(i)=FJ(,,i+3)A(i+1)`

This creates a line of increasing-order polygons.

Step 4) Finally, we will want to create 20 leaves, and put them all into a Switch SOP. Do this by entering the following expression into the Switch SOP's Select Input: `param("lsys",0)`
Step 5) Then in your L-system, J(,,0) gives you the first SOP, J(,,1) gives you the second, and so on. This solves the problem of a limited number of leaves using only JKM.

Also note that these examples use only the first stamp parameter, you can use up to three parameters: e.g. J(,,1,2,3)

The first two parameters of J, K, M are used to override length and width, like symbol F.

TouchDesigner Build:

Add • Alembic • Align • Arm • Attribute Create • Attribute • Basis • Blend • Bone Group • Boolean • Box • Bridge • Cache • Cap • Capture Region • Capture • Carve • CHOP to • Circle • Clay • Clip • Convert • Copy • CPlusPlus • Creep • Curveclay • Curvesect • DAT to • Deform • Delete • Divide • Extrude • Facet • File In • Fillet • Fit • Font • Force • Fractal • Grid • Group • Hole • Import Select • In • Introduction To SOPs id • Inverse Curve • Iso Surface • Join • Joint • Kinect • Lattice • Limit • Line • Line Thick • LOD • LSystem • Magnet • Material • Merge • Metaball • Model • Noise • Null • Object Merge • Oculus Rift • OpenVR • Out • Particle • Point • Polyloft • Polypatch • Polyreduce • Polyspline • Polystitch • Primitive • Profile • Project • Rails • Raster • Ray • Rectangle • Refine • Resample • Revolve • Script • Select • Sequence Blend • Skin • Sort • Sphere • Spring • Sprite • Stitch • Subdivide • Superquad • Surfsect • Sweep • Switch • Text • Texture • Torus • Trace • Trail • Transform • Trim • Tristrip • Tube • Twist • Vertex • Wireframe • ZED

An Operator Family that reads, creates and modifies 3D polygons, curves, NURBS surfaces, spheres, meatballs and other 3D surface data.

A text string that contains data (string, float, list, boolean, etc.) and operators (+ * < etc) that are evaluated by the node's language (python or Tscript) and returns a string, float list or boolean, etc. Expressions are used in parameters, DATs and in scripts.

A way of moving data from one TouchDesigner process to another. Images are moved via Touch Out / In TOPs, channels are moved via Touch Out / In CHOPs and Pipe Out / In CHOPs. Data moves via TCP/IP or UDP.