Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HW3 Submission #11

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 16 additions & 59 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,67 +1,24 @@

The objective of this assignment is to create an L System parser and generate interesting looking plants. Start by forking and then cloning this repository: [https://github.com/CIS700-Procedural-Graphics/Project3-LSystems](https://github.com/CIS700-Procedural-Graphics/Project3-LSystems)
Here is the HW submission: [HERE](https://mccannd.github.io/Project3-LSystems/)

# L-System Parser
Additions to the assignment:
- Ramp shader ground plane
- Tree sways / bends on the GPU. Geometry normals also account for this bend.
- Tree mesh has noise displacement on the GPU, based on precomputed noise texture. The texture is read through a bounding box that is saved in the shader.
- Angle changes to the Turtle / stack work in local axes instead of global axes

lsystem.js contains classes for L-system, Rule, and LinkedList. Here’s our suggested structure:
Submitted system: a christmas tree

**The Symbol Nodes/Linked List:**
Axiom : MB

Rather than representing our symbols as a string like in many L-system implementations, we prefer to use a linked list. This allows us to store additional information about each symbol at time of parsing (e.g. what iteration was this symbol added in?) Since we’re adding and replacing symbols at each iteration, we also save on the overhead of creating and destroying strings, since linked lists of course make it easy to add and remove nodes. You should write a Linked List class with Nodes that contain at least the following information:
Rules:
X -->
10% : \[lFFX\]\[rFFX\]>FFX
10% : \[lFFX\]\[rFFX\]-FFX
10% : X
70% : \[lFFX\]\[rFFX\]FFX

- The next node in the linked list
- The previous node in the linked list
- The grammar symbol at theis point in the overal string
B --> \[++++X\]<<<\[++++X\]<<<\[++++X\]<<<\[++++X\]<MB

We also recommend that you write the following functions to interact with your linked list:
M --> MF

- A function to symmetrically link two nodes together (e.g. Node A’s next is Node B, and Node B’s prev is Node A)
- A function to expand one of the symbol nodes of the linked list by replacing it with several new nodes. This function should look at the list of rules associated with the symbol in the linked list’s grammar dictionary, then generate a uniform random number between 0 and 1 in order to determine which of the Rules should be used to expand the symbol node. You will refer to a Rule’s probability and compare it to your random number in order to determine which Rule should be chosen.

**Rules:**

These are containers for the preconditions, postconditions and probability of a single replacement operation. They should operate on a symbol node in your linked list.

**L-system:**

This is the parser, which will loop through your linked list of symbol nodes and apply rules at each iteration.

Implement the following functions in L-System so that you can apply grammar rules to your axiom given some number of iterations. More details and implementation suggestions about functions can be found in the TODO comments

- `stringToLinkedList(input_string)`
- `linkedListToString(linkedList)`
- `replaceNode(linkedList, node, replacementString)`
- `doIterations(num)`

## Turtle

`turtle.js` has a function called renderSymbol that takes in a single node of a linked list and performs an operation to change the turtle’s state based on the symbol contained in the node. Usually, the turtle’s change in state will result in some sort of rendering output, such as drawing a cylinder when the turtle moves forward. We have provided you with a few example functions to illustrate how to write your own functions to be called by renderSymbol; these functions are rotateTurtle, moveTurtle, moveForward, and makeCylinder. If you inspect the constructor of the Turtle class, you can see how to associate an operation with a grammar symbol.

- Modify turtle.js to support operations associated with the symbols `[` and `]`
- When you parse `[` you need to store the current turtle state somewhere
- When you parse `]` you need to set your turtle’s state to the most recently stored state. Think of this a pushing and popping turtle states on and off a stack. For example, given `F[+F][-F]`, the turtle should draw a Y shape. Note that your program must be capable of storing many turtle states at once in a stack.

- In addition to operations for `[` and `]`, you must invent operations for any three symbols of your choosing.


## Interactivity

Using dat.GUI and the examples provided in the reference code, make some aspect of your demo an interactive variable. For example, you could modify:

1. the axiom
2. Your input grammer rules and their probability
3. the angle of rotation of the turtle
4. the size or color or material of the cylinder the turtle draws, etc!

## L-System Plants

Design a grammar for a new procedural plant! As the preceding parts of this assignment are basic computer science tasks, this is where you should spend the bulk of your time on this assignment. Come up with new grammar rules and include screenshots of your plants in your README. For inspiration, take a look at Example 7: Fractal Plant in Wikipedia: https://en.wikipedia.org/wiki/L-system Your procedural plant must have the following features

1. Grow in 3D. Take advantage of three.js!
2. Have flowers or leaves that are added as a part of the grammar
3. Variation. Different instances of your plant should look distinctly different!
4. A twist. Broccoli trees are cool and all, but we hope to see sometime a little more surprising in your grammars

# Publishing Your code

Running `npm run deploy` will automatically build your project and push it to gh-pages where it will be visible at `username.github.io/repo-name`. NOTE: You MUST commit AND push all changes to your MASTER branch before doing this or you may lose your work. The `git` command must also be available in your terminal or command prompt. If you're using Windows, it's a good idea to use Git Bash.
Binary file added groundRamp.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added multicolorfractal.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added multicolorperlin.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added multicolorperlin2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
141 changes: 136 additions & 5 deletions src/lsystem.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,135 @@ function Rule(prob, str) {
this.successorString = str; // The string that will replace the char that maps to this Rule
}



// TODO: Implement a linked list class and its requisite functions
// as described in the homework writeup
export class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.count = 0;
}

pushFront(symbol) {
var node = {
symbol : symbol,
next : this.head,
prev : null
}

if (this.count == 0) {
this.head = node;
this.tail = node;
} else {
this.head.prev = node;
this.head = node;
}

this.count++;
}

pushBack(symbol) {
var node = {
symbol : symbol,
prev : this.tail,
next : null
}

if (this.count == 0) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this.count++;
}

insertBetween(symbol, prev, next) {
var node = {
symbol : symbol,
prev : prev,
next : next
}
prev.next = node;
next.prev = node;
this.count++;
}

}

