Python with kivy moving multiple 3D objects - python

I have a rather simple goal of drawing a few spheres in a 3D space and adjusting their location according to some function. I want to use python with kivy to accomplish this because it make touch screen interfacing super simple, and I found a repository which takes care of most of the heavy lifting with respects to programming.
From this code in the main.py function, I want to draw n spheres, and then update their locations later on (this is done under the draw_elements(self) function, and LOP[] is a list of the class 'points')
def drawPoints():
print self.scene.objects
for i in range(len(self.LOP)):
PushMatrix()
point = self.LOP[i]
point.shape = self.scene.objects['Sphere']
point.color = _set_color(i/10., (i+1)/10., 0., id_color=(int(255/(1+i)), int(255/(1+i)), 255))
point.shape.scale = Scale((i+1)/10.0,(i+1)/10.0,(i+1)/10.0)
self.LOP[i] = point
point.shape.scale.origin = (point.loc[0],point.loc[1],point.loc[2])
_draw_element(point.shape)
PopMatrix()
drawPoints()
When the points are drawn, they are at their stated origin.
Later on the program calls the update_scene function thanks the the clock scheduler.
def update_scene(self, *largs):
def randLoc(point):
newLoc = (0.1*random.random(),0.1*random.random(),0.1*random.random())
oldLoc = point.shape.scale.origin
newLoc = ( newLoc[0]-0.05+oldLoc[0], newLoc[1]-0.05+oldLoc[1], newLoc[2]-0.05+oldLoc[2] )
return newLoc
def updateLocs(self):
for i in range(len(self.LOP)):
point = self.LOP[i]
point.shape.scale.origin = randLoc(point)
if not self.pause:
updateLocs(self)
pass
When this update function is run, only the sphere that was drawn last moves, though it does move correctly.
How can I move the other spheres I drew earlier?
(my source code can be found here though it's really just build off of the first repository)

Related

PyQT Painter drawing Polygons

In my QT application I'm drawing lots of polygons like this:
I'm animating these, so some polygons will receive a new color. This animation runs 4-5 times per second.
However, calling the paintEvent() of the Qt.Painter() 4-5 times/second redraws ALL polygons which results in performance issues. Its only updated once a second, which is too slow. As you may see in the picture below, only some polygons in the first 12 rows needs to be updated:
[![enter image description here][2]][2]
In the QT docs I have read that you can't really save the state of the things you've already drawn. So you have to redraw everything again. Am I missing something? Is there a trick to still achieve this?
This is what my paintEvent() basically looks like (simplified, reduced cyclomatic complexity)
for y in range(len(self.array)):
for x in range(len(self.array[0])):
if(this): # simplified to reduce cyclomatic complexity
painter.setBrush(QBrush(QColor(20, 0, 255)))
elif(that):
painter.setBrush(QBrush(QColor(175, 175, 175)))
else:
painter.setBrush(QBrush(QColor(0, 0, 0)))
hexa_size = self.array[y][x]
hexas = createHexagon(x, y, hexa_size) # external functions to calculate the hexagon size and position
painter.drawPolygon(hexas)
painter.end()
call (update on each Pin change):
while True:
while(stempel.readPin(0) == 0):
QApplication.processEvents()
time.sleep(0.01)
self.draw_area.update() # Pin state changed, update polygons
while(stempel.readPin(0) == 1):
QApplication.processEvents()
time.sleep(0.01)
Qt allows scheduling an update for only a portion (region) of the widget, thus optimizing the result. This requires two step:
calling update(QRect) with an appropriate rectangle that covers only the part of the widget that requires repainting;
checking the event.rect() and then implement painting in order to paint only that region;
If you know for sure that only the first X rows are going to change color, then:
self.draw_area.update(
QRect(0, 0, self.draw_area.width(), <height of the repainted rows>)
Then, in the paintEvent:
if event.rect().bottom() < <height of the repainted rows>:
rowRange = range(indexOfTheLastRowToRepaint + 1)
else:
rowRange = range(len(self.array))
Note that another solution could be using QPicture, which is a way to "serialize" a QPainter in order to improve performance and avoid unnecessary computations.
class DrawArea(QWidget):
cache = None
def paintEvent(self, event):
if not self.cache:
self.cache = QPicture()
cachePainter = QPainter(self.cache)
# draw on the painter
cachePainter.end()
painter = QPainter(self)
painter.drawPicture(0, 0, self.cache)
def resizeEvent(self, event):
self.cache = None
The code above is very minimalistic, you might create multiple QPictures for every group of row and then decide which one paint whenever you require it, even by combining the event.rect() checking as explained above.
The major benefit of this technique is that QPainter usually processes a QPicture pretty fast, so you don't have to do all computations required for rows, polygons, etc.
Finally, the image you provided seems very repetitive, almost like a texture. In that case, you might consider using a QPixmap for each group of rows and then create a QBrush with that QPixmap. In that case, you'll only need to call painter.fillRect(self.rect(), self.textureBrush).
Solved it myself by using a QGraphicsScene + QGraphicsView:
self.scene = QGraphicsScene()
self.graphicView = QGraphicsView(self.scene, self)
Creating a list where all polygons are being saved:
self.polygons = [ [0] * len(array[0]) for _ in range(len(array))]
Initial drawing of all polygons:
for y in range(len(array)):
for x in range(len(array[0])):
polygon_size = self.array[y][x]
polygon = createPoly(x, y, polygon_size)
self.polygons[y][x] = self.scene.addPolygon(polygon, QPen(Qt.NoPen), QBrush(Qt.black))
if(y % 50 == 0): QApplication.processEvents()
Update rows indivudually:
for poly_size in active_rows:
for active_row in active_rows[poly_size]:
for x in range(0, len(array[0])):
if(array[active_row][x] == int(poly_size)):
self.polygons[active_row][x].setBrush(QBrush(QColor(20, 0, 255)))
if(array[active_row - 2][x] > 0 and array[active_row - 2][x] == int(poly_size)):
self.polygons[active_row - 2][x].setBrush(QBrush(QColor(175, 175, 175)))

Using turtle in Python to draw six-pointed stars with different side lengths

Hopefully I'll be able to explain this well. I'm currently using helper functions to draw a six-pointed star in the turtle graphics window of python. First, we had to create a function to draw a triangle. Here is my code:
import turtle
wn = turtle.Screen()
tess = turtle.Turtle()
tess.speed(30)
def triangle(sz):
for i in range(3):
tess.fd(sz)
tess.lt(120)
Then, we had to use the triangle function to draw a six-pointed star. Here is my code:
def sixPtdStar(sz):
triangle(sz)
tess.lt(90)
tess.pu()
tess.fd(80)
tess.rt(90)
tess.fd(120)
tess.pd()
tess.rt(180)
triangle(sz)
Now, for me, this all runs smoothly. But the parameters for our test run of those two functions was that sz = 120 (so in the shell we'd type sixPtdStar(120) and it would run. But then we had to draw a row of stars with a new function, and then a BOX outline by those rows of stars, in another function. Here is my code:
def rowOfStars(numInRow,sz):
for i in range(numInRow):
sixPtdStar(sz)
tess.pu()
tess.lt(90)
tess.fd(80)
tess.lt(90)
def sqrOfRows(numInRow, sz):
for i in range(4):
rowOfStars(numInRow, sz)
tess.rt(90)
While this accomplishes the task, it only does so if the sz = 120. And for our test run on the rowOfStars function, the parameters are supposed to be (6, 72) and for the test run on the sqrOfRows function, our parameters are supposed to be (6, 36).
So my issue is this. How can I make this work no matter what sz equals? When I run it as is (with (6, 72) for rowOfStars or (6, 36) for sqrOfRows), the pen moves too far because the triangles aren't as big anymore.
Please let me know if more info is needed! Thanks! (I'm using Python 3.5.2)
Anywhere you use a unit that has a dimension:
tess.fd(80)
tess.fd(120) # probably should be tess.fd(sz)
tess.fd(80)
you need to scale it by what ever logic you used to get from 120 (sz) to 80. However, as #wptreanor mentioned, that logic is slightly flawed as the points on your star are uneven:
Also, your rowOfStars() routine doesn't really draw a row of stars (math is off and the pen is in the wrong state at times.) Simply fixing the scaling won't fix this. Finally, your sqrOfRows() routine won't work until rowOfStars() is fixed, and to make it useful, you need to adjust the starting position on the screen to make room for the drawing.
Below is my rework of your code to address some of these issues. It uses a slightly different calculation of how to position from finishing the lower to starting the upper triangle so the numbers are slightly different:
from turtle import Turtle, Screen
WIDTH_RATIO = 2 * 3**0.5 / 3 # ratio of widest point in star to edge of triangle
def triangle(size):
for i in range(3):
tess.fd(size)
tess.lt(120)
def sixPtdStar(size):
triangle(size)
tess.lt(30)
tess.pu()
tess.fd(size * WIDTH_RATIO)
tess.lt(150)
tess.pd()
triangle(size)
def rowOfStars(numInRow, size):
for i in range(numInRow):
sixPtdStar(size)
tess.pu()
tess.lt(90)
tess.fd(size * WIDTH_RATIO / 2)
tess.lt(90)
tess.pd()
def sqrOfRows(numInRow, size):
tess.pu()
halfSize = numInRow * size / 2
tess.goto(-halfSize, halfSize) # center on screen
tess.pd()
for i in range(4):
rowOfStars(numInRow, size)
tess.rt(90)
screen = Screen()
tess = Turtle()
tess.speed("fastest") # numbers > 10 are all equivalent, safer to use symbols
sqrOfRows(6, 36)
screen.exitonclick()
The problem is in your sixPtdStar() function.
def sixPtdStar(sz):
triangle(sz)
tess.lt(90)
tess.pu()
tess.fd(80) # here
tess.rt(90)
tess.fd(120) # and here
tess.pd()
tess.rt(180)
triangle(sz)
If your function takes a size as a parameter, all functions involving movement (such as forward() or goto()) need to be scaled by the size as well. The following code should work:
def sixPtdStar(sz):
triangle(sz)
tess.lt(90)
tess.pu()
tess.fd((2.0/3.0)*sz) #formerly 80
tess.rt(90)
tess.fd(sz) #formerly 120
tess.pd()
tess.rt(180)
triangle(sz)
This will ensure that all forward movements are proportional to the size of the object you create. You will need to make similar tweaks to your rowOfStars() function. I've also noticed that your six pointed star isn't fully symmetrical. You could resolve that by replacing tess.fd((2.0/3.0)*sz) with tess.fd((7.0/12.0)*sz).

What is the best way to change the sprite used to display an object?

I have an object that changes its display based on which way it's facing. The object takes a 4x4 grid of frames, and uses each row of 4 frames as an animation for each state.
Currently, I'm loading these into separate sprites using:
def create_animation(image_grid, start_idx, end_idx):
frames = []
for frame in image_grid[start_idx:end_idx]:
frames.append(pyglet.image.AnimationFrame(frame, 0.1))
return pyglet.sprite.Sprite(pyglet.image.Animation(frames))
and then adding the sprite that should be displayed to a batch to be drawn, and removing it when it shouldn't be drawn.
However, reading the documentation, I saw this:
Sprite.batch
The sprite can be migrated from one batch to another, or removed from its batch (for individual drawing). Note that this can be an expensive operation.
Is there a better way to achieve what I'm trying to do without the performance hit of switching the individual sprites in and out of batches?
You can load the image as a TextureGrid:
img = pyglet.resource.image("obj_grid.png")
img_grid = pyglet.image.ImageGrid(
img,
4, # rows, direction
4 # cols, frames of the animation
)
texture_grid = pyglet.image.TextureGrid(img_grid) # this is the one you actually use
Create your (single) sprite:
batch = pyglet.graphics.Batch() # unless you already have a batch
my_object = pyglet.sprite.Sprite(
img=texture_grid[0, 0], # [row, col] for starting grid /frame
batch=batch
)
Determine/change direction ("row", I'm guessing based on input?).
Loop over 0-3 ("col"/frame of the animation ):
pyglet.clock.schedule_interval(change_frame, 0.1, my_object)
def change_frame(dt, my_object): # pyglet always passes 'dt' as argument on scheduled calls
my_object.col += 1
my_object.col = my_object.col & 3 # or my_object.col % 3 if its not a power of 2
And set the frame manually:
current_frame = self.texture_grid[self.row, self.col].get_texture()
my_object._set_texture(current_frame)
No additional calls to draw(), no messing with the batch(). Everything is drawn as usual, but you change the texture it draws as you wish :)

(Instantiating an array of Buttons, but only one works

I'm trying to create a GUI for a virtual board for the game Go. There should be an nxn grid of tiles where a player can place a stone, either black or white. Clicking on a tile will make it change from tan(the default) to black, click again to white, and click a third time to go back to tan. Player one can click once on a spot to place a stone there, and player two can click twice (you need to remove stones later, so three clicks resets it). I created a tile object and then used a nested for loop to instantiate 9 by 9 of them. Unfortunately, running the code only seems to produce 1 functional tile, not 81. This code should work on any python machine (I'm using Python 3.4), so you can try to run it and see for yourself. Can anyone point out the reason the loop is only running once?
from tkinter import *
window = Tk()
n = 9
"""
A tile is a point on a game board where black or white pieces can be placed. If there are no pieces, it remains tan.
The basic feature is the "core" field which is a tkinter button. when the color is changed, the button is configured to represent this.
"""
class tile(object):
core = Button(window, height = 2, width = 3, bg = "#F4C364")
def __init__(self):
pass
"""the cycle function makes the tile object actually change color, going between three options: black, white, or tan."""
def cycle(self):
color = self.core.cget("bg")
if(color == "#F4C364"): #tan, the inital value.
self.core.config(bg = "#111111")#white.
elif (color == "#111111"):
self.core.config(bg = "#DDDDDD")#black.
else:
self.core.config(bg = "#F4C364")#back to tan.
board = [] #create overall array
for x in range(n):
board.append([])#add subarrays inside it
for y in range(n):
board[x].append(tile())#add a tile n times in each of the n subarrays
T = board[x][y] #for clarity, T means tile
T.core.config(command = lambda: T.cycle()) #I do this now because cycle hadn't been defined yet when I created the "core" field
T.core.grid(row = x, column = y) #put them into tkinter.
window.mainloop()
As mhawke points out in his answer you need to make the core an instance variable, so that each Tile gets its own core.
And as I mention in my comment above, you also need to fix the Button's command callback function. The code you use in your question will call the .cycle() method of the current value of T, which happens to be the last tile created. So no matter where you click only the last tile changes color. One way to fix that is to pass the current tile as a default argument of the lambda function when you create it. But because you are using OOP to create your Tile there's a better way, which you can see below.
I've made a few modifications to your code.
Although many Tkinter examples use from tkinter import * it's not a good practice. When you do from some_module import * it brings all of the names from some_module into the current module (your script), which means you could accidentally override those names with your own names. Even worse, if you do import * with multiple modules each new module's names can clash with the previous module's names, and you have no way of knowing that's happened until you start getting mysterious bugs. Using import tkinter as tk means you need to do a little more typing, but it makes the resulting program less bug-prone and easier to read.
I've modified the __init__ method so that it is called with the window and the (x, y) location of the tile (it's customary to use x for the horizontal coordinate and y for the vertical coordinate). Each Tile object now keeps track of its current state, where 0=empty, 1=black, 2=white. This makes it easier to update the colors. And because we've passed in the window and (x, y) we can use that info to add the tile to the grid. The tile also remembers the location (in self.location), which may come in handy.
I've modified the cycle method so that it updates both the background color and the activebackground of the tile. So when the mouse hovers over the tile it changes to a color that's (roughly) halfway between its current color and the color it will turn if you click it. IMO, this is nicer than the tile always turning pale grey when the mouse hovers over it.
I've also optimized the code that creates all the tiles and stores them in the board list of lists.
import tkinter as tk
colors = (
#background, #activebackground
("#F4C364", "#826232"), #tan
("#111111", "#777777"), #black
("#DDDDDD", "#E8C8A8"), #white
)
class Tile(object):
""" A tile is a point on a game board where black or white pieces can be placed.
If there are no pieces, it remains tan.
The basic feature is the "core" field which is a tkinter button.
when the color is changed, the button is configured to represent this.
"""
def __init__(self, win, x, y):
#States: 0=empty, 1=black, 2=white
self.state = 0
bg, abg = colors[self.state]
self.core = tk.Button(win, height=2, width=3,
bg=bg, activebackground=abg,
command=self.cycle)
self.core.grid(row=y, column=x)
#self.location = x, y
def cycle(self):
""" the cycle function makes the tile object actually change color,
going between three options: black, white, or tan.
"""
#cycle to the next state. 0 -> 1 -> 2 -> 0
self.state = (self.state + 1) % 3
bg, abg = colors[self.state]
self.core.config(bg=bg, activebackground=abg)
#print(self.location)
window = tk.Tk()
n = 9
board = []
for y in range(n):
row = [Tile(window, x, y) for x in range(n)]
board.append(row)
window.mainloop()
The problem is that core is a class variable which is created once and shared by all instances of class tile. It should be an instance variable for each tile instance.
Move core = Button(window, height = 2, width = 3, bg = "#F4C364") into tile.__init__() like this:
class Tile(object):
def __init__(self):
self.core = Button(window, height = 2, width = 3, bg = "#F4C364")
The root of the problem is that core is shared by all instances of the class by virtue of how you've defined it. You need to move creation of the button into the initializer.
I also suggest moving the configuration of the command into the button itself. The caller shouldn't need (nor care) how the button works internally. Personally I'd have the tile inherit from Button, but if you favor composition over inheritance I'll stick with that.
Example:
class tile(object):
def __init__(self):
self.core = Button(window, height = 2, width = 3, bg = "#F4C364"
command=self.cycle)

How can you add a camera to a robot in the Breve Simulator?

I've created a two wheeled robot based on the braitenberg vehicle. Our robots have two wheels and a PolygonDisk body(Much like kepera and e-puck robots). I would like to add a camera to the front of the robot. The problem then becomes how to control the camera and how to keep pointing it in the right direction(same direction as the robot). How can you make the camera point in the same direction as the robot ?
After much trying and failing I finally made it work.
So here is how I did it:
The general idea is to have an link or object linked to the vehicle and then measuring
its rotation and location in order to find out in which direction the camera should be aimed.
1) Add an object that is linked to the robot:
def addVisualCam(self):
joint = None
cam = breve.createInstances(breve.Link,1)
cam.setShape(breve.createInstances(breve.PolygonCone, 1).initWith(10,0.08,0.08))
joint = breve.createInstances(breve.FixedJoint,1)
# So ad-hoc it hurts. oh well...
joint.setRelativeRotation(breve.vector(0,1,0), -3.14/2)
joint.link(breve.vector(0,1.05,0), breve.vector(0,0,0), cam, self.vehicle.bodyLink, 0)
joint.setDoubleSpring(300, 1.01000, -1.01000)
self.vehicle.addDependency(joint)
self.vehicle.addDependency(cam)
cam.setColor(breve.vector(0,0,0))
self.cam = cam
2) Add this postIterate:
def postIterate(self):
look_at = self.cam.getLocation() + (self.cam.getRotation() * breve.vector(0,0,1))
look_from = -(self.cam.getRotation()*breve.vector(0,0,1))
self.vision.look(look_at, look_from)

Categories

Resources