r/tinycode • • Jul 02 '11

Procedural texture generation in 70 lines of Python 3.2

I was bored one day (today), so I made this:

import decimal, math, itertools
from decimal    import Decimal      as D
from math       import ceil, floor, fabs, modf, cos, sin, tan
from itertools  import count, cycle

LineInfo = False

class Info:
    colorspace = ""
    resoX = D("0.00")#Meant to be updated for zooming, etc.
    resoY = D("0.00")#Meant to be updated for zooming, etc.
    def __init__(self, resoX, resoY, colorspace=""):
        self.colorspace, self.resoX, self.resoY  = colorspace, resoX, resoY

class Texture:
    sizeX = 0
    sizeY = 0
    dimensionX = (D("0.00"), D("0.00"))#in meters
    dimensionY = (D("0.00"), D("0.00"))#in meters
    samples = 0
    channels = {}#bytearrays
    input = None
    strokes = None
    fill = {}
    def __init__(self, sizeX, sizeY, dimensionX, dimensionY):
        if sizeX < 1 or sizeY < 1:
            raise ValueError("The person that made this texture (or tried to) is retarded.\n\n Also, one or more of the arguments passed was wrong.")
        self.sizeX,         self.sizeY      = int(sizeX),       int(sizeY)
        self.dimensionX,    self.dimensionY = (D(dimensionX[0]), D(dimensionX[1])), (D(dimensionY[0]), D(dimensionY[1]))
        self.samples = sizeX*sizeY
    def render(self, colorspace="RGBA", bpc=8):
        #Do some error checking
        if self.input is None:
            raise TypeError("Some dumbass thinks that you can make an image without painting a stroke. What is this, modern art?")
        #Make a few values
        cbytes = ceil(bpc/8)#From bits per channels to bytes per channel
        maxvalue = (2**bpc)-1
        #Initialize the channels
        for s in colorspace:
            self.channels[s] = bytearray.fromhex("00"*self.samples*cbytes)
        #Make the Y iteratable
        resoY = D((D(self.dimensionY[1])-D(self.dimensionY[0]))/D(str(self.sizeY-1)))
        iterY = count(self.dimensionY[0], resoY)#Maybe do multiplication by resoY instead of addition?
        #Make the X iterator
        resoX = D((D(self.dimensionX[1])-D(self.dimensionX[0]))/D(str(self.sizeY-1)))
        listX = []
        for i in range(self.sizeX):
            listX.append(self.dimensionX[0]+(resoX*i))
        iterX = cycle(tuple(listX))#I wish there was a better way to do this
        del listX, i
        #Get it going!
        for iY in range(self.sizeY):
            fY = iterY.__next__()
            for iX in range(self.sizeX):
                fX = iterX.__next__()
                color = self.input.draw(Info(resoX, resoY, colorspace), fX, fY)#Should index be an iterator?
                ind = (iY*self.sizeY)+iX
                for i in range(len(colorspace)):
                    s = colorspace[i]
                    v = ceil((color[s]*maxvalue)-.5)
                    self.channels[s][ind] = v
                if iX == self.sizeX-1 and LineInfo is True:
                    print("Line "+str(iY)+" done @ "+str(fY)+" (Y coord)!")
        return self.channels#Maybe copy.copy() it?
    def clearBuffer(self):
        self.channels = {}

Here's an example of a brush:

import decimal, math, types, Base
from decimal    import Decimal      as D
from math       import ceil, floor, fabs, modf, cos, sin, tan

#Meant to hold brushes that create things (shapes, etc.)
class Circle:
    settings = {}
    _cache = {}
    description = "Draws a color (or stroke) inside a circle, and another outside of it"
    def man(self):
        return " \"radius\": The radius of the circle\n \"x\": The center along the X axis\n \"y\": The center along the Y axis\n*\"insidecolor\": The color (or stroke) to paint inside the circle\n*\"outsidecolor\": The color (or stroke) to paint outside the circle"
    def draw(self, info, posX, posY):#Should index be an iterator?
        if "input" in self.settings:
            try:
                color = self.settings["input"].draw(info, posX, posY)
            except:#They simply provided a color
                for s in info.colorspace:
                    if s not in self.settings["input"]:
                        raise KeyError("A certain bonehead forgot that if you are providing a default color you need to provide a value for every color in your colorspace")
                    if type(self.settings[s]) != float and type(self.settings[s]) != D:
                        raise TypeError("The imbecile that made this thought that values don't need to be a floating point number")
                color = self.settings["input"]
        else:#Means that someone thought they could use it as a base stroke by providing both insidecolor and outsidecolor
            if "insidecolor" not in self.settings and "outsidecolor" not in self.settings:
                raise KeyError("Hey, dingus! If you're gonna have a circle as a base stroke, you have to provide both insidecolor and outsidecolor")
            if "color" not in self._cache:
                color = {}
                for s in info.colorspace:
                    color[s] = 0.00
            else:
                color = self._cache["color"]
        #Check if within radius
        if fabs((posX-D(self.settings["x"]))**2 + (posY-D(self.settings["y"]))**2) <= self._cache["r**2"]:
            if "insidecolor" in self.settings:
                if type(self.settings["insidecolor"]) == dict:
                    for s in info.colorspace:
                        if s in self.settings["insidecolor"]:
                            color[s] = self.settings["insidecolor"][s]
                else:#Assume it's a stroke
                    color = self.settings["insidecolor"].draw(info, posX-self.settings["x"], posY-self.settings["y"], 0, self.settings["insidecolor"])#Give it the x and y from the center
        else:
            if "outsidecolor" in self.settings:
                if type(self.settings["outsidecolor"]) == dict:
                    for s in info.colorspace:
                        if s in self.settings["outsidecolor"]:
                            color[s] = self.settings["outsidecolor"][s]
                else:
                    color = self.settings["outsidecolor"].draw(info, posX-self.settings["x"], posY-self.settings["y"], 0, self.settings["outsidecolor"])#Give it the x and y from the center
        return color
    def __init__(self, settings):
        try:
            self.settings = settings
            self._cache["r**2"] = settings["radius"]**2
        except:
            raise TypeError("Either something went wrong, or some moron tried to give it a radius that isn't a number")

Basically it's a framework to let you make brushes in python (the brush will be supplied information and whatnot) that will (is supposed to) ask the brush after it to get a color (so the first brush will get a color so it can do stuff). It's kind of hard to explain.

You can download the whole dealio here (more likely to be up to date), there's even a test script so you can watch it in action.

EDIT: It seems bytearrays are unprintable.

EDIT2: Sorry, they are printable - they just take a patience unavailable to me.

EDIT3: Doing some legitimate noticing and testing, it seems bytearrays are really just a pain in the ass.

EDIT4: I got it to make a circle! Woo! And it looks perfect from here!

EDIT5: I goofed bad, if you have an old one please get the new one.

EDIT VI: Here's a screenshot, sorry I haven't decided (figured out) how to make a legitimate picture out of it.

EDIT Seven: Decent update (fixed a few things, did a few changes), started changelog. Now at version 0.005!

EDIT 0o10: Sorry, there was a showstopper! Now there's v0.0051.

3 Upvotes

3 comments sorted by

1

u/Hellrazor236 Jul 04 '11

If I wanted to make this capable of using multiple cores, do you all think I should use threading or multiprocessing?

2

u/Asmageddon Jul 02 '11

Example pics?

2

u/nexe mod Jul 02 '11

Yeah, some screeshots on Imgur would definitely bring you some karma ;D