// TODO: Turn the string into linked list
// Turn the string into linked list
export function stringToLinkedList(input_string) {
// ex. assuming input_string = "F+X"
// you should return a linked list where the head is
// at Node('F') and the tail is at Node('X')
var ll = new LinkedList();
//console.log(input_string);
for (var i = 0; i < input_string.length; i++) {
ll.pushBack(input_string.charAt(i));
}

return ll;
}

// TODO: Return a string form of the LinkedList
export function linkedListToString(linkedList) {
// ex. Node1("F")->Node2("X") should be "FX"
var result = "";
for (var current = linkedList.head; current != null; current = current.next) {
result += current.symbol;
}

return result;
}

// TODO: Given the node to be replaced,
// insert a sub-linked-list that represents replacementString
function replaceNode(linkedList, node, replacementString) {
var beforeNode = node.prev;
var afterNode = node.next;
//console.log(replacementString);
var replacement = stringToLinkedList(replacementString);

replacement.head.prev = beforeNode;
replacement.tail.next = afterNode;

if (node == linkedList.head) {
linkedList.head = replacement.head;
} else {
beforeNode.next = replacement.head;
}

if (node == linkedList.tail) {
linkedList.tail = replacement.tail;
} else {
afterNode.prev = replacement.tail;
}


}

export default function Lsystem(axiom, grammar, iterations) {
// default LSystem
this.axiom = "FX";
this.axiom = "MB";
this.grammar = {};
/*this.grammar['X'] = [
new Rule(1.0, '[-<FX][+<FX]')
];*/
this.grammar['X'] = [
new Rule(1.0, '[-FX][+FX]')
new Rule(0.1, '[lFFX][rFFX]>FFX'),
new Rule(0.1, '[lFFX][rFFX]-FFX'),
new Rule(0.1, 'X'),
new Rule(0.7, '[lFFX][rFFX]FFX')
];

this.grammar['B'] = [
new Rule(1.0, '[++++X]<<<[++++X]<<<[++++X]<<<[++++X]<MB')
];
this.grammar['M'] = [
new Rule(1.0, 'MF')
];
this.iterations = 0;

Expand Down Expand Up @@ -64,13 +163,45 @@ export default function Lsystem(axiom, grammar, iterations) {
}
}

