diff --git a/README.md b/README.md index 5ca56be..c15db78 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,32 @@ +# [L System Tree](https://anvidalal.github.io/LSystems/) -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) + -# L-System Parser +## Objective -lsystem.js contains classes for L-system, Rule, and LinkedList. Here’s our suggested structure: +Learn L Systems by making trees. -**The Symbol Nodes/Linked List:** +## Process -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: +I started off by writing a doubly linked list to represent my L-System. Once had that down, I introduced the variable of iteration to see what my tree would look like at different steps.
+ -- The next node in the linked list -- The previous node in the linked list -- The grammar symbol at theis point in the overal string +Next, I added width to my tree, such that it was inversely proportional to the iteration.
+ -We also recommend that you write the following functions to interact with your linked list: +I added texture to my branches to make it look more like a tree.
+ -- 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. +I then played altered how my width changes with each iteration.
+ -**Rules:** +Finally I added leaves to every branch in my linked list that was at the last iteration.
+ -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. \ No newline at end of file +After some tweaks in the grammar, I was able to achieve some really random looking trees.
+ + + + + + diff --git a/src/lsystem.js b/src/lsystem.js index e643b6d..44f50ca 100644 --- a/src/lsystem.js +++ b/src/lsystem.js @@ -1,76 +1,224 @@ // A class that represents a symbol replacement rule to // be used when expanding an L-system grammar. function Rule(prob, str) { - this.probability = prob; // The probability that this Rule will be used when replacing a character in the grammar string - this.successorString = str; // The string that will replace the char that maps to this Rule + this.probability = prob; // The probability that this Rule will be used when replacing a character in the grammar string + 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 +function Node(symbol, iter) { + this.next = null; + this.prev = null; + this.symbol = symbol; + this.iter = iter; +} + +function LinkedList() { + this.head = null; + this.length = 0; +} + +LinkedList.prototype.getTailNode = function() { + var currentNode = this.head; + while (currentNode.next != null) { + currentNode = currentNode.next; + } + return currentNode; +} + +LinkedList.prototype.add = function(symbol, iter) { + var node = new Node(symbol, iter); + var currentNode = this.head; + if (currentNode == null) { + this.head = node; + this.length = 1; + return; + } + var tail = this.getTailNode(); + this.link(tail, node); + this.length++; +} + +LinkedList.prototype.link = function(first, second) { + if (first != null) + { + first.next = second; + if (second != null) + { + second.prev = first; + } + } +} // TODO: 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(); - return ll; +export function stringToLinkedList(input_string, iter) { + // 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(); + for (var i = 0; i < input_string.length; i++) { + ll.add(input_string[i], iter); + } + return ll; } // TODO: Return a string form of the LinkedList export function linkedListToString(linkedList) { - // ex. Node1("F")->Node2("X") should be "FX" - var result = ""; - return result; + // ex. Node1("F")->Node2("X") should be "FX" + var result = ""; + var currentNode = linkedList.head; + while (currentNode != null) { + result += currentNode.symbol; + currentNode = currentNode.next; + } + return result; } // TODO: Given the node to be replaced, // insert a sub-linked-list that represents replacementString -function replaceNode(linkedList, node, replacementString) { +function replaceNode(linkedList, node, replacementString, iter) { + + var nodeBefore = node.prev; + var nodeAfter = node.next; + + var stringList = stringToLinkedList(replacementString, iter); + var tail = stringList.getTailNode(); + + if (nodeBefore == null && nodeAfter == null) { + linkedList.head = stringList.head; + } + else if (nodeBefore == null) + { + linkedList.head = stringList.head; + linkedList.link(tail, nodeAfter); + } + else if (nodeAfter == null) { + linkedList.link(nodeBefore, stringList.head); + } + else { + linkedList.link(nodeBefore, stringList.head); + linkedList.link(tail, nodeAfter); + } + + linkedList.length+= replacementString.length - 1; + return linkedList; +} + +function addLeaves(linkedList, iter) +{ + for(var currentNode = linkedList.head; currentNode != null; currentNode = currentNode.next) { + if (currentNode.symbol == 'F' && currentNode.iter == iter) + { + var node = new Node('L', iter + 1); + var next = currentNode.next; + linkedList.link(currentNode, node); + if (next) + { + linkedList.link(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]') - ]; - this.iterations = 0; - - // Set up the axiom string - if (typeof axiom !== "undefined") { - this.axiom = axiom; - } - - // Set up the grammar as a dictionary that - // maps a single character (symbol) to a Rule. - if (typeof grammar !== "undefined") { - this.grammar = Object.assign({}, grammar); - } - - // Set up iterations (the number of times you - // should expand the axiom in DoIterations) - if (typeof iterations !== "undefined") { - this.iterations = iterations; - } - - // A function to alter the axiom string stored - // in the L-system - this.updateAxiom = function(axiom) { - // Setup axiom - if (typeof axiom !== "undefined") { - this.axiom = axiom; - } - } - - // 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); - return lSystemLL; - } + // default LSystem + this.axiom = "FKKX"; + this.grammar = {}; + this.grammar['X'] = [ + new Rule(0.2, '[-FX][+FX][FX]'), + new Rule(0.1, '[-FXG][+FX][FX]'), + new Rule(0.1, '[-FX][FX]'), + new Rule(0.1, '[+FX][FXG]'), + new Rule(0.1, '[-FX]'), + new Rule(0.1, '[+FX]'), + new Rule(0.1, '[FX]'), + + ]; + this.grammar['G'] = [ + new Rule(0.8, 'G'), + new Rule(0.2, 'L') + ]; + this.grammar['K'] = [ + new Rule(0.5, 'K'), + new Rule(0.5, 'X') + ]; + this.iterations = 0; + + // Set up the axiom string + if (typeof axiom !== "undefined") { + this.axiom = axiom; + } + + // Set up the grammar as a dictionary that + // maps a single character (symbol) to a Rule. + if (typeof grammar !== "undefined") { + this.grammar = Object.assign({}, grammar); + } + + // Set up iterations (the number of times you + // should expand the axiom in DoIterations) + if (typeof iterations !== "undefined") { + this.iterations = iterations; + //this.doIterations(iterations); + } + + // A function to alter the axiom string stored + // in the L-system + this.updateAxiom = function(axiom) { + // Setup axiom + if (typeof axiom !== "undefined") { + this.axiom = axiom; + } + } + + // A function to alter the axiom string stored + // in the L-system + this.updateGrammar = function(rule) { + // Setup axiom + if (typeof axiom !== "undefined") { + this.axiom = axiom; + } + } + + // 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, 0); + + for (var i = 0; i < n; i++) { + var currentNode = lSystemLL.head; + + while (currentNode != null) { + var next = currentNode.next; + var symbol = currentNode.symbol; + var iter = currentNode.iter; + + if (this.grammar[symbol]) + { + var rand = Math.random(); + var sum = 0.0; + var rules = this.grammar[symbol]; + for (var j = 0; j < rules.length; j++) + { + sum += rules[j].probability; + if (rand <= sum) + { + replaceNode(lSystemLL, currentNode, rules[j].successorString, i + 1); + break; + } + } + } + currentNode = next; + } + } + addLeaves(lSystemLL, n); + //console.log(linkedListToString(lSystemLL)); + return lSystemLL; + } } \ No newline at end of file diff --git a/src/main.js b/src/main.js index f0c6600..7718ac2 100644 --- a/src/main.js +++ b/src/main.js @@ -1,10 +1,15 @@ 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} from './lsystem.js' import Turtle from './turtle.js' var turtle; +var userInput = { + iterations : 4, + width : 0.2, + angle : 60 +} // called after the scene loads function onLoad(framework) { @@ -22,23 +27,29 @@ function onLoad(framework) { scene.add(directionalLight); // set camera position - camera.position.set(1, 1, 2); + camera.position.set(22, 3, 0); camera.lookAt(new THREE.Vector3(0,0,0)); // initialize LSystem and a Turtle to draw var lsys = new Lsystem(); - turtle = new Turtle(scene); + turtle = new Turtle(scene, userInput.angle, userInput.width); + doLsystem(lsys, userInput.iterations, turtle); gui.add(camera, 'fov', 0, 180).onChange(function(newVal) { camera.updateProjectionMatrix(); }); - gui.add(lsys, 'axiom').onChange(function(newVal) { - lsys.UpdateAxiom(newVal); - doLsystem(lsys, lsys.iterations, turtle); + gui.add(userInput, 'width', 0, 1).onChange(function(newVal) { + clearScene(turtle); + doLsystem(lsys, userInput.iterations, turtle); + }); + + gui.add(userInput, 'angle', 0, 180).onChange(function(newVal) { + clearScene(turtle); + doLsystem(lsys, userInput.iterations, turtle); }); - gui.add(lsys, 'iterations', 0, 12).step(1).onChange(function(newVal) { + gui.add(userInput, 'iterations', 0, 8).step(1).onChange(function(newVal) { clearScene(turtle); doLsystem(lsys, newVal, turtle); }); @@ -54,9 +65,9 @@ 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 = new Turtle(turtle.scene, userInput.angle, userInput.width); turtle.renderSymbols(result); } @@ -65,4 +76,4 @@ function onUpdate(framework) { } // when the scene is done initializing, it will call onLoad, then on frame updates, call onUpdate -Framework.init(onLoad, onUpdate); +Framework.init(onLoad, onUpdate); \ No newline at end of file diff --git a/src/shaders/wood-frag.glsl b/src/shaders/wood-frag.glsl new file mode 100644 index 0000000..5dfa18c --- /dev/null +++ b/src/shaders/wood-frag.glsl @@ -0,0 +1,13 @@ +varying vec2 vUv; +varying float noise; +uniform sampler2D image; + + +void main() { + + vec2 uv = vec2(1,1) - vUv; + vec4 color = texture2D( image, uv ); + + gl_FragColor = vec4( color.rgb, 1.0 ); + +} \ No newline at end of file diff --git a/src/shaders/wood-vert.glsl b/src/shaders/wood-vert.glsl new file mode 100644 index 0000000..cfc274d --- /dev/null +++ b/src/shaders/wood-vert.glsl @@ -0,0 +1,5 @@ +varying vec2 vUv; +void main() { + vUv = uv; + 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..674f369 100644 --- a/src/turtle.js +++ b/src/turtle.js @@ -1,5 +1,17 @@ const THREE = require('three') +var treeMaterial = new THREE.ShaderMaterial({ + uniforms: { + image: { + type: "t", + value: THREE.ImageUtils.loadTexture('./wood.jpg') + } + }, + vertexShader: require('./shaders/wood-vert.glsl'), + fragmentShader: require('./shaders/wood-frag.glsl') + }); +var leafMaterial = new THREE.MeshPhongMaterial( {color: 0x004c00} ); + // A class used to encapsulate the state of a turtle at a given moment. // The Turtle class contains one TurtleState member variable. // You are free to add features to this state class, @@ -13,17 +25,42 @@ var TurtleState = function(pos, dir) { export default class Turtle { - constructor(scene, grammar) { + constructor(scene, angle, width, grammar) { this.state = new TurtleState(new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0)); this.scene = scene; + this.stack = []; + + if (angle) + { + this.angle = angle; + } + else + { + this.angle = 60; + } + + if (width) + { + this.width = width; + } + else + { + this.width = 1.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), + '-' : this.rotateTurtle.bind(this, -1, 0, 0), + '>' : this.rotateTurtle.bind(this, 0, 0, 1), + '<' : this.rotateTurtle.bind(this, 0, 0, -1), + 'F' : this.makeCylinder.bind(this, 2, 0.1), + 'f' : this.moveForward.bind(this, 1), + '[' : this.saveState.bind(this), + ']' : this.applyState.bind(this), + 'L' : this.makeLeaf.bind(this) }; } else { this.renderGrammar = grammar; @@ -34,6 +71,16 @@ export default class Turtle { // and its orientation to the Y axis clear() { this.state = new TurtleState(new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0)); + this.stack = []; + } + + saveState() { + var newState = new TurtleState(this.state.pos, this.state.dir); + this.stack.push(newState); + } + + applyState() { + this.state = this.stack.pop(); } // A function to help you debug your turtle functions @@ -47,17 +94,17 @@ export default class Turtle { // Euler angles indicated by the input. rotateTurtle(x, y, z) { var e = new THREE.Euler( - x * 3.14/180, - y * 3.14/180, - z * 3.14/180); + Math.random() * this.angle * x * 3.14/180, + Math.random() * this.angle * y * 3.14/180, + Math.random() * this.angle * z * 3.14/180); this.state.dir.applyEuler(e); } // Translate the turtle along the input vector. // Does NOT change the turtle's _dir_ vector moveTurtle(x, y, z) { - var new_vec = THREE.Vector3(x, y, z); - this.state.pos.add(new_vec); + var new_vec = THREE.Vector3(x, y, z); + this.state.pos.add(new_vec); }; // Translate the turtle along its _dir_ vector by the distance indicated @@ -68,10 +115,14 @@ export default class Turtle { // Make a cylinder of given length and width starting at turtle pos // Moves turtle pos ahead to end of the new cylinder - makeCylinder(len, width) { - var geometry = new THREE.CylinderGeometry(width, width, len); - var material = new THREE.MeshBasicMaterial( {color: 0x00cccc} ); - var cylinder = new THREE.Mesh( geometry, material ); + makeCylinder(len) { + var width = this.width / (((this.iter + 1) * 0.3) + 0.2); + var geometry = new THREE.CylinderGeometry(width * 0.7, width, len); + if (this.iter == 0 && this.nextIter == 0) + { + geometry = new THREE.CylinderGeometry(width, width, len); + } + var cylinder = new THREE.Mesh( geometry, treeMaterial ); this.scene.add( cylinder ); //Orient the cylinder to the turtle's current direction @@ -91,12 +142,33 @@ export default class Turtle { //Scoot the turtle forward by len units this.moveForward(len/2); }; + + makeLeaf() { + var leafGeometry = new THREE.SphereGeometry( 1, 16, 16 ); + var leaf = new THREE.Mesh(leafGeometry, leafMaterial); + this.scene.add(leaf); + + //Orient the leaf to the turtle's current direction + var quat = new THREE.Quaternion(); + quat.setFromUnitVectors(new THREE.Vector3(0,1,0), this.state.dir); + var mat4 = new THREE.Matrix4(); + mat4.makeRotationFromQuaternion(quat); + leaf.applyMatrix(mat4); + + + //Move the leaf 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)); + mat5.makeTranslation(trans.x, trans.y, trans.z); + leaf.applyMatrix(mat5); + leaf.scale.set(0.4, 0.4, 0.4); + } // Call the function to which the input symbol is bound. // 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(); } @@ -106,6 +178,11 @@ export default class Turtle { renderSymbols(linkedList) { var currentNode; for(currentNode = linkedList.head; currentNode != null; currentNode = currentNode.next) { + this.iter = currentNode.iter; + if (currentNode.next != null) + { + this.nextIter = currentNode.next.iter; + } this.renderSymbol(currentNode); } } diff --git a/tree1.jpg b/tree1.jpg new file mode 100644 index 0000000..0f07994 Binary files /dev/null and b/tree1.jpg differ diff --git a/tree10.jpg b/tree10.jpg new file mode 100644 index 0000000..676d49b Binary files /dev/null and b/tree10.jpg differ diff --git a/tree11.jpg b/tree11.jpg new file mode 100644 index 0000000..b2ba149 Binary files /dev/null and b/tree11.jpg differ diff --git a/tree2.jpg b/tree2.jpg new file mode 100644 index 0000000..6ed42ed Binary files /dev/null and b/tree2.jpg differ diff --git a/tree3.jpg b/tree3.jpg new file mode 100644 index 0000000..8c66aa9 Binary files /dev/null and b/tree3.jpg differ diff --git a/tree4.jpg b/tree4.jpg new file mode 100644 index 0000000..1127706 Binary files /dev/null and b/tree4.jpg differ diff --git a/tree5.jpg b/tree5.jpg new file mode 100644 index 0000000..d4801fd Binary files /dev/null and b/tree5.jpg differ diff --git a/tree6.jpg b/tree6.jpg new file mode 100644 index 0000000..2bbbbde Binary files /dev/null and b/tree6.jpg differ diff --git a/tree7.jpg b/tree7.jpg new file mode 100644 index 0000000..3d52cb6 Binary files /dev/null and b/tree7.jpg differ diff --git a/tree8.jpg b/tree8.jpg new file mode 100644 index 0000000..6bdcf22 Binary files /dev/null and b/tree8.jpg differ diff --git a/tree9.jpg b/tree9.jpg new file mode 100644 index 0000000..f968684 Binary files /dev/null and b/tree9.jpg differ diff --git a/wood.jpg b/wood.jpg new file mode 100644 index 0000000..eca0e3d Binary files /dev/null and b/wood.jpg differ