def generate(self, init_chord, file_name, LS=False, chord_name=None, chord_file=None, state_file=None, n_steps=80, r=(21,109)): if(LS): Lsystem = LSystem(chord_name, init_chord, chord_file, state_file, r) init_sequence = numpy.zeros((1, n_steps +1, self.maxFeatures)) init_sequence[:, 0, init_chord-self.r[0]] = 1 for i in numpy.arange(n_steps): probs = self.rnnModel.predict_proba(init_sequence)[:, i, :] for j in numpy.arange(len(init_sequence)): if(LS): ind = Lsystem.getMaxProbs(probs[j,0:(self.maxFeatures-1)],True) else: ind = maxProbs(probs[j,0:(self.maxFeatures-1)]) init_sequence[j, i+1, ind] = 1 generate_sq = [sq[:,0:(self.maxFeatures-1)].nonzero()[1] for sq in init_sequence] print(generate_sq[0] + self.r[0]) if(LS): print(Lsystem.cur_chord) print(Lsystem.cur_state) print(Lsystem.cur_opes) midiwrite(file_name, init_sequence[0,:,0:(self.maxFeatures-1)], self.r, self.dt) extent = (0, self.dt * len(init_sequence[0,:,0:(self.maxFeatures-1)])) + self.r pylab.figure() pylab.imshow(init_sequence[0,:,0:(self.maxFeatures-1)].T, origin='lower', aspect='auto',interpolation='nearest', cmap=pylab.cm.gray_r,extent=extent) pylab.xlabel('time (s)') pylab.ylabel('MIDI note number') pylab.title('generated piano-roll')
def lsystem_grid(layer_name='GP_layer'): print("###################################") max_depth = 4 bpy.context.scene.frame_end = 100 SPACING_FACTOR = 20 NB_ROWS = 10 NB_COLS = 8 gp_layer = init_grease_pencil(clear_layer=True, gpencil_layer_name=layer_name) gp_frame = gp_layer.frames.new(0) azimuth_adds = np.linspace(5, 70, NB_ROWS) inclination_adds = np.linspace(-20, 20, NB_COLS) for row in range(NB_ROWS): for col in range(NB_COLS): base_lsystem = LSystem(axiom=['X'], constants=['-', '+', '[', ']'], rules={ 'X': 'F+[[X]-X]-F[-FX]+X', 'F': 'FF', }, render_config={ 'azimuth_add': azimuth_adds[row], 'inclination_add': inclination_adds[col], }) print("###################") print(f"row {row}, col {col}") print( f"azimuth_add {base_lsystem.azimuth_add}, inclination_add {base_lsystem.inclination_add}" ) #print("n={}, alpha={}".format(max_depth, system.render_config['azimuth_add'])) #print("{}".format(system.axiom)) #print("{}".format(system.rules)) for i in range(max_depth): if i % 1 == 0: print(f"Depth {i}") base_lsystem.rewrite() render(base_lsystem.current_state.copy(), lambda x, y, context: draw(x, y, gp_layer, context), azimuth_add=base_lsystem.azimuth_add, inclination_add=base_lsystem.inclination_add, inclination=3.7, pos=(row * SPACING_FACTOR, col * SPACING_FACTOR, 0), line_length=.5)
def lsystem_params_anim(layer_name='GP_layer'): print("###################################") max_depth = 4 nb_frames = 100 bpy.context.scene.frame_end = nb_frames gp_layer = init_grease_pencil(clear_layer=True, gpencil_layer_name=layer_name) azimuth_adds = np.linspace(-40, 40, nb_frames) inclination_adds = np.linspace(-20, 20, nb_frames) for frame in range(nb_frames): base_systems = [ fractal_plant, fractal_plant_b, fractal_plant_c, fractal_plant_e, stochastic_plant ] base_system = base_systems[np.random.randint(0, len(base_systems))] system = LSystem( axiom=base_system.axiom, constants=base_system.constants, rules=base_system.rules, rules_probs=base_system.rules_probs, render_config={ 'azimuth_add': azimuth_adds[np.random.randint(len(azimuth_adds))], #20., 'inclination_add': inclination_adds[np.random.randint( len(inclination_adds))], #0., }) print("###################") print( f"azimuth_add {system.azimuth_add}, inclination_add {system.inclination_add}" ) for i in range(max_depth): if i % 1 == 0: print(f"Depth {i}") system.rewrite() gp_frame = gp_layer.frames.new(frame) render(system.current_state.copy(), lambda x, y, context: draw(x, y, gp_layer, context), azimuth_add=system.azimuth_add, inclination_add=system.inclination_add, inclination=3.7, pos=(0, 0, 0), line_length=1.)
def generate(self, init_chord, file_name, LS=False, chord_name=None, chord_file=None, state_file=None, n_steps=80, r=(21, 109)): if (LS): Lsystem = LSystem(chord_name, init_chord, chord_file, state_file, r) init_sequence = numpy.zeros((1, n_steps + 1, self.maxFeatures)) init_sequence[:, 0, init_chord - self.r[0]] = 1 for i in numpy.arange(n_steps): probs = self.rnnModel.predict_proba(init_sequence)[:, i, :] for j in numpy.arange(len(init_sequence)): if (LS): ind = Lsystem.getMaxProbs( probs[j, 0:(self.maxFeatures - 1)], True) else: ind = maxProbs(probs[j, 0:(self.maxFeatures - 1)]) init_sequence[j, i + 1, ind] = 1 generate_sq = [ sq[:, 0:(self.maxFeatures - 1)].nonzero()[1] for sq in init_sequence ] print(generate_sq[0] + self.r[0]) if (LS): print(Lsystem.cur_chord) print(Lsystem.cur_state) print(Lsystem.cur_opes) midiwrite(file_name, init_sequence[0, :, 0:(self.maxFeatures - 1)], self.r, self.dt) extent = (0, self.dt * len(init_sequence[0, :, 0:(self.maxFeatures - 1)])) + self.r pylab.figure() pylab.imshow(init_sequence[0, :, 0:(self.maxFeatures - 1)].T, origin='lower', aspect='auto', interpolation='nearest', cmap=pylab.cm.gray_r, extent=extent) pylab.xlabel('time (s)') pylab.ylabel('MIDI note number') pylab.title('generated piano-roll')
def animate_lsystem(system: LSystem, max_depth: int, pos=(0, 0, 0), layer_name='GP_layer'): gp_layer = init_grease_pencil(clear_layer=True, gpencil_layer_name=layer_name) print("###################") print(f"{layer_name}") print("n={}, alpha={}".format(max_depth, system.render_config['azimuth_add'])) print(system.axiom) print(system.rules) for i in range(max_depth): if i % 1 == 0: print(f"Depth {i}") gp_frame = gp_layer.frames.new(i) system.rewrite() # notice we skip rendering axioms state render(system.current_state.copy(), lambda x, y, context: draw(x, y, gp_layer, context), azimuth_add=system.azimuth_add, inclination_add=system.inclination_add, inclination=4., pos=(0, 0, 0), line_length=1.)
def weed(turtle, screen): instructions = (LSystem.LSystem(4, 'H')) print(instructions) #RULES: """ H H --> HFX[+H][-H] X --> X[-FFF][+FFF]FX """ def turtle_draw(turtle, instructions, steps, angle): instructions = (LSystem.LSystem(4, 'H')) turtle.speed(0) turtle.left(90) position_list = '' heading_list = [] x_position = [] y_position = [] for char in instructions: if char == 'F': turtle.forward(steps) elif char == '+': turtle.right(angle) elif char == '-': turtle.left(angle) elif char == '[': x_position = x_position + [turtle.xcor()] y_position = y_position + [turtle.ycor()] heading_list = heading_list + [turtle.heading()] elif char == ']': turtle.goto(x_position.pop(), y_position.pop()) turtle.setheading(heading_list.pop()) rand = random.randrange(10, 50, 1) rand = rand / 10 print(rand) rand2 = random.randrange(15, 45) turtle_draw(turtle, instructions, rand, rand2)
def turtle_draw(turtle, instructions, steps, angle): instructions = (LSystem.LSystem(4, 'H')) turtle.speed(0) turtle.left(90) position_list = '' heading_list = [] x_position = [] y_position = [] for char in instructions: if char == 'F': turtle.forward(steps) elif char == '+': turtle.right(angle) elif char == '-': turtle.left(angle) elif char == '[': x_position = x_position + [turtle.xcor()] y_position = y_position + [turtle.ycor()] heading_list = heading_list + [turtle.heading()] elif char == ']': turtle.goto(x_position.pop(), y_position.pop()) turtle.setheading(heading_list.pop())
def main(): filelist = ["hilbertcurve.txt", "dragoncurve.txt", "arrowheadcurve.txt", "peanogospercurve.txt", "sierpinskitrianglecurve.txt"] for i in filelist: print("Curve: ", i) sys = LSystem.LSystem(i) sys.drawCurve()
from LSystem import * import numpy as np import matplotlib.pyplot as plt from pylab import get_current_fig_manager hilbertcurve = LSystem("Hilbert curve", "X", ["X=-YF+XFX+FY-", "Y=+XF-YFY-FX+"], starting_angle=0, angle_increment=90) levy_c = LSystem("Levy C curve", "F", ["F=+F--F+"], starting_angle=0, angle_increment=45) cantor = LSystem("Cantor set", "AB", ["A=ABA", "B=BBB"], starting_angle=0, angle_increment=90) sierpinsky = LSystem("Sierpinsky triangle", "F-G-G", ["F=F-G+F+G-F", "G=GG"], starting_angle=0, angle_increment=120) koch = LSystem("Koch curve", "F", ["F=F+F-F-F+F"], starting_angle=0, angle_increment=90) algae = LSystem("Algae growth", "A", ["A=AB", "B=A"], starting_angle=0, angle_increment=20) dragon = LSystem("Dragon curve", "FX", ["X=X+YF+", "Y=-FX-Y"], starting_angle=90, angle_increment=90) #levy_c.test_system() #sierpinsky.test_system() #koch.test_system() #algae.test_system() #dragon.test_system() #dragon.age_system(10) #dragon.easy_plot() #koch.age_system(4) #koch.easy_plot() sierpinsky.age_system(2) sierpinsky.easy_plot() sierpinsky.age_system(2) sierpinsky.easy_plot() sierpinsky.age_system(2)
n = (2**6) * (3**4) * (5**5) # n = (2 ** 16) - 1 # n = 16 * 3 # n = 7 # n = 2 # print(integer_to_factor_notation(n)) # s = "(((0))(0))" # 3^2 * 2 = 18 s = "((((0)0)0)0)" # 3^(3^3) = 7625597484987 # print(factor_notation_to_integer(s)) # now make turtle graphics from the notation of different numbers (treating them as L-Systems) snowflake_rule_dict = { "0": LSystem.LSystemRule("0", { "0)0(0(0)0": 1, "0": 0 }), } rule_dict = { "(": LSystem.LSystemRule("(", { "((0)": 0.5, "(": 0.5 }), ")": LSystem.LSystemRule(")", { "(0))": 0.5, ")": 0.5 }), "0": LSystem.LSystemRule("0", { "(0)": 0.5, "0": 0.5 }),
import LSystem import turtle screen = turtle.Screen() screen.bgcolor('black') alex = turtle.Turtle() alex.color('darkgreen') instructions = (LSystem.LSystem(4,'H')) print(instructions) #RULES: """ H H --> HFX[+H][-H] X --> X[-FFF][+FFF]FX """ def turtle_draw(turtle, instructions, steps, angle): position_list = '' heading_list = [] x_position = [] y_position = [] for char in instructions: if char == 'F': turtle.forward(steps) elif char == '+': turtle.right(angle) elif char == '-': turtle.left(angle) elif char == '[':
def DrawScene(ri, time): """Everything between RiBegin and RiEnd""" frameString = "%04d" % DrawScene.counter filename = "Art%s.tif" % frameString DrawScene.counter += 1 stats = dict(endofframe=1, xmlfilename='stats.xml', filename='') bakeArgs = dict(displaychannels='_occlusion', samples=OccSamples) bakeArgs['filename'] = '' bakeArgs['hitgroup'] = '' ri.Option("limits", {"int threads": ThreadCount}) ri.Option("statistics", stats) if SingleFrame: ri.Display("Art", "framebuffer", "rgba") else: ri.Display(filename, "file", "rgba") ri.Format(*ImageFormat) ri.DisplayChannel("float _occlusion") ri.ShadingRate(ShadingRate) ri.PixelSamples(*PixelSamples) ri.Projection(ri.PERSPECTIVE, {ri.FOV: 30}) ri.Shutter(time, time + ShutterDuration) ri.Translate(-1, -1, 20) ri.Rotate(-20, 1, 0, 0) ri.Rotate(180, 1, 0, 0) # curve = [1, 1, 0.8, 0.1, 0.9, 0.2, 1, 1, 1, 1] # ri.Camera("world", {"float[10] shutteropening": curve}) ri.Imager("Vignette") ri.WorldBegin() ri.Declare("displaychannels", "string") ri.Declare("samples", "float") ri.Declare("coordsys", "string") ri.Declare("hitgroup", "string") ri.Attribute("cull", dict(hidden=0, backfacing=0)) ri.Attribute("dice", dict(rasterorient=0)) ri.Attribute("visibility", dict(diffuse=1, specular=1)) ri.SetLabel('Floor') bakeArgs['color em'] = (0.0 / 255.0, 165.0 / 255.0, 211.0 / 255.0) ri.Surface("ComputeOcclusion", bakeArgs) ri.TransformBegin() ri.Rotate(90, 1, 0, 0) ri.Disk(-0.7, 300, 360) ri.TransformEnd() ri.SetLabel('Sculpture') bakeArgs['color em'] = (0.25, 0.25, 0.25) ri.LightSource("ambientlight", dict(intensity=.1)) ri.LightSource("distantlight", { "intensity": [1], "from": [0, -100, 15], "to": [0, 0, 0] }) ri.LightSource("distantlight", { "intensity": [0.75], "from": [-2, -10, 0], "to": [0, 0, 0] }) if True: ri.Surface("ComputeOcclusion", bakeArgs) else: ri.Surface("plastic") tree = open(RulesFile).read() lsys = LSystem.LSystem(tree) shapes = lsys.evaluate(seed=29) ri.TransformBegin() ri.Rotate(90, 1, 0, 0) ri.Translate(0, 0, -0.55) curves = [] points, normals = [], [] for shape in shapes: if shape == None: if len(points) > 0: curves.append((points, normals)) points, normals = [], [] continue P, N = shape points.append(P[0]) points.append(P[1]) points.append(P[2]) normals.append(N[0]) normals.append(N[1]) normals.append(N[2]) if len(points) > 0: curves.append((points, normals)) print len(curves), "curves" for points, normals in curves: ri.Curves("linear", [len(points) / 3], "nonperiodic", { ri.P: points, ri.N: normals, "constantwidth": 0.15 }) ri.TransformEnd() ri.WorldEnd()
def DrawScene(ri, time): """Everything between RiBegin and RiEnd""" frameString = "%04d" % DrawScene.counter filename = "Art%s.tif" % frameString DrawScene.counter += 1 bakeArgs = dict(filename="AO.ptc", samples=OccSamples) bakeArgs['displaychannels'] = '_occlusion' if Crop: crop = (Crop[0] / ImageFormat[0], (Crop[0] + Crop[2]) / ImageFormat[0], Crop[1] / ImageFormat[1], (Crop[1] + Crop[3]) / ImageFormat[1]) ri.CropWindow(*crop) ri.Option("limits", {"int threads": ThreadCount}) ri.Display("panorama", "framebuffer", "rgba") ri.Format(*ImageFormat) ri.ShadingRate(ShadingRate) ri.PixelSamples(*PixelSamples) ri.Projection(ri.PERSPECTIVE, {ri.FOV: 30}) #ri.Imager("PanoramicDistortion", {"background": (0.0/255.0,165.0/255.0,211.0/255.0)}) ri.WorldBegin() ri.Declare("samples", "float") ri.Declare("displaychannels", "string") ri.Attribute("cull", dict(hidden=0, backfacing=0)) ri.Attribute("dice", dict(rasterorient=0)) ri.Attribute("visibility", dict(diffuse=1, specular=1)) ri.SetLabel('Floor') bakeArgs['color em'] = (0.0 / 255.0, 165.0 / 255.0, 211.0 / 255.0) ri.Surface("AmbientOcclusion", bakeArgs) ri.TransformBegin() ri.Rotate(90, 1, 0, 0) ri.Disk(0.7, 30, 360) ri.TransformEnd() width = 0.15 height = 0.1 sharpness = 2.0 ri.SetLabel('Sculpture') bakeArgs['color em'] = (1.5, 1.5, 1.5) ri.Surface("AmbientOcclusion", bakeArgs) tree = open('City.xml').read() shapes = [] seed = 76 for x in xrange(5): shapes += LSystem.Evaluate(tree, seed) seed = seed + 1 ri.TransformBegin() ri.Translate(-1.25, 0, 20.0) # 2.5 for panoromic ri.Rotate(45, 0, 1, 0) for shape in shapes: if shape == None: continue P, U, V, W = shape if P.y > 0: continue corners = [] corners += (P - U - V - W)[:] corners += (P + U - V - W)[:] corners += (P - U + V - W)[:] corners += (P + U + V - W)[:] corners += (P - U - V + W)[:] corners += (P + U - V + W)[:] corners += (P - U + V + W)[:] corners += (P + U + V + W)[:] ri.PointsPolygons([4, 4, 4, 4, 4, 4], [ 2, 3, 1, 0, 1, 5, 4, 0, 7, 6, 4, 5, 3, 2, 6, 7, 0, 4, 6, 2, 7, 5, 1, 3 ], {ri.P: corners}) ri.TransformEnd() ri.WorldEnd()
def DrawScene(ri, time): """Everything between RiBegin and RiEnd""" frameString = "%04d" % DrawScene.counter filename = "Art%s.tif" % frameString DrawScene.counter += 1 bakeArgs = dict(filename="City.ptc", samples=OccSamples) bakeArgs['displaychannels'] = '_occlusion' if Crop: left = 0 right = 1 top = 0.2 bottom = 0.85 ri.CropWindow(left, right, top, bottom) ri.Option("limits", {"int threads": ThreadCount}) ri.Display("panorama", "framebuffer", "rgba") ri.Format(*ImageFormat) ri.DisplayChannel("float _occlusion") ri.ShadingRate(ShadingRate) ri.PixelSamples(*PixelSamples) ri.Projection(ri.PERSPECTIVE, {ri.FOV: 30}) #ri.Imager("PanoramicDistortion", {"background": (0.0/255.0,165.0/255.0,211.0/255.0)}) ri.WorldBegin() ri.Translate(0, 0, 20) ri.Rotate(-20, 1, 0, 0) ri.Translate(0, 0, -20) ri.Declare("samples", "float") ri.Declare("displaychannels", "string") ri.Declare("coordsys", "string") ri.Attribute("cull", dict(hidden=0, backfacing=0)) ri.Attribute("dice", dict(rasterorient=0)) ri.Attribute("visibility", dict(diffuse=1, specular=1)) width = 0.15 height = 0.1 sharpness = 2.0 ri.SetLabel('Sculpture') bakeArgs['color em'] = (1.5, 1.5, 1.5) bakeArgs['coordsys'] = 'object' ri.Surface("AmbientOcclusion", bakeArgs) tree = open('City.xml').read() shapes = [] seed = 76 for x in xrange(10): shapes += LSystem.Evaluate(tree, seed) seed = seed + 1 ri.TransformBegin() ri.Translate(0, 0, 15.0) # 2.5 for panoromic ri.Rotate(45, 0, 1, 0) ri.CoordinateSystem("Sculpture") for shape in shapes: if shape == None: continue P, U, V, W = shape if P.y < 0.0: continue if P.y > 0.25 and P.x * P.x + P.z * P.z > 1.0: continue if False: u = U.normalized() v = V.normalized() w = W.normalized() if abs(u.y) > 0.9: pass elif abs(v.y) > 0.9: (U, V, W) = (V, U, W) elif abs(w.y) > 0.9: (U, V, W) = (W, U, V) corners = [] corners += (P - U - V - W)[:] # 0 corners += (P + U - V - W)[:] # 1 corners += (P - U + V - W)[:] # 2 corners += (P + U + V - W)[:] # 3 corners += (P - U - V + W)[:] # 4 corners += (P + U - V + W)[:] # 5 corners += (P - U + V + W)[:] # 6 corners += (P + U + V + W)[:] # 7 ri.PointsPolygons([4, 4, 4, 4, 4, 4], [ 2, 3, 1, 0, 1, 5, 4, 0, 7, 6, 4, 5, 3, 2, 6, 7, 0, 4, 6, 2, 7, 5, 1, 3 ], {ri.P: corners}) if False: ri.SetLabel('RightWall') bakeArgs['color em'] = (0.0 / 255.0, 165.0 / 255.0, 211.0 / 255.0) ri.Surface("AmbientOcclusion", bakeArgs) corners = [] P = euclid.Point3(0, 0, 0) U = euclid.Vector3(10, 0, 0) V = euclid.Vector3(0, 10, 0) W = euclid.Vector3(0, 0, 0) corners += (P - U - V - W)[:] corners += (P + U - V - W)[:] corners += (P - U + V - W)[:] corners += (P + U + V - W)[:] ri.PointsPolygons([ 4, ], [2, 3, 1, 0], {ri.P: corners}) ri.SetLabel('LeftWall') ri.Surface("AmbientOcclusion", bakeArgs) corners = [] P = euclid.Point3(0, 0, 0) U = euclid.Vector3(0, 0, 10) V = euclid.Vector3(0, 10, 0) W = euclid.Vector3(0, 0, 0) corners += (P - U - V - W)[:] corners += (P + U - V - W)[:] corners += (P - U + V - W)[:] corners += (P + U + V - W)[:] ri.PointsPolygons([ 4, ], [2, 3, 1, 0], {ri.P: corners}) ri.SetLabel('Floor') bakeArgs['color em'] = (0.0 / 255.0, 165.0 / 255.0, 211.0 / 255.0) ri.Surface("AmbientOcclusion", bakeArgs) corners = [] P = euclid.Point3(0, 0, 0) U = euclid.Vector3(0, 0, 10) V = euclid.Vector3(10, 0, 0) W = euclid.Vector3(0, 0, 0) corners += (P - U - V - W)[:] corners += (P + U - V - W)[:] corners += (P - U + V - W)[:] corners += (P + U + V - W)[:] ri.PointsPolygons([4], [2, 3, 1, 0], {ri.P: corners}) # I started on try to export to GLBO format # but "easy_install python-lzf" does not work # and I decided to abondon this effort in the # interest of time if False: vertices = [euclid.Point3(1, 1, 1)] indices = [0, 0, 0] GL_UNSIGNED_SHORT = 0x1403 GL_FLOAT = 0x1406 vertices = [pack('fff', *v[:]) for v in vertices] indices = [pack('H', i) for i in indices] frames = [vertices] attrib = \ pack('PiiIiP', 0, 3, GL_FLOAT, 3 * 4, len(frames), 0) attribs = [attrib] header = '' header += \ pack('iiiiQ', len(attribs), len(indices), len(vertices), GL_UNSIGNED_SHORT, len(indices) * 2) # Write contents to a simple binary file if True: i = 0 vertices = [] normals = [] for shape in shapes: if shape == None: continue P, U, V, W = shape if P.y < 0.0: continue if P.y > 0.25 and P.x * P.x + P.z * P.z > 1.0: continue u = U.normalized() v = V.normalized() w = W.normalized() if abs(u.y) > 0.9: pass elif abs(v.y) > 0.9: (U, V, W) = (V, U, W) elif abs(w.y) > 0.9: (U, V, W) = (W, U, V) corners = [] corners.append(P - U - V - W) corners.append(P + U - V - W) corners.append(P - U + V - W) corners.append(P + U + V - W) corners.append(P - U - V + W) corners.append(P + U - V + W) corners.append(P - U + V + W) corners.append(P + U + V + W) faces = [ 2, 3, 1, 0, 1, 5, 4, 0, 7, 6, 4, 5, 3, 2, 6, 7, 0, 4, 6, 2, 7, 5, 1, 3 ] U.normalize() V.normalize() W.normalize() facets = [ W, W, W, W, V, V, V, V, -W, -W, -W, -W, -V, -V, -V, -V, U, U, U, U, -U, -U, -U, -U ] faces = [corners[x] for x in faces] faces = [c for v in faces for c in v] # flatten facets = [c for v in facets for c in v] # flatten #if len(faces) != 72: raise Exception("Internal issue") #if len(facets) != 72: raise Exception("Internal issue") vertices.append(pack('72f', *faces)) normals.append(pack('72f', *facets)) vertexCount = len(vertices) * 72 / 3 outfile = open('City.dat', 'wb') outfile.write(pack('i', vertexCount)) outfile.write(''.join(vertices)) outfile.write(''.join(normals)) outfile.close() ri.TransformEnd() ri.WorldEnd()
def compute(self, plug, data): # TODO:: create the main functionality of the node. Your node should # take in three floats for max position (X,Y,Z), three floats # for min position (X,Y,Z), and the number of random points to # be generated. Your node should output an MFnArrayAttrsData # object containing the random points. Consult the homework # sheet for how to deal with creating the MFnArrayAttrsData. # TODO:: create the main functionality of the node. Your node should # take in three floats for max position (X,Y,Z), three floats # for min position (X,Y,Z), and the number of random points to # be generated. Your node should output an MFnArrayAttrsData # object containing the random points. Consult the homework # sheet for how to deal with creating the MFnArrayAttrsData. #input data angleData = data.inputValue(LSystemInstanceNode.angle) stepSizeData = data.inputValue(LSystemInstanceNode.stepSize) grammarFileData = data.inputValue(LSystemInstanceNode.grammarFile) iterData = data.inputValue(LSystemInstanceNode.iterations) angleValue = angleData.asDouble() stepSizeValue = stepSizeData.asDouble() grammarFileValue = grammarFileData.asString() iterValue = iterData.asInt() #output data outBranchesData = data.outputValue(LSystemInstanceNode.outputBranches) outBranchesAAD = OpenMaya.MFnArrayAttrsData() outBranchesObject = outBranchesAAD.create() outFlowersData = data.outputValue(LSystemInstanceNode.outputFlowers) outFlowersAAD = OpenMaya.MFnArrayAttrsData() outFlowersObject = outFlowersAAD.create() #vectors for pos, id, scale, aim for branches and flowers branchPosArr = outBranchesAAD.vectorArray("position") branchIDArr = outBranchesAAD.doubleArray("id") branchScaleArr = outBranchesAAD.vectorArray("scale") branchAimArr = outBranchesAAD.vectorArray("aimDirection") flowerPosArr = outFlowersAAD.vectorArray("position") flowerIDArr = outFlowersAAD.doubleArray("id") lsystem = LSystem.LSystem() lsystem.loadProgram(str(grammarFileValue)) lsystem.setDefaultAngle(angleValue) lsystem.setDefaultStep(stepSizeValue) branches = LSystem.VectorPyBranch() flowers = LSystem.VectorPyBranch() lsystem.processPy(iterValue, branches, flowers) # fill branches and flowers for j, branch in enumerate(branches): aim = OpenMaya.MVector(branch[3] - branch[0], branch[4] - branch[1], branch[5] - branch[2]) branchPosArr.append( OpenMaya.MVector((branch[3] + branch[0]) / 2.0, (branch[4] + branch[1]) / 2.0, (branch[5] + branch[2]) / 2.0)) branchIDArr.append(j) aimlength = math.sqrt((branch[3] - branch[0]) * (branch[3] - branch[0]) + (branch[5] - branch[2]) * (branch[5] - branch[2]) + (branch[4] - branch[1]) * (branch[4] - branch[1])) branchScaleArr.append(OpenMaya.MVector(aimlength, 1.0, 1.0)) branchAimArr.append(aim) for k, flower in enumerate(flowers): pos = OpenMaya.MVector(flower[0], flower[1], flower[2]) flowerPosArr.append(pos) flowerIDArr.append(k) outBranchesData.setMObject(outBranchesObject) outFlowersData.setMObject(outFlowersObject) data.setClean(plug) data.setClean(plug)
from LSystem import * from LSystemTurtle import * import random def d_rand(): return random.uniform(4.0, 7.0) def delta_rand(): return random.uniform(20.0, 30.0) #Symmetrical G system = LSystem({'G': 'GG+[GF-][-FG]+GG', 'F': 'FF'}) lturtle = LSystemTurtle(system, 10, 22.5) lturtle.set_center(0, 0) lturtle.run(4, 'G') lturtle.save('plant_1.eps') #Symmetrical G with +/- swapping system = LSystem({'G': 'GG+[GF-][+FG]-GG', 'F': 'FF'}) lturtle = LSystemTurtle(system, 3, 22.5) lturtle.run(4, 'G') lturtle.save('plant_2.eps') #Symmetrical F system = LSystem({'F': 'FF+[-F[--F][F--]F-]+FF'}) lturtle = LSystemTurtle(system, 5, 22.5) lturtle.run(4, 'F') lturtle.save('plant_3.eps')
#!/usr/bin/python import time RulesFile = 'Ribbon.xml' import LSystem if __name__ == "__main__": tree = open(RulesFile).read() #shapes = LSystem.Evaluate(tree, seed = 29) lsystem = LSystem.LSystem(tree) startTime = time.clock() shapes = lsystem.evaluate(tree) print time.clock() - startTime, " seconds"
def __init__(self, image_matrix, white=1, levels=4, init_shape=INIT_SKEL, maxQuant = 220): """ :param image_matrix: """ self.dnCount = 0 self.dnSum = 0. self.upCount = 0 self.upSum = 0. self.lenList = list() self.imin = image_matrix self.xmin = 0 self.ymin = 0 self.xmax = self.imin.shape[0] - 1 self.ymax = self.imin.shape[1] - 1 # whiten self.imin /= white self.imin += 255 - (255 // white) # processor count self.PROCESSORS = multiprocessing.cpu_count() if self.PROCESSORS > 1: self.PROCESSORS -= 1 # quantize self.centroids = Quantization.measCentroid(self.imin, levels) print("Centroids: ") print(self.centroids) levels = min(levels, len(self.centroids)) levels = max(2, levels) nq = np.array([[x * maxQuant / (levels - 1)] for x in range(0, levels)]) print(nq) self.imin = Quantization.quantMatrix(self.imin, nq, self.centroids) plt.imshow(self.imin, cmap=cm.gray) plt.savefig("figStartOrig.png") plt.clf() # self.R0_B = self.density(nq[-1][0]) # Initial segment if init_shape == self.INIT_MOORE: moore = [] m = [] n = 1 << 7 for i in range(0, n ** 2): x, y = Hilbert.d2xy(n, i, True) m.append((x, y)) moore.append(((self.imin.shape[0] * x) / (n - 1), (self.imin.shape[1] * y) / (n - 1))) ''' Ordinarily, the moore curve starts in the middle of one edge. Rotate the moore graph to start in the middle ''' m2q = len(moore) // 4 moore2 = moore[m2q:] moore2.extend(moore[:m2q]) ''' Add the first and last point to return to start ''' ptAlpha = np.multiply(np.array(self.imin.shape), 0.5) moore2.append(tuple(ptAlpha)) moore2.insert(0, tuple(ptAlpha)) moore3 = [(0.95 * x + 0.025 * self.imin.shape[0], 0.95 * y + 0.025 * self.imin.shape[1]) for x, y in moore2] self.maze_path = np.array(moore3) self.maze_path = TSPopt.simplify(self.maze_path) for i in range(10): self.resampling() self.maze_path = TSPopt.simplify(self.maze_path) while True: delta, seg1 = TSPopt.threeOptLocal(self.maze_path, 40) self.maze_path = seg1 if delta == 0.: break for i in range(10): self.resampling() ''' Have to add a brownian to thois because when you do the resample, you could end up with points on the same line, which will lead to a divb0 issue. ''' brownian = self.brownian() self.maze_path = np.add(self.maze_path, brownian) self.plotMazeImage("figStartMoore.png",superimpose=True) elif init_shape == self.INIT_FASS: """ FASS is for Filling, self-Avoiding, Simple, and self-Similar. This is one instance of a FASS system. This one starts in the center, which is why it is advantageous for us. """ import LSystem fass2 = LSystem.LSystem(axiom="FX", rules=[('X','Y-LFL-FRF-LFLFL-FRFR+F'), ('Y','X+RFR+FLF+RFRFR+FLFL-F'), ('L','LF+RFR+FL-F-LFLFL-FRFR+'), ('R','-LFLF+RFRFR+F+RF-LFL-FR')], angle = 90) fass2.iterate(5) path1=np.array(fass2.segment(initialpt=[0.0,0.0], d=1.0)) dim = path1.max() - path1.min() path2 = list() path1min = path1.min() for pt in path1: path2.append(((self.imin.shape[0] * (pt[0]-path1min)) / (dim - 1), (self.imin.shape[1] * (pt[1]-path1min)) / (dim - 1))) path3 = [(0.95 * x + 0.025 * self.imin.shape[0], 0.95 * y + 0.025 * self.imin.shape[1]) for x, y in path2] self.maze_path = path3 self.plotMazeImage("figStartFass0.png",superimpose=True) self.maze_path = TSPopt.simplify(self.maze_path) for _ in range(10): self.resampling() self.maze_path = TSPopt.simplify(self.maze_path) while True: delta, seg1 = TSPopt.threeOptLocal(self.maze_path, 40) self.maze_path = seg1 if delta == 0.: break for i in range(10): self.resampling() self.plotMazeImage("figStartFass.png",superimpose=True) elif init_shape == self.INIT_DIAG: # simple diagonal segListEnd = tuple([x - 1 for x in self.imin.shape]) self.maze_path = list() for i in range(20): self.maze_path.append((int(i*segListEnd[0]/20), int(i*segListEnd[1]/20))) self.maze_path.append(segListEnd) self.maze_path = np.array(self.maze_path) elif init_shape == self.INIT_SKEL: # use skeleton to cover most of dark image (>128) b = np.array([[0.], [128.]]) q = np.array([[0.], [1.]]) blacks = Quantization.quantMatrix(self.imin, q, b) skeleton = Skeleton.Skeleton(blacks) skeleton.segments.addInitialStartPt() skeleton.euclidMstOrder() skeleton.segments.concatSegments() oneD = skeleton.segments.segmentList.flatten() self.maze_path = np.reshape(oneD, (-1, 2)) brownian = self.brownian() self.maze_path = np.add(self.maze_path, brownian) self.maze_path = TSPopt.simplify(self.maze_path) size = 60 while True: delta, seg1 = TSPopt.threeOptLocal(self.maze_path, size) self.maze_path = seg1 if delta == 0.: break size = max(5,size-5) self.plotMazeImage("figStartSkeleton.png",superimpose=True) self.seg = Segments.Segments() factor = 0.5 delta = 0.0 self.bndry_xmax = self.xmax + factor * self.R0_B - delta self.bndry_ymax = self.ymax + factor * self.R0_B - delta self.bndry_xmin = self.xmin - factor * self.R0_B + delta self.bndry_ymin = self.ymin - factor * self.R0_B + delta pt_00 = (self.bndry_xmin, self.bndry_ymin) pt_01 = (self.bndry_xmin, self.bndry_ymax) pt_11 = (self.bndry_xmax, self.bndry_ymax) pt_10 = (self.bndry_xmax, self.bndry_ymin) self.boundary_seg = [pt_00, pt_01, pt_11, pt_10, pt_00] self.minDist = sys.float_info.max
# -*- coding: utf-8 -*- """ LSystemRunSol.py """ import LSystem if __name__ == '__main__': LSystem.main()
def compute(self, plug, data): if (plug == LSystemInstanceNode.branches or plug == LSystemInstanceNode.flowers): # get parameters iterations = data.inputValue( LSystemInstanceNode.iterations).asInt() angle = data.inputValue(LSystemInstanceNode.angle).asFloat() step = data.inputValue(LSystemInstanceNode.step).asFloat() file = data.inputValue(LSystemInstanceNode.file).asString() # update lsystem if (angle != LSystemInstanceNode.lsystem.getDefaultAngle()): LSystemInstanceNode.lsystem.setDefaultAngle(angle) if (step != LSystemInstanceNode.lsystem.getDefaultStep()): LSystemInstanceNode.lsystem.setDefaultStep(step) LSystemInstanceNode.lsystem.loadProgram(file.encode()) # instantiate branches output object branches = data.outputValue(LSystemInstanceNode.branches) branchesAAD = OpenMaya.MFnArrayAttrsData() branchesObject = branchesAAD.create() branchesPosArray = branchesAAD.vectorArray("position") branchesIdArray = branchesAAD.doubleArray("id") branchesScaleArray = branchesAAD.vectorArray("scale") branchesOrientArray = branchesAAD.vectorArray("aimDirection") # instantiate flowers output object flowers = data.outputValue(LSystemInstanceNode.flowers) flowersAAD = OpenMaya.MFnArrayAttrsData() flowersObject = flowersAAD.create() flowersPosArray = flowersAAD.vectorArray("position") flowersIdArray = flowersAAD.doubleArray("id") flowersScaleArray = flowersAAD.vectorArray("scale") # execute LSystem branchesVec = LSystem.VectorPyBranch() flowersVec = LSystem.VectorPyBranch() LSystemInstanceNode.lsystem.processPy(iterations, branchesVec, flowersVec) # branches output for branch in branchesVec: midX = (branch[0] + branch[3]) / 2 midY = (branch[2] + branch[5]) / 2 midZ = (branch[4] + branch[1]) / 2 branchesPosArray.append(OpenMaya.MVector(midX, midY, midZ)) vecX = branch[3] - branch[0] vecZ = branch[4] - branch[1] vecY = branch[5] - branch[2] vecBranch = OpenMaya.MVector(vecX, vecY, vecZ) radius = LSystemInstanceNode.lsystem.getDefaultStep() * 0.1 branchesScaleArray.append( OpenMaya.MVector(vecBranch.length(), radius, radius)) branchesOrientArray.append(OpenMaya.MVector(vecX, vecY, vecZ)) # flowers output for flower in flowersVec: flowersPosArray.append( OpenMaya.MVector(flower[0], flower[2], flower[1])) scale = LSystemInstanceNode.lsystem.getDefaultStep() * 0.2 flowersScaleArray.append(OpenMaya.MVector(scale, scale, scale)) branches.setMObject(branchesObject) flowers.setMObject(flowersObject) data.setClean(plug)
def __init__(self, image_matrix, white=1, levels=4, init_shape=3): """ :param image_matrix: """ self.dnCount = 0 self.dnSum = 0. self.upCount = 0 self.upSum = 0. self.lenList = list() self.imin = image_matrix self.xmin = 0 self.ymin = 0 self.xmax = self.imin.shape[0] - 1 self.ymax = self.imin.shape[1] - 1 # whiten self.imin /= white self.imin += 255 - (255 // white) # quantize self.centroids = Quantization.measCentroid(self.imin, levels) print(self.centroids) levels = min(levels, len(self.centroids)) levels = max(2, levels) nq = np.array([[x * 255 / (levels - 1)] for x in range(0, levels)]) self.imin = Quantization.quantMatrix(self.imin, nq, self.centroids) plt.imshow(self.imin, cmap=cm.gray) plt.savefig("figStartOrig.png") plt.clf() # self.R0_B = self.density(nq[-1][0]) # Initial segment if init_shape == 1: moore = [] m = [] n = 1 << 7 for i in range(0, n**2): x, y = Hilbert.d2xy(n, i, True) m.append((x, y)) moore.append(((self.imin.shape[0] * x) / (n - 1), (self.imin.shape[1] * y) / (n - 1))) ''' Rotate the moore graph to start in the middle ''' m2q = len(moore) // 4 moore2 = moore[m2q:] moore2.extend(moore[:m2q]) ''' Add the first and last point to return to start ''' ptAlpha = np.multiply(np.array(self.imin.shape), 0.5) moore2.append(tuple(ptAlpha)) moore2.insert(0, tuple(ptAlpha)) moore3 = [(0.95 * x + 0.025 * self.imin.shape[0], 0.95 * y + 0.025 * self.imin.shape[1]) for x, y in moore2] self.maze_path = np.array(moore3) self.plotMazeImage("figStart0.png") self.maze_path = TSPopt.simplify(self.maze_path) for i in range(10): self.resampling() self.plotMazeImage("figStart1.png") self.maze_path = TSPopt.simplify(self.maze_path) while True: delta, seg1 = TSPopt.threeOptLocal(self.maze_path, 40) self.maze_path = seg1 if delta == 0.: break self.plotMazeImage("figStart2.png") for i in range(10): self.resampling() ''' Have to add a brownian to thois because when you do the resample, you could end up with points on the same line, which will lead to a divb0 issue. ''' brownian = self.brownian() self.maze_path = np.add(self.maze_path, brownian) self.plotMazeImage("figStart3.png") elif init_shape == 2: import LSystem gosper = LSystem.LSystem(axiom='B', rules=[('A', 'A-B--B+A++AA+B-'), ('B', '+A-BB--B-A++A+B')], angle=60.0) gosper.iterate(5) self.maze_path = np.array( gosper.segment(initialpt=[200.0, 600.0], d=4.0)) self.plotMazeImage("figStartGosper0.png") elif init_shape == 3: import LSystem fass2 = LSystem.LSystem(axiom="FX", rules=[('X', 'Y-LFL-FRF-LFLFL-FRFR+F'), ('Y', 'X+RFR+FLF+RFRFR+FLFL-F'), ('L', 'LF+RFR+FL-F-LFLFL-FRFR+'), ('R', '-LFLF+RFRFR+F+RF-LFL-FR')], angle=90) fass2.iterate(5) path1 = np.array(fass2.segment(initialpt=[0.0, 0.0], d=1.0)) dim = path1.max() - path1.min() path2 = list() path1min = path1.min() for pt in path1: path2.append( ((self.imin.shape[0] * (pt[0] - path1min)) / (dim - 1), (self.imin.shape[1] * (pt[1] - path1min)) / (dim - 1))) path3 = [(0.95 * x + 0.025 * self.imin.shape[0], 0.95 * y + 0.025 * self.imin.shape[1]) for x, y in path2] self.maze_path = path3 self.plotMazeImage("figFass2_0.png") self.maze_path = TSPopt.simplify(self.maze_path) for i in range(10): self.resampling() self.plotMazeImage("figFass2_1.png") self.maze_path = TSPopt.simplify(self.maze_path) while True: delta, seg1 = TSPopt.threeOptLocal(self.maze_path, 40) self.maze_path = seg1 if delta == 0.: break self.plotMazeImage("figFass2_2.png") for i in range(10): self.resampling() else: self.maze_path = [(0., 0.)] segListEnd = tuple([x - 1 for x in self.imin.shape]) self.maze_path.append(segListEnd) self.maze_path = np.array(self.maze_path) self.seg = Segments.Segments() factor = 0.5 delta = 0.0 self.bndry_xmax = self.xmax + factor * self.R0_B - delta self.bndry_ymax = self.ymax + factor * self.R0_B - delta self.bndry_xmin = self.xmin - factor * self.R0_B + delta self.bndry_ymin = self.ymin - factor * self.R0_B + delta pt_00 = (self.bndry_xmin, self.bndry_ymin) pt_01 = (self.bndry_xmin, self.bndry_ymax) pt_11 = (self.bndry_xmax, self.bndry_ymax) pt_10 = (self.bndry_xmax, self.bndry_ymin) self.boundary_seg = [pt_00, pt_01, pt_11, pt_10, pt_00] self.minDist = sys.float_info.max
def compute(self, plug, data): # TODO:: create the main functionality of the node. Your node should # take in three floats for max position (X,Y,Z), three floats # for min position (X,Y,Z), and the number of random points to # be generated. Your node should output an MFnArrayAttrsData # object containing the random points. Consult the homework # sheet for how to deal with creating the MFnArrayAttrsData. print "I'm computing\n" if (plug == LSystemInstanceNode.branches or plug == LSystemInstanceNode.flowers): print "I'm inside\n" angleHandle = data.inputValue(LSystemInstanceNode.angle) d_angle = angleHandle.asDouble() stepHandle = data.inputValue(LSystemInstanceNode.step) d_step = stepHandle.asDouble() grammarHandle = data.inputValue(LSystemInstanceNode.grammar) s_grammar = str(grammarHandle.asString()) iterationHandle = data.inputValue(LSystemInstanceNode.iteration) i_iteration = iterationHandle.asInt() timeHandle = data.inputValue(LSystemInstanceNode.time) t_time = timeHandle.asTime() i_time = int(t_time.asUnits(OpenMaya.MTime.kFilm)) branchesHandle = data.outputValue(LSystemInstanceNode.branches) branchesAAD = OpenMaya.MFnArrayAttrsData() branchesObject = branchesAAD.create() branchesPositionArray = branchesAAD.vectorArray("position") branchesIdArray = branchesAAD.doubleArray("id") branchesScaleArray = branchesAAD.vectorArray("scale") branchesAimArray = branchesAAD.vectorArray("aimDirection") flowersHandle = data.outputValue(LSystemInstanceNode.flowers) flowersAAD = OpenMaya.MFnArrayAttrsData() flowersObject = flowersAAD.create() flowersPositionArray = flowersAAD.vectorArray("position") flowersIdArray = flowersAAD.doubleArray("id") flowersScaleArray = flowersAAD.vectorArray("scale") flowersAimArray = flowersAAD.vectorArray("aimDirection") vecBranch = LSystem.VectorPyBranch() vecFlower = LSystem.VectorPyBranch() l = LSystem.LSystem() l.setDefaultAngle(d_angle) l.setDefaultStep(d_step) l.loadProgram(s_grammar) #s_grammar l.processPy(i_time, vecBranch, vecFlower) #iteration i = 0 for x in vecBranch: length = ((x[0] - x[3]) * (x[0] - x[3]) + (x[1] - x[4]) * (x[1] - x[4]) + (x[2] - x[5]) * (x[2] - x[5]))**0.5 branchesPositionArray.append( OpenMaya.MVector((x[0] + x[3]) / 2, (x[1] + x[4]) / 2, (x[2] + x[5]) / 2)) branchesIdArray.append(i) branchesScaleArray.append(OpenMaya.MVector(length, 1, 1)) branchesAimArray.append( OpenMaya.MVector((x[3] - x[0]), (x[4] - x[1]), (x[5] - x[2]))) i += 1 print i i = 0 for x in vecFlower: length = (x[0] * x[0] + x[1] * x[1] + x[2] * x[2])**0.5 flowersPositionArray.append(OpenMaya.MVector(x[0], x[1], x[2])) flowersIdArray.append(i) flowersScaleArray.append(OpenMaya.MVector(1, 1, 1)) flowersAimArray.append(OpenMaya.MVector(x[0], x[1], x[2])) i += 1 print i branchesHandle.setMObject(branchesObject) flowersHandle.setMObject(flowersObject) data.setClean(plug) else: print plug.name()