// TODO
// This function returns a linked list that is the result
// of expanding the L-system's axiom n times.
// The implementation we have provided you just returns a linked
// list of the axiom.
this.doIterations = function(n) {
var lSystemLL = StringToLinkedList(this.axiom);
var lSystemLL = stringToLinkedList(this.axiom);
// for each iteration
for (var iter = 0; iter < n; iter++) {
// for each symbol of the original string
var current = lSystemLL.head;
while(current != null) {
var symbol = current.symbol;
if (this.grammar[symbol] != undefined) {
// have replacement rule

// save position of next original node
var newNext = current.next;

// pick a random rule from the grammar
var r = Math.random();
var ruleset = this.grammar[symbol];
var nString = ruleset[0].successorString;
var totalProb = 0.0;
for (var i = 0; i < ruleset.length; i++) {
totalProb += ruleset[i].probability;
if (r <= totalProb) {
nString = ruleset[i].successorString;
break;
}
}

replaceNode(lSystemLL, current, nString);
current = newNext;
} else {
current = current.next;
}
}
}
console.log(linkedListToString(lSystemLL));
return lSystemLL;
}
}
24 changes: 21 additions & 3 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,23 @@ function onLoad(framework) {
camera.position.set(1, 1, 2);
camera.lookAt(new THREE.Vector3(0,0,0));

var sUniforms = {
ramp: {
type: "t",
value: THREE.ImageUtils.loadTexture('./groundRamp.png')
},
};

var planeMat = new THREE.ShaderMaterial({
uniforms : sUniforms,
vertexShader: require('./shaders/floor_vert.glsl'),
fragmentShader: require('./shaders/floor_frag.glsl')
});
var planeGeom = new THREE.PlaneGeometry(100, 100);
var planeObj = new THREE.Mesh(planeGeom, planeMat);
scene.add(planeObj);
planeObj.rotateX(-Math.PI / 2.0);

// initialize LSystem and a Turtle to draw
var lsys = new Lsystem();
turtle = new Turtle(scene);
Expand All @@ -34,7 +51,7 @@ function onLoad(framework) {
});

gui.add(lsys, 'axiom').onChange(function(newVal) {
lsys.UpdateAxiom(newVal);
lsys.updateAxiom(newVal);
doLsystem(lsys, lsys.iterations, turtle);
});

Expand All @@ -47,21 +64,22 @@ function onLoad(framework) {
// clears the scene by removing all geometries added by turtle.js
function clearScene(turtle) {
var obj;
for( var i = turtle.scene.children.length - 1; i > 3; i--) {
for( var i = turtle.scene.children.length - 1; i > 4; i--) {
obj = turtle.scene.children[i];
turtle.scene.remove(obj);
}
}

function doLsystem(lsystem, iterations, turtle) {
var result = lsystem.DoIterations(iterations);
var result = lsystem.doIterations(iterations);
turtle.clear();
turtle = new Turtle(turtle.scene);
turtle.renderSymbols(result);
}

// called on frame updates
function onUpdate(framework) {
if (turtle !== undefined) turtle.updateTime();
}

// when the scene is done initializing, it will call onLoad, then on frame updates, call onUpdate
Expand Down
11 changes: 11 additions & 0 deletions src/shaders/floor_frag.glsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
varying vec2 vUv;
uniform sampler2D ramp;
void main() {
float xd = vUv.x - 0.5;
float yd = vUv.y - 0.5;

float dist = sqrt(xd * xd + yd * yd);
float u = min(dist * 2.0, 1.0);
vec4 col = texture2D(ramp, vec2(0.5, u));
gl_FragColor = col;
}
6 changes: 6 additions & 0 deletions src/shaders/floor_vert.glsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
varying vec2 vUv;

void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 );
}
23 changes: 23 additions & 0 deletions src/shaders/lsystem_frag.glsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
varying float h;
varying vec3 n;
varying float u;
varying float l;

vec3 lerpvec(in vec3 a, in vec3 b, in float t)
{
float tx = t * b[0] + (1.0 - t) * a[0];
float ty = t * b[1] + (1.0 - t) * a[1];
float tz = t * b[2] + (1.0 - t) * a[2];
return vec3(tx, ty, tz);
}


void main() {
vec3 base = vec3(0.1, 0.5, 0.16);
vec3 trunk = vec3(0.2, 0.11, 0.02);
vec3 c1 = lerpvec(trunk, base, pow(u, 0.7));
vec3 col = lerpvec(c1, vec3(1.0, 1.0, 0.5) * n, 0.15);
col = lerpvec(vec3(0.15, 0.03, 0.15), col, l);
//gl_FragColor = vec4( h, h, h, 1.0 );
gl_FragColor = vec4(col, 1.0 );
}
Loading