diff --git a/README.md b/README.md index 5ca56be..336a9c7 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,14 @@ +# [L-System on the web](http://amansachan.com/L-System/) -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) +## Project Description -# L-System Parser +Created an L system incorporating probability, that changes every time +Various GUI controls were added to give the project more life. -lsystem.js contains classes for L-system, Rule, and LinkedList. Here’s our suggested structure: +GUI controls let you: -**The Symbol Nodes/Linked List:** +1. Change the color of the tree -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: +2. Change the number of iterations -- The next node in the linked list -- The previous node in the linked list -- The grammar symbol at theis point in the overal string - -We also recommend that you write the following functions to interact with your linked list: - -- 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. \ No newline at end of file +3. Change the starting axiom diff --git a/src/framework.js b/src/framework.js index 76f901a..fb3fceb 100644 --- a/src/framework.js +++ b/src/framework.js @@ -1,4 +1,3 @@ - const THREE = require('three'); const OrbitControls = require('three-orbit-controls')(THREE) import Stats from 'stats-js' @@ -69,4 +68,4 @@ function init(callback, update) { export default { init: init -} \ No newline at end of file +} diff --git a/src/lsystem.js b/src/lsystem.js index e643b6d..a7680e1 100644 --- a/src/lsystem.js +++ b/src/lsystem.js @@ -1,61 +1,163 @@ // A class that represents a symbol replacement rule to // be used when expanding an L-system grammar. -function Rule(prob, str) { +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 + + //you get the probability, and the replacement string, and using a condition based on that probability use the rule + if(prob > Math.random()) + { + //actually carry out the rule + return str; + } + else + { + return this; + } } // TODO: Implement a linked list class and its requisite functions // as described in the homework writeup +var LinkedList = function(){ + this.first = null; // variables first and last will not be directly accessible because theyre not bound to "this" + this.last =null; //even thought theyre not directly accessible, they exist + + //The actual data held by linked list elements; used for push pop and remove but we actually return the variable LL + var Node = function(value){ + this.grammar = value; + // this.flag_replace = false; + this.next = null; // next is initially just an empty object + this.previous = null; + }; -// TODO: Turn the string into linked list -export function stringToLinkedList(input_string) { + this.push = function(value){ + var node = new Node(value); + if(this.first == null) + { + this.first = node; + this.last = node; + } + else + { + // symlink(last, node); + this.last.next = node; + node.previous = this.last; + this.last = node; + } + return node; + }; + + this.pop = function(){ + var popped_value = this.first.grammar; + this.first = this.first.next; + return popped_value; + }; + return this; +}; + +// 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 + // 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.push(input_string[i]); + } return ll; } // TODO: Return a string form of the LinkedList -export function linkedListToString(linkedList) { +export function linkedListToString(linkedList) +{ // ex. Node1("F")->Node2("X") should be "FX" var result = ""; + var current = linkedList.first; + while (current) + { // while not null + result = result + current.grammar; + current = current.next; + } return result; } -// TODO: Given the node to be replaced, +// 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) +{ + //link the previous node to the one after the current node + var ll = StringToLinkedList(replacementString); + if(node == linkedList.first) + { + console.log("replace first"); + linkedList.first = ll.first; + + node.next.previous = ll.last; + ll.last.next = node.next; + } + else if(node == linkedList.last) + { + linkedList.last = ll.last; + + node.previous.next = ll.first; + ll.first.prev = node.previous; + } + else + { + node.previous.next = ll.first; + ll.first.prev = node.previous; + + node.next.previous = ll.last; + ll.last.next = node.next; + } } export default function Lsystem(axiom, grammar, iterations) { // default LSystem - this.axiom = "FX"; + this.axiom = "FFF+T"; this.grammar = {}; + + //All the grammar rules this.grammar['X'] = [ - new Rule(1.0, '[-FX][+FX]') + // new Rule(0.8, '[-FT][+FT]') + new Rule(0.5, 'F-[[X]+X]+F[+FX]-X'), + new Rule(0.5, 'FF'), + new Rule(0.5, 'X'), + new Rule(0.5, 'F[+FX][-FX]'), + new Rule(0.5, 'F[-FX][+FX]'), + new Rule(1.0, 'LA'), + new Rule(0.6, 'L'), + new Rule(0.5, 'F+[[X]-X]-F[-FX]+X') + ]; + this.grammar['F'] = [ + new Rule(0.3, 'F') ]; - this.iterations = 0; - + this.grammar['T'] = [ + new Rule(0.6, '[FX][aFX][aFX][aFX][aFX][aFX][aFX][aFX][aFX][aFX][aFX][aFX][aFX]') + ]; + this.iterations = 0; + // Set up the axiom string if (typeof axiom !== "undefined") { this.axiom = axiom; } - // Set up the grammar as a dictionary that + // 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 + + // 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 + // A function to alter the axiom string stored // in the L-system this.updateAxiom = function(axiom) { // Setup axiom @@ -65,12 +167,62 @@ export default function Lsystem(axiom, grammar, iterations) { } // TODO - // This function returns a linked list that is the result + // 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) { + this.DoIterations = function(n) { + var grammar_replacement_rule_index = 0; + var count_x = 0; var lSystemLL = StringToLinkedList(this.axiom); + for(var i =0; i < n; i++) + { + //call replace node on every character in the string + var temp = lSystemLL.first; + + while(temp) { + var tempNext = temp.next; + + var grammar_symbol = temp.grammar; + if((i >=1)) + { + if((grammar_symbol == "X")) + { + count_x++; + var grammar_replacement_rule = this.grammar[grammar_symbol][count_x%7]; + var grammar_replacement = grammar_replacement_rule.successorString; + grammar_symbol = grammar_replacement; + } + else if((grammar_symbol == "T") || (grammar_symbol == "F")) + { + var grammar_replacement_rule = this.grammar[grammar_symbol][0]; + var grammar_replacement = grammar_replacement_rule.successorString; + grammar_symbol = grammar_replacement; + } + + } + else if((grammar_symbol == "X") || (grammar_symbol == "T") || (grammar_symbol == "F")) + { + var grammar_replacement_rule = this.grammar[grammar_symbol][0]; + var grammar_replacement = grammar_replacement_rule.successorString; + grammar_symbol = grammar_replacement; + } + + if(i == n-1) + { + if((grammar_symbol == "X")) + { + var grammar_replacement_rule = this.grammar[grammar_symbol][5]; + var grammar_replacement = grammar_replacement_rule.successorString; + grammar_symbol = grammar_replacement; + } + } + + replaceNode(lSystemLL, temp, grammar_symbol); + + temp = tempNext; + } + } return lSystemLL; } -} \ No newline at end of file +} diff --git a/src/main.js b/src/main.js index f0c6600..51477f8 100644 --- a/src/main.js +++ b/src/main.js @@ -1,10 +1,21 @@ - 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 myTurtle = require('./turtle.js'); + +// name is a member of myModule due to the export above +// var BranchMaterial = myTurtle.BranchMaterial; +// var LeafMaterial = myTurtle.LeafMaterial; +// var FruitMaterial = myTurtle.FruitMaterial; + var turtle; +var guiParameters = { + BranchColor: new THREE.Color(0x46271A),// [23,50,138], + LeafColor: [216,42,42], + FruitColor: [17,191,52], +} // called after the scene loads function onLoad(framework) { @@ -22,13 +33,20 @@ function onLoad(framework) { scene.add(directionalLight); // set camera position - camera.position.set(1, 1, 2); + camera.position.set(1, 1, 20); camera.lookAt(new THREE.Vector3(0,0,0)); // initialize LSystem and a Turtle to draw var lsys = new Lsystem(); turtle = new Turtle(scene); + gui.addColor(guiParameters, 'BranchColor').onChange(function(newVal) + { + guiParameters.BranchColor = (new THREE.Color(newVal)).getHex(); + // console.log(guiParameters.BranchColor); + doLsystem(lsys, lsys.iterations, turtle); + }); + gui.add(camera, 'fov', 0, 180).onChange(function(newVal) { camera.updateProjectionMatrix(); }); @@ -38,7 +56,7 @@ function onLoad(framework) { doLsystem(lsys, lsys.iterations, turtle); }); - gui.add(lsys, 'iterations', 0, 12).step(1).onChange(function(newVal) { + gui.add(lsys, 'iterations', 0, 9).step(1).onChange(function(newVal) { clearScene(turtle); doLsystem(lsys, newVal, turtle); }); @@ -57,12 +75,13 @@ function doLsystem(lsystem, iterations, turtle) { var result = lsystem.DoIterations(iterations); turtle.clear(); turtle = new Turtle(turtle.scene); + turtle.branchcolor = guiParameters.BranchColor; turtle.renderSymbols(result); } // called on frame updates -function onUpdate(framework) { -} +function onUpdate(framework) +{} // when the scene is done initializing, it will call onLoad, then on frame updates, call onUpdate Framework.init(onLoad, onUpdate); diff --git a/src/shaders/LSystems-frag.glsl b/src/shaders/LSystems-frag.glsl new file mode 100644 index 0000000..16698ab --- /dev/null +++ b/src/shaders/LSystems-frag.glsl @@ -0,0 +1,7 @@ +uniform vec3 genericColor; + +void main() +{ + //vec4 color = feathercolor; + gl_FragColor = vec4( genericColor, 1.0 ); +} diff --git a/src/shaders/LSystems-vert.glsl b/src/shaders/LSystems-vert.glsl new file mode 100644 index 0000000..3c72359 --- /dev/null +++ b/src/shaders/LSystems-vert.glsl @@ -0,0 +1,5 @@ + +void main() +{ + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +} diff --git a/src/turtle.js b/src/turtle.js index 1db2723..0c6b901 100644 --- a/src/turtle.js +++ b/src/turtle.js @@ -10,20 +10,31 @@ var TurtleState = function(pos, dir) { dir: new THREE.Vector3(dir.x, dir.y, dir.z) } } - + 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.SaveStack = []; + this.index = 0; + this.angle_g = 0.0; + this.branchcolor = new THREE.Vector3( 0x8B4513 ); + // this.leafcolor = new THREE.Vector3( 0x32CD32 ); + // this.fruitcolor = new THREE.Vector3( 0x990000 ); // 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, 30, 0, 30), + '-' : this.rotateTurtle.bind(this, -30, 0, -30), + 'F' : this.makeCylinder.bind(this, 2, 0.1), + 'X' : this.makeCylinder.bind(this, 2, 0.1), //branch + 'A' : this.makeFruit.bind(this, 0.2), //leaf + 'L' : this.makeLeaf.bind(this, 0.1, 0.2), //fruit + 'a' : this.radialrotate.bind(this), //radial growth + '[' : this.saveState.bind(this), + ']' : this.respawnAtState.bind(this) }; } else { this.renderGrammar = grammar; @@ -32,27 +43,38 @@ export default class Turtle { // Resets the turtle's position to the origin // and its orientation to the Y axis - clear() { - this.state = new TurtleState(new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0)); + clear() + { + this.state = new TurtleState(new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0)); } // A function to help you debug your turtle functions // by printing out the turtle's current state. - printState() { + printState() + { console.log(this.state.pos) console.log(this.state.dir) } - // Rotate the turtle's _dir_ vector by each of the + // Rotate the turtle's _dir_ vector by each of the // 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); + rotateTurtle(x, y, z) + { + var e = new THREE.Euler(x * 3.14/180, + y * 3.14/180, + z * 3.14/180); this.state.dir.applyEuler(e); } + radialrotate() + { + var axis = new THREE.Vector3( 0, 1, 0 ); + var angle = (this.angle_g) * 3.14/180; + this.state.dir.applyAxisAngle( axis, angle ); + // console.log(this.angle_g); + this.angle_g += 45; + } + // Translate the turtle along the input vector. // Does NOT change the turtle's _dir_ vector moveTurtle(x, y, z) { @@ -65,13 +87,13 @@ export default class Turtle { var newVec = this.state.dir.multiplyScalar(dist); this.state.pos.add(newVec); }; - + // 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 ); + var Bmaterial = new THREE.MeshBasicMaterial( {color: this.branchcolor} ); + var cylinder = new THREE.Mesh( geometry, Bmaterial ); this.scene.add( cylinder ); //Orient the cylinder to the turtle's current direction @@ -81,7 +103,6 @@ export default class Turtle { mat4.makeRotationFromQuaternion(quat); 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)); @@ -91,22 +112,85 @@ export default class Turtle { //Scoot the turtle forward by len units this.moveForward(len/2); }; - + + makeFruit(radius) { + var sphereGeom = new THREE.IcosahedronGeometry(radius, 3); + var Fmaterial = new THREE.MeshBasicMaterial( {color: 0x990000} ); + var sphere = new THREE.Mesh( sphereGeom, Fmaterial ); + // sphere.position.set(this.state.pos); + // sphere.scale.set(0.1,0.1,0.1); + this.scene.add( sphere ); + + //Move the cylinder so its base rests at the turtle's current position + var mat5 = new THREE.Matrix4(); + var mat6 = new THREE.Matrix4(); + var trans = this.state.pos; + // var pos = sphere.position; + mat5.makeTranslation(trans.x, trans.y, trans.z); + sphere.applyMatrix(mat5); + + // Leaf.applyMatrix(mat5); + //apply scaling after + sphere.scale.set(1, 1, 1); + sphere.rotateZ(-15* 3.14/180); + var pos = sphere.position; + sphere.position.set(pos.x, pos.y-0.1, pos.z); + }; + + makeLeaf(radius, length){ + var sphereGeom = new THREE.IcosahedronGeometry(radius, 3); + var Lmaterial = new THREE.MeshBasicMaterial( {color: 0x32CD32} ); ///0x990000 + var Leaf = new THREE.Mesh( sphereGeom, Lmaterial ); + this.scene.add( Leaf ); + + //Move the cylinder so its base rests at the turtle's current position + var mat5 = new THREE.Matrix4(); + var mat6 = new THREE.Matrix4(); + var trans = this.state.pos; + var pos = Leaf.position; + // mat6.makeRotationZ ( 15* 3.14/180); + mat5.makeTranslation(trans.x, trans.y, trans.z); + // mat5 *= mat6; + Leaf.applyMatrix(mat5); + + // Leaf.applyMatrix(mat5); + //apply scaling after + Leaf.scale.set(1, 10, 1); + Leaf.rotateZ(-15* 3.14/180); + var pos = Leaf.position; + Leaf.position.set(pos.x, pos.y-1, pos.z); + } + + saveState() + { + this.SaveStack.push(new TurtleState(this.state.pos, this.state.dir)); + }; + + respawnAtState() + { + this.state = this.SaveStack.pop(); + }; + // Call the function to which the input symbol is bound. - // Look in the Turtle's constructor for examples of how to bind + // Look in the Turtle's constructor for examples of how to bind // functions to grammar symbols. - renderSymbol(symbolNode) { - var func = this.renderGrammar[symbolNode.character]; + renderSymbol(symbolNode) + { + // var func = this.renderGrammar[symbolNode.character]; + var func = this.renderGrammar[symbolNode.grammar]; if (func) { func(); } }; // Invoke renderSymbol for every node in a linked list of grammar symbols. - renderSymbols(linkedList) { + renderSymbols(linkedList) + { var currentNode; - for(currentNode = linkedList.head; currentNode != null; currentNode = currentNode.next) { + // for(currentNode = linkedList.head; currentNode != null; currentNode = currentNode.next) + for(currentNode = linkedList.first; currentNode != null; currentNode = currentNode.next) + { this.renderSymbol(currentNode); } } -} \ No newline at end of file +} diff --git a/webpack.config.js b/webpack.config.js index 57dce48..bf2a406 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,4 +1,5 @@ const path = require('path'); +const webpack = require('webpack'); module.exports = { entry: path.join(__dirname, "src/main"), @@ -24,5 +25,8 @@ module.exports = { devtool: 'source-map', devServer: { port: 7000 - } -} \ No newline at end of file + }, + plugins: [ + new webpack.OldWatchingPlugin() + ] +}