diff --git a/README.md b/README.md index 5ca56be..64e1938 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,45 @@ +# Nick's L-System Parser and Alien Tree -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) +[https://nnewberg.github.io/Project3-LSystems/](https://nnewberg.github.io/Project3-LSystems/) -# L-System Parser +##Axiom and Grammar -lsystem.js contains classes for L-system, Rule, and LinkedList. Here’s our suggested structure: +I used the axiom: -**The Symbol Nodes/Linked List:** +``` +FX +``` +

+Where,
-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: +``` +X --> FX[+F--FX][-F++FX][UFVVFX][VFUUFX] +``` +

+And
+``` +U +``` +and +``` +V +``` +rotate about the z axis + and - respectively.

-- The next node in the linked list -- The previous node in the linked list -- The grammar symbol at theis point in the overal string +The user can manipulate the angle of the buds +

-We also recommend that you write the following functions to interact with your linked list: +##Pics or it didn't happen +![alt text](https://github.com/nnewberg/Project3-LSystems/blob/master/img/Screen%20Shot%202017-02-07%20at%2012.23.33%20PM.png?raw=true) -- 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. +![alt text](https://github.com/nnewberg/Project3-LSystems/blob/master/img/Screen%20Shot%202017-02-07%20at%2012.23.43%20PM.png?raw=true) -**Rules:** +![alt text](https://github.com/nnewberg/Project3-LSystems/blob/master/img/Screen%20Shot%202017-02-07%20at%2012.24.02%20PM.png?raw=true) -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. +![alt text](https://github.com/nnewberg/Project3-LSystems/blob/master/img/Screen%20Shot%202017-02-07%20at%2012.24.33%20PM.png?raw=true) -**L-system:** +![alt text](https://github.com/nnewberg/Project3-LSystems/blob/master/img/Screen%20Shot%202017-02-07%20at%2012.47.22%20PM.png?raw=true) -This is the parser, which will loop through your linked list of symbol nodes and apply rules at each iteration. +![alt text](https://github.com/nnewberg/Project3-LSystems/blob/master/img/Screen%20Shot%202017-02-07%20at%2012.48.03%20PM.png?raw=true) -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. \ No newline at end of file +![alt text](https://github.com/nnewberg/Project3-LSystems/blob/master/img/Screen%20Shot%202017-02-07%20at%2012.53.21%20PM.png?raw=true) \ No newline at end of file diff --git a/img/Screen Shot 2017-02-07 at 12.23.33 PM.png b/img/Screen Shot 2017-02-07 at 12.23.33 PM.png new file mode 100644 index 0000000..417e867 Binary files /dev/null and b/img/Screen Shot 2017-02-07 at 12.23.33 PM.png differ diff --git a/img/Screen Shot 2017-02-07 at 12.23.43 PM.png b/img/Screen Shot 2017-02-07 at 12.23.43 PM.png new file mode 100644 index 0000000..00dd6dc Binary files /dev/null and b/img/Screen Shot 2017-02-07 at 12.23.43 PM.png differ diff --git a/img/Screen Shot 2017-02-07 at 12.24.02 PM.png b/img/Screen Shot 2017-02-07 at 12.24.02 PM.png new file mode 100644 index 0000000..ffe7572 Binary files /dev/null and b/img/Screen Shot 2017-02-07 at 12.24.02 PM.png differ diff --git a/img/Screen Shot 2017-02-07 at 12.24.19 PM.png b/img/Screen Shot 2017-02-07 at 12.24.19 PM.png new file mode 100644 index 0000000..d566eff Binary files /dev/null and b/img/Screen Shot 2017-02-07 at 12.24.19 PM.png differ diff --git a/img/Screen Shot 2017-02-07 at 12.24.33 PM.png b/img/Screen Shot 2017-02-07 at 12.24.33 PM.png new file mode 100644 index 0000000..1deab3f Binary files /dev/null and b/img/Screen Shot 2017-02-07 at 12.24.33 PM.png differ diff --git a/img/Screen Shot 2017-02-07 at 12.47.22 PM.png b/img/Screen Shot 2017-02-07 at 12.47.22 PM.png new file mode 100644 index 0000000..de85358 Binary files /dev/null and b/img/Screen Shot 2017-02-07 at 12.47.22 PM.png differ diff --git a/img/Screen Shot 2017-02-07 at 12.48.03 PM.png b/img/Screen Shot 2017-02-07 at 12.48.03 PM.png new file mode 100644 index 0000000..5023193 Binary files /dev/null and b/img/Screen Shot 2017-02-07 at 12.48.03 PM.png differ diff --git a/img/Screen Shot 2017-02-07 at 12.53.21 PM.png b/img/Screen Shot 2017-02-07 at 12.53.21 PM.png new file mode 100644 index 0000000..2363260 Binary files /dev/null and b/img/Screen Shot 2017-02-07 at 12.53.21 PM.png differ diff --git a/package.json b/package.json index be683fc..22de833 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "dependencies": { "dat-gui": "^0.5.0", "gl-matrix": "^2.3.2", + "require-module": "^0.1.0", "stats-js": "^1.0.0-alpha1", "three": "^0.82.1", "three-orbit-controls": "^82.1.0" diff --git a/src/lsystem.js b/src/lsystem.js index e643b6d..6d38579 100644 --- a/src/lsystem.js +++ b/src/lsystem.js @@ -5,6 +5,76 @@ function Rule(prob, str) { this.successorString = str; // The string that will replace the char that maps to this Rule } +function Node(){ + this.symbol =''; + this.next = null; + this.prev = null; +} + +function Node(symbol){ + + if (typeof symbol !== "undefined"){ + this.symbol = symbol; + } +} + +function LinkedList(){ + this.head = null; + this.tail = null; + this.size = 0; +} + +//insert node_b after node_a +function insertAfterLinkedList(linkedList, node_a, node_b){ + node_b.next = node_a.next; + node_a.next = node_b; + node_b.prev = node_a; + linkedList.size ++; +} + +function addLastLinkedList(linkedList, node){ + if (linkedList.head == null){ + linkedList.head = node; + linkedList.tail = node; + linkedList.size++; + return; + } + //if nonempty linkedlist, add to the end + linkedList.tail.next = node; + node.prev = linkedList.tail; + linkedList.tail = node; //update the tail + linkedList.size++; +} + +export function testLinkedList(){ + + // var gram = {}; + // gram['X'] = [ + // //new Rule(1.0, '[-FX][+FX]') + // new Rule(1.0, '[UFVFX][VFX][JFX][KFX]') + + // ]; + // var ls = new Lsystem("FX", gram, 1); + + // var ll = stringToLinkedList("[-FX][+FX]"); + // console.log(ll); + + // var ll = stringToLinkedList(ls.axiom); + // ll = ls.doIteration(ll); + // console.log(linkedListToString(ll)); + // ll = ls.doIteration(ll); + // console.log(linkedListToString(ll)); + + //console.log(ll); + //console.log(ls.doIteration(ll)); + // console.log(linkedListToString(ls.doIterations(0))); + // console.log(linkedListToString(ls.doIterations(1))); + // console.log(linkedListToString(ls.doIterations(2))); + // console.log(linkedListToString(ls.doIterations(3))); + + +} + // TODO: Implement a linked list class and its requisite functions // as described in the homework writeup @@ -14,29 +84,89 @@ export function stringToLinkedList(input_string) { // you should return a linked list where the head is // at Node('F') and the tail is at Node('X') var ll = new LinkedList(); + for (var i = 0; i < input_string.length; i++){ + addLastLinkedList(ll, new Node(input_string[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 = ""; + var tmp_node = linkedList.head; + while(tmp_node != null){ + result += tmp_node.symbol; + tmp_node = tmp_node.next; + } return result; } +function nodesEqual(node1, node2){ + if (typeof node1 !== "undefined" && + typeof node2 !== "undefined") { + + return (node1.symbol == node2.symbol); + }else{ + return false; + } + +} + + // TODO: Given the node to be replaced, // insert a sub-linked-list that represents replacementString function replaceNode(linkedList, node, replacementString) { + + // var tmp_node = linkedList.head; + // while(tmp_node != null){ + + // if (tmp_node == null){return;} + + // if (nodesEqual(tmp_node, node)){ + var replacementLL = stringToLinkedList(replacementString); + + if (node.prev != null){ + replacementLL.head.prev = node.prev; + node.prev.next = replacementLL.head; + }else{ + linkedList.head = replacementLL.head; + } + + if (node.next != null){ + node.next.prev = replacementLL.tail; + replacementLL.tail.next = node.next; + }else{ + linkedList.tail = replacementLL.tail; + } + + linkedList.size += replacementLL.size - 1; + // } + + // tmp_node = tmp_node.next; + + // } + } export default function Lsystem(axiom, grammar, iterations) { + // default LSystem this.axiom = "FX"; this.grammar = {}; this.grammar['X'] = [ - new Rule(1.0, '[-FX][+FX]') + new Rule(0.75, 'FX[+F--FX][-F++FX][UFVVFX][VFUUFX]') + //new Rule(1.0, '[--F++F++F++F++F+++F+++F++++FX]') + ]; - this.iterations = 0; + // this.grammar['F'] = [ + // // new Rule(1.0, '[-FX][+FX]') + // new Rule(1.0, 'FF') + // ]; + + + this.iterations = 5; // Set up the axiom string if (typeof axiom !== "undefined") { @@ -69,8 +199,57 @@ export default function Lsystem(axiom, grammar, iterations) { // of expanding the L-system's axiom n times. // The implementation we have provided you just returns a linked // list of the axiom. + + this.doIteration = function(origLL){ + + var symbolsSeen = []; + //var newLL = stringToLinkedList(linkedListToString(origLL)); + var tmp_node = origLL.head; + + while(tmp_node != null){//iterate through all nodes of ORIGINAL + + var symbol = tmp_node.symbol; + + //only replace the node if we haven't seen it and there's a rule + // if (symbol in this.grammar && symbolsSeen.indexOf(symbol) == -1){ + //replace the character if we have a rule in our grammer + if (symbol in this.grammar){ + + var coinToss = Math.random() < this.grammar[symbol][0].probability; + + // coinToss = true; + if(coinToss){ + var replacementString = this.grammar[symbol][0].successorString; + replaceNode(origLL, tmp_node, replacementString); + symbolsSeen.push(symbol); + + }else{ + replaceNode(origLL, tmp_node, "FX"); + + } + } + + + + // } + + tmp_node = tmp_node.next; + + } + + return origLL; + } + this.doIterations = function(n) { - var lSystemLL = StringToLinkedList(this.axiom); + + var lSystemLL = stringToLinkedList(this.axiom); + + for (var i = 0; i < n; i ++){ //do the replacement n times + + lSystemLL = this.doIteration(lSystemLL); + + } + return lSystemLL; } } \ No newline at end of file diff --git a/src/main.js b/src/main.js index f0c6600..69b1706 100644 --- a/src/main.js +++ b/src/main.js @@ -1,10 +1,11 @@ const THREE = require('three'); // older modules are imported like this. You shouldn't have to worry about this much import Framework from './framework' -import Lsystem, {LinkedListToString} from './lsystem.js' +import Lsystem, {linkedListToString, testLinkedList} from './lsystem.js' import Turtle from './turtle.js' var turtle; +var lsys; // called after the scene loads function onLoad(framework) { @@ -22,11 +23,14 @@ function onLoad(framework) { scene.add(directionalLight); // set camera position - camera.position.set(1, 1, 2); - camera.lookAt(new THREE.Vector3(0,0,0)); + camera.position.set(1, 50, 50); + camera.lookAt(new THREE.Vector3(0,20,0)); + + //test + testLinkedList(); // initialize LSystem and a Turtle to draw - var lsys = new Lsystem(); + lsys = new Lsystem(); turtle = new Turtle(scene); gui.add(camera, 'fov', 0, 180).onChange(function(newVal) { @@ -34,14 +38,28 @@ function onLoad(framework) { }); gui.add(lsys, 'axiom').onChange(function(newVal) { - lsys.UpdateAxiom(newVal); + lsys.updateAxiom(newVal); doLsystem(lsys, lsys.iterations, turtle); }); + gui.add(turtle, 'angle', 0, 180).step(1).onChange(function(newVal) { + clearScene(turtle); + turtle.clear(); + turtle.updateAngle(newVal); + var result = lsys.doIterations(lsys.iterations); + turtle.iterations = lsys.iterations; + turtle.renderSymbols(result); + + //doLsystem(lsys, lsys.iterations, turtle); + }); + gui.add(lsys, 'iterations', 0, 12).step(1).onChange(function(newVal) { clearScene(turtle); doLsystem(lsys, newVal, turtle); }); + + doLsystem(lsys, 5, turtle); + } // clears the scene by removing all geometries added by turtle.js @@ -54,9 +72,10 @@ function clearScene(turtle) { } function doLsystem(lsystem, iterations, turtle) { - var result = lsystem.DoIterations(iterations); + var result = lsystem.doIterations(iterations); turtle.clear(); turtle = new Turtle(turtle.scene); + turtle.iterations = iterations; turtle.renderSymbols(result); } diff --git a/src/shaders/tree-frag.glsl b/src/shaders/tree-frag.glsl new file mode 100644 index 0000000..de1ecfa --- /dev/null +++ b/src/shaders/tree-frag.glsl @@ -0,0 +1,25 @@ +varying vec3 vPos; +uniform float uCylY; +uniform float uIters; + +void main() { +vec3 yellow, magenta, green, blue; + +blue.rg = vec2(0.0); +blue[2] = 1.0; + +// Making Yellow +yellow.rg = vec2(1.0); // Assigning 1. to red and green channels +yellow[2] = 0.0; // Assigning 0. to blue channel + +// Making Magenta +magenta = yellow.rbg; // Assign the channels with green and blue swapped + +// Making Green +green.rgb = yellow.bgb; // Assign the blue channel of Yellow (0) to red and blue channels + + vec3 color = mix(blue, green, uCylY/(uIters*10.0)); + + gl_FragColor = vec4( color.rgb, 1.0 ); + +} \ No newline at end of file diff --git a/src/shaders/tree-vert.glsl b/src/shaders/tree-vert.glsl new file mode 100644 index 0000000..052bedf --- /dev/null +++ b/src/shaders/tree-vert.glsl @@ -0,0 +1,6 @@ +varying vec3 vPos; + +void main() { + vPos = position; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +} \ No newline at end of file diff --git a/src/turtle.js b/src/turtle.js index 1db2723..e281495 100644 --- a/src/turtle.js +++ b/src/turtle.js @@ -16,14 +16,24 @@ export default class Turtle { constructor(scene, grammar) { this.state = new TurtleState(new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0)); this.scene = scene; + this.savedStates = []; + this.angle = 30.0; + this.iterations = 0; + //this.angle = 30.0; // TODO: Start by adding rules for '[' and ']' then more! // Make sure to implement the functions for the new rules inside Turtle if (typeof grammar === "undefined") { this.renderGrammar = { - '+' : this.rotateTurtle.bind(this, 30, 0, 0), - '-' : this.rotateTurtle.bind(this, -30, 0, 0), - 'F' : this.makeCylinder.bind(this, 2, 0.1) + '+' : this.rotateTurtle.bind(this, 1.0, 0, 0), + '-' : this.rotateTurtle.bind(this, -1.0, 0, 0), + 'U' : this.rotateTurtle.bind(this, 0.0, 0, 1.0), + 'V' : this.rotateTurtle.bind(this, 0.0, 0, -1.0), + 'J' : this.rotateTurtle.bind(this, 0.0, 1.0, 0), + 'K' : this.rotateTurtle.bind(this, 0.0, -1.0, 0.0), + 'F' : this.makeCylinder.bind(this, 2, 0.05), + '[' : this.storeState.bind(this), + ']' : this.restoreState.bind(this) }; } else { this.renderGrammar = grammar; @@ -46,10 +56,16 @@ export default class Turtle { // Rotate the turtle's _dir_ vector by each of the // Euler angles indicated by the input. rotateTurtle(x, y, z) { + + // if(x > 0){ + // x = this.angle; + // }else{ + // x = -this.angle; + // } var e = new THREE.Euler( - x * 3.14/180, - y * 3.14/180, - z * 3.14/180); + x * this.angle * 3.14/180, + y * this.angle * 3.14/180, + z * this.angle * 3.14/180); this.state.dir.applyEuler(e); } @@ -70,8 +86,22 @@ export default class Turtle { // Moves turtle pos ahead to end of the new cylinder makeCylinder(len, width) { var geometry = new THREE.CylinderGeometry(width, width, len); + + //Move the cylinder so its base rests at the turtle's current position + var mat5 = new THREE.Matrix4(); + var trans = this.state.pos.add(this.state.dir.multiplyScalar(0.5 * len)); + mat5.makeTranslation(trans.x, trans.y, trans.z); + + var treeMaterial = new THREE.ShaderMaterial({ + uniforms: { + uCylY: {value: trans.y}, + uIters: {value: this.iterations} + }, + vertexShader: require('./shaders/tree-vert.glsl'), + fragmentShader: require('./shaders/tree-frag.glsl') + }); var material = new THREE.MeshBasicMaterial( {color: 0x00cccc} ); - var cylinder = new THREE.Mesh( geometry, material ); + var cylinder = new THREE.Mesh( geometry, treeMaterial ); this.scene.add( cylinder ); //Orient the cylinder to the turtle's current direction @@ -82,10 +112,6 @@ export default class Turtle { cylinder.applyMatrix(mat4); - //Move the cylinder so its base rests at the turtle's current position - var mat5 = new THREE.Matrix4(); - var trans = this.state.pos.add(this.state.dir.multiplyScalar(0.5 * len)); - mat5.makeTranslation(trans.x, trans.y, trans.z); cylinder.applyMatrix(mat5); //Scoot the turtle forward by len units @@ -96,7 +122,7 @@ export default class Turtle { // Look in the Turtle's constructor for examples of how to bind // functions to grammar symbols. renderSymbol(symbolNode) { - var func = this.renderGrammar[symbolNode.character]; + var func = this.renderGrammar[symbolNode.symbol]; if (func) { func(); } @@ -109,4 +135,20 @@ export default class Turtle { this.renderSymbol(currentNode); } } + + storeState(){ + this.savedStates.push(new TurtleState(this.state.pos, this.state.dir)); + // console.log("SAVED"); + // console.log(this.state.pos); + }; + + restoreState(){ + this.state = this.savedStates.pop(); + // console.log("RESTORED"); + // console.log(this.state.pos); + }; + + updateAngle(newAngle){ + this.angle = newAngle; + } } \ No newline at end of file