Search is not available for this dataset
text stringlengths 75 104k |
|---|
def setRot(self,data,rot):
"""
Sets the rotation of this bone on the given entity.
``data`` is the entity to modify in dictionary form.
``rot`` is the rotation of the bone in the format used in :py:func:`calcSphereCoordinates()`\ .
"""
self.ensureBones(data)
rot = rot[0]%360,max(-90, min(90, rot[1]))
data["_bones"][self.name]["rot"]=rot |
def setLength(self,data,blength):
"""
Sets the length of this bone on the given entity.
``data`` is the entity to modify in dictionary form.
``blength`` is the new length of the bone.
"""
self.ensureBones(data)
data["_bones"][self.name]["length"]=blength |
def setParent(self,parent):
"""
Sets the parent of this bone for all entities.
Note that this method must be called before many other methods to ensure internal state has been initialized.
This method also registers this bone as a child of its parent.
"""
self.parent = parent
self.parent.child_bones[self.name]=self |
def setRotate(self,data):
"""
Sets the OpenGL state required for proper drawing of the model.
Mostly rotates and translates the camera.
It is important to call :py:meth:`unsetRotate()` after calling this method to properly unset state and avoid OpenGL errors.
"""
self.parent.setRotate(data)
glPushMatrix()
x,y = self.getRot(data)
pivot = self.getPivotPoint(data)
px,py,pz = pivot
#ppx,ppy,ppz = self.parent.getPivotPoint(data)
#rot_vec = px-ppx,py-ppy,pz-ppz
#print([px,py,pz],[ppx,ppy,ppz],rot_vec,[x,y],self.getLength(data))
#norm = v_normalize(rot_vec,self.name) if v_magnitude(rot_vec)==0 else [0,1,0] # prevents a zero divison error
normx = [0,1,0] # currently fixed to the up vector, should be changed in the future for proper rotation that is not along the y or z axis
normy = [0,0,1]
#offset = -px,-py,-pz
glTranslatef(px,py,pz)#-offset[0],-offset[1],-offset[2])
glRotatef(x-self.start_rot[0], normx[0],normx[1],normx[2])
glRotatef(y-self.start_rot[1], normy[0],normy[1],normy[2])
glTranslatef(-px,-py,-pz)#offset[0],offset[1],offset[2]) |
def getPivotPoint(self,data):
"""
Returns the point this bone pivots around on the given entity.
This method works recursively by calling its parent and then adding its own offset.
The resulting coordinate is relative to the entity, not the world.
"""
ppos = self.parent.getPivotPoint(data)
rot = self.parent.getRot(data)
length = self.parent.getLength(data)
out = calcSphereCoordinates(ppos,length,rot)
return out |
def getVertices(self,data):
"""
Returns the vertices of this region already transformed and ready-to-use.
Internally uses :py:meth:`Bone.transformVertices()`\ .
"""
return self.bone.transformVertices(data,self.vertices,self.dims) |
def getTexCoords(self,data):
"""
Returns the texture coordinates, if any, to accompany the vertices of this region already transformed.
Note that it is recommended to check the :py:attr:`enable_tex` flag first.
Internally uses :py:meth:`Material.transformTexCoords()`\ .
"""
return self.material.transformTexCoords(data,self.tex_coords,self.tex_dims) |
def startAnimation(self,data,jumptype):
"""
Callback that is called to initialize this animation on a specific actor.
Internally sets the ``_anidata`` key of the given dict ``data``\ .
``jumptype`` is either ``jump`` or ``animate`` to define how to switch to this animation.
"""
data["_anidata"]={}
adata = data["_anidata"]
adata["keyframe"]=0
adata["last_tick"]=time.time()
adata["jumptype"]=jumptype
adata["phase"]="transition" |
def tickEntity(self,data):
"""
Callback that should be called regularly to update the animation.
It is recommended to call this method about 60 times a second for smooth animations. Irregular calling of this method will be automatically adjusted.
This method sets all the bones in the given actor to the next state of the animation.
Note that :py:meth:`startAnimation()` must have been called before calling this method.
"""
adata = data["_anidata"]
if adata.get("anitype",self.name)!=self.name:
return # incorrectly called
dt = time.time()-adata.get("last_tick",time.time())
adata["last_tick"]=time.time()
if adata.get("phase","transition")=="transition":
# If transitioning to this animation
if adata.get("jumptype",self.default_jt)=="jump":
# Jumping to the animation, e.g. set all bones to the start frame
for bone,dat in self.start_frame.get("bones",{}).items():
if "rot" in dat:
self.bones[bone].setRot(data,dat["rot"])
if "length" in dat:
self.bones[bone].setLength(data,dat["length"])
adata["phase"]="animation"
if self.atype=="keyframes":
adata["from_frame"]=self.start_frame.get("frame",0)
elif adata.get("jumptype",self.default_jt)=="animate":
raise NotImplementedError("Animation update phase transition type animate not yet implemented")
# Not yet working
if "transition_frame" not in adata:
adata["transition_frame"] = 0
tlen = self.anidata.get("transition_length",self.anidata.get("length",60)/3)
tspeed = self.anidata.get("transition_speed",self.anidata.get("keyframespersecond",60))
framediff=int(dt/(1./tspeed)) # Number of frames that have passed since the last update
overhang = dt-(framediff*(1./tspeed)) # time that has passed but is not enough for a full frame
adata["last_tick"]-=overhang # causes the next frame to include the overhang from this frame
if framediff == 0:
return # optimization that saves time
frame1 = adata["transition_frame"]
adata["transition_frame"]+=framediff
if adata["transition_frame"]>tlen:
adata["phase"]="animation"
if self.atype=="keyframes":
adata["from_frame"]=self.start_frame.get("frame",0)
return
frame2 = adata["transition_frame"]
if "frombones" not in adata:
frombones = {}
for bname,bone in self.bones.items():
frombones[bname]={"rot":bone.getRot(data),"length":bone.getLength(data)}
adata["frombones"] = frombones
if "tobones" not in adata:
tobones = {}
for bname,bone in self.start_frame["bones"].items():
tobones[bname]=bone
adata["tobones"] = tobones
frombones = adata["frombones"]
tobones = adata["tobones"]
from_frame = 0
to_frame = tlen
for bname,bone in self.bones.items():
# rot
if bname not in frombones or bname not in tobones:
continue
from_rot = frombones[bname]["rot"]
to_rot = tobones[bname]["rot"]
from_x,from_y=from_rot
to_x,to_y=to_rot
delta_per_frame_x = (to_x-from_x)/(to_frame-from_frame)
delta_per_frame_y = (to_y-from_y)/(to_frame-from_frame)
delta_x = delta_per_frame_x*(frame2-frame1)
delta_y = delta_per_frame_y*(frame2-frame1)
rot = bone.getRot(data)
new_rot = [rot[0]+delta_x,rot[1]+delta_y]
bone.setRot(data,new_rot)
# length
# Not yet implemented
elif adata["phase"]=="animation":
# If animating
if self.atype == "static":
pass # Should not need any updates as the transition will set the bones
elif self.atype == "keyframes":
framediff=int(dt/(1./self.kps)) # Number of frames that have passed since the last update
overhang = dt-(framediff*(1./self.kps)) # time that has passed but is not enough for a full frame
adata["last_tick"]-=overhang # causes the next frame to include the overhang from this frame
if framediff == 0:
return # optimization that saves time
frame1 = adata["keyframe"]
adata["keyframe"]+=framediff
if adata["keyframe"]>self.anilength:
repeat = True
adata["keyframe"]%=self.anilength
else:
repeat = False
frame2 = adata["keyframe"]
if repeat:
frame1 = frame2
frame2+=1
for bname,bone in self.bones.items():
# Rot
if bname in self.rframes_per_bone:
from_frame = None#adata["from_frame"]
to_frame = None
for framenum,rot in self.rframes_per_bone[bname].items():
if (from_frame is None or framenum>from_frame) and framenum<=frame1:
# from_frame is the largest frame number that is before the starting point
from_frame = framenum
if (to_frame is None or framenum<to_frame) and framenum>=frame2:
# to_frame is the smallest frame number that is after the end point
to_frame = framenum
if from_frame is None or to_frame is None:
raise ValueError("Invalid frames for bone %s in animation %s"%(bname,self.name))
if from_frame==to_frame or repeat:
if self.anidata.get("repeat","jump")=="jump":
for b,dat in self.start_frame.get("bones",{}).items():
if "rot" in dat:
self.bones[b].setRot(data,dat["rot"])
if "length" in dat:
self.bones[b].setLength(data,dat["length"])
elif self.anidata.get("repeat","jump")=="animate":
from_frame = adata["to_frame"]
adata["from_frame"]=from_frame
adata["to_frame"]=to_frame
from_rot = self.rframes_per_bone[bname][from_frame]
to_rot = self.rframes_per_bone[bname][to_frame]
from_x,from_y=from_rot
to_x,to_y=to_rot
if self.anidata.get("interpolation","linear") == "linear":
delta_per_frame_x = (to_x-from_x)/(to_frame-from_frame)
delta_per_frame_y = (to_y-from_y)/(to_frame-from_frame)
delta_x = delta_per_frame_x*(frame2-frame1)
delta_y = delta_per_frame_y*(frame2-frame1)
rot = bone.getRot(data)
new_rot = [rot[0]+delta_x,rot[1]+delta_y]
elif self.anidata["interpolation"] == "jump":
new_rot = to_x,to_y
else:
raise ValueError("Invalid interpolation method '%s' for animation %s"%(self.anidata["interpolation"],self.name))
bone.setRot(data,new_rot)
# Length
if bname in self.lframes_per_bone:
# Not yet implemented
pass
else:
# Should not be possible, but still
raise ValueError("Invalid animation type %s for animation %s during tick"%(self.atype,name)) |
def set_state(self):
"""
Sets the state required for this actor.
Currently translates the matrix to the position of the actor.
"""
x,y,z = self.obj.pos
glTranslatef(x,y,z) |
def unset_state(self):
"""
Resets the state required for this actor to the default state.
Currently resets the matrix to its previous translation.
"""
x,y,z = self.obj.pos
glTranslatef(-x,-y,-z) |
def set_state(self):
"""
Sets the state required for this vertex region.
Currently binds and enables the texture of the material of the region.
"""
glEnable(self.region.material.target)
glBindTexture(self.region.material.target, self.region.material.id)
self.region.bone.setRotate(self.data) |
def unset_state(self):
"""
Resets the state required for this actor to the default state.
Currently only disables the target of the texture of the material, it may still be bound.
"""
glDisable(self.region.material.target)
self.region.bone.unsetRotate(self.data) |
def ensureModelData(self,obj):
"""
Ensures that the given ``obj`` has been initialized to be used with this model.
If the object is found to not be initialized, it will be initialized.
"""
if not hasattr(obj,"_modeldata"):
self.create(obj,cache=True)
if "_modelcache" not in obj._modeldata:
# Assume all initialization is missing, simply reinitialize
self.create(obj,cache=True) |
def create(self,obj,cache=False):
"""
Initializes per-actor data on the given object for this model.
If ``cache`` is set to True, the entity will not be redrawn after initialization.
Note that this method may set several attributes on the given object, most of them starting with underscores.
During initialization of vertex regions, several vertex lists will be created.
If the given object has an attribute called ``batch3d`` it will be used, else it will be created.
If the batch already existed, the :py:meth:`draw()` method will do nothing, else it will draw the batch.
Memory leaks may occur if this is called more than once on the same object without calling :py:meth:`cleanup()` first.
"""
obj._modeldata = {}
data = obj._modeldata
data["_model"]=self
data["_modelcache"] = {}
moddata = data["_modelcache"]
# Model group, for pos of entity
moddata["group"] = JSONModelGroup(self,data,obj)
modgroup = moddata["group"]
if not hasattr(obj,"batch3d"):
obj.batch3d = pyglet.graphics.Batch()
data["_manual_render"]=True
# Vlists/Regions
moddata["vlists"] = {}
for name,region in self.modeldata["regions"].items():
v = region.getVertices(data)
vlistlen = int(len(v)/region.dims)
if region.enable_tex:
vlist = obj.batch3d.add(vlistlen,region.getGeometryType(data),JSONRegionGroup(self,data,region,modgroup),
"v3f/static",
"t3f/static",
)
else:
vlist = obj.batch3d.add(vlistlen,region.getGeometryType(data),modgroup,
"v3f/static",
)
moddata["vlists"][name]=vlist
self.setAnimation(obj,self.modeldata["default_animation"].name,transition="jump")
self.data = data
if not cache:
self.redraw(obj) |
def cleanup(self,obj):
"""
Cleans up any left over data structures, including vertex lists that reside in GPU memory.
Behaviour is undefined if it is attempted to use this model with the same object without calling :py:meth:`create()` first.
It is very important to call this method manually during deletion as this will delete references to data objects stored in global variables of third-party modules.
"""
if not hasattr(obj,"_modeldata"):
return # already not initialized
data = obj._modeldata
if "_modelcache" in data:
moddata = data["_modelcache"]
if "vlists" in moddata:
for vlist in list(moddata["vlists"].keys()):
del moddata["vlists"][vlist]
del moddata["vlists"]
if "_bones" in data:
for bone in list(data["_bones"].keys()):
del data["_bones"][bone]
del data["_bones"]
if "_anidata" in data:
adata = data["_anidata"]
if "_schedfunc" in adata:
pyglet.clock.unschedule(adata["_schedfunc"])
if data.get("_manual_render",False):
del obj.batch3d
# Removes open vertex lists and other caches
if "_modelcache" not in data:
return
moddata = data["_modelcache"]
if "vlist" in moddata:
moddata["vlist"].delete() # Free up the graphics memory
if "group" in moddata:
del moddata["group"]
del data["_modelcache"], moddata |
def redraw(self,obj):
"""
Redraws the model of the given object.
Note that currently this method probably won't change any data since all movement and animation is done through pyglet groups.
"""
self.ensureModelData(obj)
data = obj._modeldata
vlists = data["_modelcache"]["vlists"]
for name,region in self.modeldata["regions"].items():
vlists[name].vertices = region.getVertices(data)
if region.enable_tex:
vlists[name].tex_coords = region.getTexCoords(data) |
def draw(self,obj):
"""
Actually draws the model of the given object to the render target.
Note that if the batch used for this object already existed, drawing will be skipped as the batch should be drawn by the owner of it.
"""
self.ensureModelData(obj)
data = obj._modeldata
if data.get("_manual_render",False):
obj.batch3d.draw() |
def setAnimation(self,obj,animation,transition=None,force=False):
"""
Sets the animation to be used by the object.
See :py:meth:`Actor.setAnimation()` for more information.
"""
self.ensureModelData(obj)
data = obj._modeldata
# Validity check
if animation not in self.modeldata["animations"]:
raise ValueError("There is no animation of name '%s' for model '%s'"%(animation,self.modelname))
if data.get("_anidata",{}).get("anitype",None)==animation and not force:
return # animation is already running
# Cache the obj to improve readability
anim = self.modeldata["animations"][animation]
# Set to default if not set
if transition is None:
transition = anim.default_jt
# Notify the animation to allow it to initialize itself
anim.startAnimation(data,transition)
# initialize animation data
if "_anidata" not in data:
data["_anidata"]={}
adata = data["_anidata"]
adata["anitype"]=animation
if "_schedfunc" in adata:
# unschedule the old animation, if any
# prevents clashing and crashes
pyglet.clock.unschedule(adata["_schedfunc"])
# Schedule the animation function
def schedfunc(*args):
# This function is defined locally to create a closure
# The closure stores the local variables, e.g. anim and data even after the parent function has finished
# Note that this may also prevent the garbage collection of any objects defined in the parent scope
anim.tickEntity(data)
# register the function to pyglet
pyglet.clock.schedule_interval(schedfunc,1./(anim.kps if anim.atype=="keyframes" else 60))
# save it for later for de-initialization
adata["_schedfunc"] = schedfunc |
def setModel(self,model):
"""
Sets the model this actor should use when drawing.
This method also automatically initializes the new model and removes the old, if any.
"""
if self.model is not None:
self.model.cleanup(self)
self.model = model
model.create(self) |
def setAnimation(self,animation,transition=None,force=False):
"""
Sets the animation the model of this actor should show.
``animation`` is the name of the animation to switch to.
``transition`` can be used to override the transition between the animations.
``force`` can be used to force reset the animation even if it is already running.
If there is no model set for this actor, a :py:exc:`RuntimeError` will be raised.
"""
if self.model is None:
raise RuntimeError("Can only set animation if a model is set")
self.model.setAnimation(self,animation,transition,force) |
def move(self,dist):
"""
Moves the actor using standard trigonometry along the current rotational vector.
:param float dist: Distance to move
.. todo::
Test this method, also with negative distances
"""
x, y = self._rot
y_angle = math.radians(y)
x_angle = math.radians(x)
m = math.cos(y_angle)
dy = math.sin(y_angle)
dy = 0.0
dx = math.cos(x_angle)
dz = math.sin(x_angle)
dx,dy,dz = dx*dist,dy*dist,dz*dist
x,y,z = self._pos
self.pos = x+dx,y+dy,z+dz
return dx,dy,dz |
def write_reports(self, relative_path, suite_name, reports,
package_name=None):
"""write the collection of reports to the given path"""
dest_path = self.reserve_file(relative_path)
with open(dest_path, 'wb') as outf:
outf.write(toxml(reports, suite_name, package_name=package_name))
return dest_path |
def reserve_file(self, relative_path):
"""reserve a XML file for the slice at <relative_path>.xml
- the relative path will be created for you
- not writing anything to that file is an error
"""
if os.path.isabs(relative_path):
raise ValueError('%s must be a relative path' % relative_path)
dest_path = os.path.join(self.root_dir, '%s.xml' % relative_path)
if os.path.exists(dest_path):
raise ValueError('%r must not already exist' % dest_path)
if dest_path in self.expected_xunit_files:
raise ValueError('%r already reserved' % dest_path)
dest_dir = os.path.dirname(dest_path)
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
self.expected_xunit_files.append(dest_path)
return dest_path |
def toxml(test_reports, suite_name,
hostname=gethostname(), package_name="tests"):
"""convert test reports into an xml file"""
testsuites = et.Element("testsuites")
testsuite = et.SubElement(testsuites, "testsuite")
test_count = len(test_reports)
if test_count < 1:
raise ValueError('there must be at least one test report')
assert test_count > 0, 'expecting at least one test'
error_count = len([r for r in test_reports if r.errors])
failure_count = len([r for r in test_reports if r.failures])
ts = test_reports[0].start_ts
start_timestamp = datetime.fromtimestamp(ts).isoformat()
total_duration = test_reports[-1].end_ts - test_reports[0].start_ts
def quote_attribute(value):
return value if value is not None else "(null)"
testsuite.attrib = dict(
id="0",
errors=str(error_count),
failures=str(failure_count),
tests=str(test_count),
hostname=quote_attribute(hostname),
timestamp=quote_attribute(start_timestamp),
time="%f" % total_duration,
name=quote_attribute(suite_name),
package=quote_attribute(package_name),
)
for r in test_reports:
test_name = r.name
test_duration = r.end_ts - r.start_ts
class_name = r.src_location
testcase = et.SubElement(testsuite, "testcase")
testcase.attrib = dict(
name=test_name,
classname=quote_attribute(class_name),
time="%f" % test_duration,
)
if r.errors or r.failures:
if r.failures:
failure = et.SubElement(testcase, "failure")
failure.attrib = dict(
type="exception",
message=quote_attribute('\n'.join(['%s' % e for e in r.failures])),
)
else:
error = et.SubElement(testcase, "error")
error.attrib = dict(
type="exception",
message=quote_attribute('\n'.join(['%s' % e for e in r.errors])),
)
return et.tostring(testsuites, encoding="utf-8") |
def setup(self):
"""
Sets up the OpenGL state.
This method should be called once after the config has been created and before the main loop is started.
You should not need to manually call this method, as it is automatically called by :py:meth:`run()`\ .
Repeatedly calling this method has no effects.
"""
if self._setup:
return
self._setup = True
# Ensures that default values are supplied
#self.cleanConfig()
# Sets min/max window size, if specified
if self.cfg["graphics.min_size"] is not None:
self.set_minimum_size(*self.cfg["graphics.min_size"])
if self.cfg["graphics.max_size"] is not None:
self.set_maximum_size(*self.cfg["graphics.max_size"])
# Sets up basic OpenGL state
glClearColor(*self.cfg["graphics.clearColor"])
glEnable(GL_DEPTH_TEST)
glEnable(GL_BLEND)
glShadeModel(GL_SMOOTH)
if self.cfg["graphics.fogSettings"]["enable"]:
self.setupFog()
if self.cfg["graphics.lightSettings"]["enable"]:
self.setupLight() |
def setupFog(self):
"""
Sets the fog system up.
The specific options available are documented under :confval:`graphics.fogSettings`\ .
"""
fogcfg = self.cfg["graphics.fogSettings"]
if not fogcfg["enable"]:
return
glEnable(GL_FOG)
if fogcfg["color"] is None:
fogcfg["color"] = self.cfg["graphics.clearColor"]
# Set the fog color.
glFogfv(GL_FOG_COLOR, (GLfloat * 4)(*fogcfg["color"]))
# Set the performance hint.
glHint(GL_FOG_HINT, GL_DONT_CARE) # TODO: add customization, including headless support
# Specify the equation used to compute the blending factor.
glFogi(GL_FOG_MODE, GL_LINEAR)
# How close and far away fog starts and ends. The closer the start and end,
# the denser the fog in the fog range.
glFogf(GL_FOG_START, fogcfg["start"])
glFogf(GL_FOG_END, fogcfg["end"]) |
def run(self,evloop=None):
"""
Runs the application in the current thread.
This method should not be called directly, especially when using multiple windows, use :py:meth:`Peng.run()` instead.
Note that this method is blocking as rendering needs to happen in the main thread.
It is thus recommendable to run your game logic in another thread that should be started before calling this method.
``evloop`` may optionally be a subclass of :py:class:`pyglet.app.base.EventLoop` to replace the default event loop.
"""
self.setup()
if evloop is not None:
pyglet.app.event_loop = evloop
pyglet.app.run() # This currently just calls the basic pyglet main loop, maybe implement custom main loop for more control |
def changeMenu(self,menu):
"""
Changes to the given menu.
``menu`` must be a valid menu name that is currently known.
.. versionchanged:: 1.2a1
The push/pop handlers have been deprecated in favor of the new :py:meth:`Menu.on_enter() <peng3d.menu.Menu.on_enter>`\ , :py:meth:`Menu.on_exit() <peng3d.menu.Menu.on_exit>`\ , etc. events.
"""
if menu not in self.menus:
raise ValueError("Menu %s does not exist!"%menu)
elif menu == self.activeMenu:
return # Ignore double menu activation to prevent bugs in menu initializer
old = self.activeMenu
self.activeMenu = menu
if old is not None:
self.menus[old].on_exit(menu)
self.menus[old].doAction("exit")
#self.pop_handlers()
self.menu.on_enter(old)
self.menu.doAction("enter")
self.peng.sendEvent("peng3d:window.menu.change",{"peng":self.peng,"window":self,"old":old,"menu":menu}) |
def addMenu(self,menu):
"""
Adds a menu to the list of menus.
"""
# If there is no menu selected currently, this menu will automatically be made active.
# Add the line above to the docstring if fixed
self.menus[menu.name]=menu
self.peng.sendEvent("peng3d:window.menu.add",{"peng":self.peng,"window":self,"menu":menu}) |
def dispatch_event(self,event_type,*args):
"""
Internal event handling method.
This method extends the behavior inherited from :py:meth:`pyglet.window.Window.dispatch_event()` by calling the various :py:meth:`handleEvent()` methods.
By default, :py:meth:`Peng.handleEvent()`\ , :py:meth:`handleEvent()` and :py:meth:`Menu.handleEvent()` are called in this order to handle events.
Note that some events may not be handled by all handlers during early startup.
"""
super(PengWindow,self).dispatch_event(event_type,*args)
try:
p = self.peng
m = self.menu
except AttributeError:
# To prevent early startup errors
if hasattr(self,"peng") and self.peng.cfg["debug.events.logerr"]:
print("Error:")
traceback.print_exc()
return
p.handleEvent(event_type,args,self)
self.handleEvent(event_type,args)
m.handleEvent(event_type,args) |
def toggle_exclusivity(self,override=None):
"""
Toggles mouse exclusivity via pyglet's :py:meth:`set_exclusive_mouse()` method.
If ``override`` is given, it will be used instead.
You may also read the current exclusivity state via :py:attr:`exclusive`\ .
"""
if override is not None:
new = override
else:
new = not self.exclusive
self.exclusive = new
self.set_exclusive_mouse(self.exclusive)
self.peng.sendEvent("peng3d:window.toggle_exclusive",{"peng":self.peng,"window":self,"exclusive":self.exclusive}) |
def set2d(self):
"""
Configures OpenGL to draw in 2D.
Note that wireframe mode is always disabled in 2D-Mode, but can be re-enabled by calling ``glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)``\ .
"""
# Light
glDisable(GL_LIGHTING)
# To avoid accidental wireframe GUIs and fonts
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL)
width, height = self.get_size()
glDisable(GL_DEPTH_TEST)
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, 0, height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() |
def set3d(self,cam):
"""
Configures OpenGL to draw in 3D.
This method also applies the correct rotation and translation as set in the supplied camera ``cam``\ .
It is discouraged to use :py:func:`glTranslatef()` or :py:func:`glRotatef()` directly as this may cause visual glitches.
If you need to configure any of the standard parameters, see the docs about :doc:`/configoption`\ .
The :confval:`graphics.wireframe` config value can be used to enable a wireframe mode, useful for debugging visual glitches.
"""
if not isinstance(cam,camera.Camera):
raise TypeError("cam is not of type Camera!")
# Light
#glEnable(GL_LIGHTING)
if self.cfg["graphics.wireframe"]:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
width, height = self.get_size()
glEnable(GL_DEPTH_TEST)
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(self.cfg["graphics.fieldofview"], width / float(height), self.cfg["graphics.nearclip"], self.cfg["graphics.farclip"]) # default 60
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
x, y = cam.rot
glRotatef(x, 0, 1, 0)
glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
x, y, z = cam.pos
glTranslatef(-x, -y, -z) |
def redraw_label(self):
"""
Re-draws the text by calculating its position.
Currently, the text will always be centered on the position of the label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
self._label.font_name = self.font_name
self._label.font_size = self.font_size
self._label.font_color = self.font_color
self._label.x = int(x+sx/2.)
self._label.y = int(y+sy/2.)
self._label.width = self.size[0]
self._label.height = self.size[1]
self._label._update() |
def redraw_label(self):
"""
Re-draws the label by calculating its position.
Currently, the label will always be centered on the position of the label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
x = x+self.bg.border[0]
y = y+sy/2.-self._text.font_size/4.
w = self.size[0]
h = self.size[1]
self._text.x,self._text.y = x,y
self._text.width,self._text.height=w,h
self._default.x,self._default.y = x,y
self._default.width,self._default.height=w,h
self._text._update() # Needed to prevent the label from drifting to the top-left after resizing by odd amounts
self._default._update() |
def changeSubMenu(self,submenu):
"""
Changes the submenu that is displayed.
:raises ValueError: if the name was not previously registered
"""
if submenu not in self.submenus:
raise ValueError("Submenu %s does not exist!"%submenu)
elif submenu == self.activeSubMenu:
return # Ignore double submenu activation to prevent bugs in submenu initializer
old = self.activeSubMenu
self.activeSubMenu = submenu
if old is not None:
self.submenus[old].on_exit(submenu)
self.submenus[old].doAction("exit")
self.submenu.on_enter(old)
self.submenu.doAction("enter") |
def draw(self):
"""
Draws the submenu and its background.
Note that this leaves the OpenGL state set to 2d drawing.
"""
# Sets the OpenGL state for 2D-Drawing
self.window.set2d()
# Draws the background
if isinstance(self.bg,Layer):
self.bg._draw()
elif hasattr(self.bg,"draw") and callable(self.bg.draw):
self.bg.draw()
elif isinstance(self.bg,list) or isinstance(self.bg,tuple):
self.bg_vlist.draw(GL_QUADS)
elif callable(self.bg):
self.bg()
elif isinstance(self.bg,Background):
# The background will be drawn via the batch
if not self.bg.initialized:
self.bg.init_bg()
self.bg.redraw_bg()
self.bg.initialized=True
elif self.bg=="blank":
pass
else:
raise TypeError("Unknown background type")
# In case the background modified relevant state
self.window.set2d()
# Check that all widgets that need redrawing have been redrawn
for widget in self.widgets.values():
if widget.do_redraw:
widget.on_redraw()
widget.do_redraw = False
# Actually draw the content
self.batch2d.draw()
# Call custom draw methods where needed
for widget in self.widgets.values():
widget.draw() |
def delWidget(self,widget):
"""
Deletes the widget by the given name.
Note that this feature is currently experimental as there seems to be a memory leak with this method.
"""
# TODO: fix memory leak upon widget deletion
#print("*"*50)
#print("Start delWidget")
if isinstance(widget,BasicWidget):
widget = widget.name
if widget not in self.widgets:
return
w = self.widgets[widget]
#print("refs: %s"%sys.getrefcount(w))
w.delete()
del self.widgets[widget]
del widget
#w_wref = weakref.ref(w)
#print("GC: GARBAGE")
#print(gc.garbage)
#print("Widget Info")
#print(w_wref())
#import objgraph
#print("Objgraph")
#objgraph.show_refs([w], filename='./mem_widget.png')
#print("refs: %s"%sys.getrefcount(w))
#w_r = gc.get_referrers(w)
#print("GC: REFS")
#for w_ref in w_r:
# print(repr(w_ref)[:512])
#print("GC: END")
#print("len: %s"%len(w_r))
#del w_ref,w_r
#print("after del %s"%w_wref())
#print("refs: %s"%sys.getrefcount(w))
del w |
def setBackground(self,bg):
"""
Sets the background of the submenu.
The background may be a RGB or RGBA color to fill the background with.
Alternatively, a :py:class:`peng3d.layer.Layer` instance or other object with a ``.draw()`` method may be supplied.
It is also possible to supply any other method or function that will get called.
Also, the strings ``flat``\ , ``gradient``\ , ``oldshadow`` and ``material`` may be given, resulting in a background that looks similar to buttons.
Lastly, the string ``"blank"`` may be passed to skip background drawing.
"""
self.bg = bg
if isinstance(bg,list) or isinstance(bg,tuple):
if len(bg)==3 and isinstance(bg,list):
bg.append(255)
self.bg_vlist.colors = bg*4
elif bg in ["flat","gradient","oldshadow","material"]:
self.bg = ContainerButtonBackground(self,borderstyle=bg)
self.on_resize(self.window.width,self.window.height) |
def getPosSize(self):
"""
Helper function converting the actual widget position and size into a usable and offsetted form.
This function should return a 6-tuple of ``(sx,sy,x,y,bx,by)`` where sx and sy are the size, x and y the position and bx and by are the border size.
All values should be in pixels and already include all offsets, as they are used directly for generation of vertex data.
This method can also be overridden to limit the background to a specific part of its widget.
"""
sx,sy = self.widget.size
x,y = self.widget.pos
bx,by = self.border
return sx,sy,x,y,bx,by |
def getColors(self):
"""
Overrideable function that generates the colors to be used by various borderstyles.
Should return a 5-tuple of ``(bg,o,i,s,h)``\ .
``bg`` is the base color of the background.
``o`` is the outer color, it is usually the same as the background color.
``i`` is the inner color, it is usually lighter than the background color.
``s`` is the shadow color, it is usually quite a bit darker than the background.
``h`` is the highlight color, it is usually quite a bit lighter than the background.
"""
bg = self.submenu.bg[:3] if isinstance(self.submenu.bg,list) or isinstance(self.submenu.bg,tuple) else [242,241,240]
o,i = bg, [min(bg[0]+8,255),min(bg[1]+8,255),min(bg[2]+8,255)]
s,h = [max(bg[0]-40,0),max(bg[1]-40,0),max(bg[2]-40,0)], [min(bg[0]+12,255),min(bg[1]+12,255),min(bg[2]+12,255)]
# Outer,Inner,Shadow,Highlight
return bg,o,i,s,h |
def redraw_bg(self):
# Convenience variables
sx,sy = self.widget.size
x,y = self.widget.pos
bx,by = self.border
# Button background
# Outer vertices
# x y
v1 = x, y+sy
v2 = x+sx, y+sy
v3 = x, y
v4 = x+sx, y
# Inner vertices
# x y
v5 = x+bx, y+sy-by
v6 = x+sx-bx, y+sy-by
v7 = x+bx, y+by
v8 = x+sx-bx, y+by
# 5 Quads, for edges and the center
qb1 = v5+v6+v2+v1
qb2 = v8+v4+v2+v6
qb3 = v3+v4+v8+v7
qb4 = v3+v7+v5+v1
qc = v7+v8+v6+v5
v = qb1+qb2+qb3+qb4+qc
self.vlist.vertices = v
bg = self.submenu.bg[:3] if isinstance(self.submenu.bg,list) or isinstance(self.submenu.bg,tuple) else [242,241,240]
o,i = bg, [min(bg[0]+8,255),min(bg[1]+8,255),min(bg[2]+8,255)]
s,h = [max(bg[0]-40,0),max(bg[1]-40,0),max(bg[2]-40,0)], [min(bg[0]+12,255),min(bg[1]+12,255),min(bg[2]+12,255)]
# Outer,Inner,Shadow,Highlight
if self.borderstyle == "flat":
if self.widget.pressed:
i = s
cb1 = i+i+i+i
cb2 = i+i+i+i
cb3 = i+i+i+i
cb4 = i+i+i+i
cc = i+i+i+i
elif self.borderstyle == "gradient":
if self.widget.pressed:
i = s
elif self.widget.is_hovering:
i = [min(i[0]+6,255),min(i[1]+6,255),min(i[2]+6,255)]
cb1 = i+i+o+o
cb2 = i+o+o+i
cb3 = o+o+i+i
cb4 = o+i+i+o
cc = i+i+i+i
elif self.borderstyle == "oldshadow":
if self.widget.pressed:
i = s
s,h = h,s
elif self.widget.is_hovering:
i = [min(i[0]+6,255),min(i[1]+6,255),min(i[2]+6,255)]
s = [min(s[0]+6,255),min(s[1]+6,255),min(s[2]+6,255)]
cb1 = h+h+h+h
cb2 = s+s+s+s
cb3 = s+s+s+s
cb4 = h+h+h+h
cc = i+i+i+i
elif self.borderstyle == "material":
if self.widget.pressed:
i = [max(bg[0]-20,0),max(bg[1]-20,0),max(bg[2]-20,0)]
elif self.widget.is_hovering:
i = [max(bg[0]-10,0),max(bg[1]-10,0),max(bg[2]-10,0)]
cb1 = s+s+o+o
cb2 = s+o+o+s
cb3 = o+o+s+s
cb4 = o+s+s+o
cc = i+i+i+i
else:
raise ValueError("Invalid Border style")
c = cb1+cb2+cb3+cb4+cc
self.vlist.colors = c
# Cross
# Old method that displayed a tick
"""if not self.widget.pressed:
self.vlist_cross.colors = 6*bg
else:
if self.borderstyle=="flat":
c = [min(bg[0]+8,255),min(bg[1]+8,255),min(bg[2]+8,255)]
elif self.borderstyle=="gradient":
c = h
elif self.borderstyle=="oldshadow":
c = h
elif self.borderstyle=="material":
c = s
self.vlist_cross.colors = 6*c
# Convenience variables
sx,sy = self.widget.size
x,y = self.widget.pos
bx,by = self.border
v1 = x+bx, y+(sy-by*2)/2+by
v2 = x+sx/2, y+(sy-by*2)/4+by
v3 = v6
v4 = x+sx, y+sy
v5 = x+sx/2, y+by
v6 = x+bx, y+(sy-by*2)/4+by
self.vlist_cross.vertices = v2+v1+v6+v5+v4+v3"""
# TODO: add better visual indicator
v1 = x+bx*1.5, y+sy-by*1.5
v2 = x+sx-bx*1.5, y+sy-by*1.5
v3 = x+bx*1.5, y+by*1.5
v4 = x+sx-bx*1.5, y+by*1.5
self.vlist_check.colors = self.checkcolor*4 if self.widget.pressed else i*4
self.vlist_check.vertices = v3+v4+v2+v1 |
def redraw_label(self):
"""
Re-calculates the position of the Label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
self._label.anchor_x = "left"
self._label.x = x+sx/2.+sx
self._label.y = y+sy/2.+sy*.15
self._label._update() |
def add(self,keybind,kbname,handler,mod=True):
"""
Adds a keybind to the internal registry.
Keybind names should be of the format ``namespace:category.subcategory.name``\ e.g. ``peng3d:actor.player.controls.forward`` for the forward key combo for the player actor.
:param str keybind: Keybind string, as described above
:param str kbname: Name of the keybind, may be used to later change the keybinding without re-registering
:param function handler: Function or any other callable called with the positional arguments ``(symbol,modifiers,release)`` if the keybind is pressed or released
:param int mod: If the keybind should respect modifiers
"""
keybind = keybind.lower()
if mod:
if keybind not in self.keybinds:
self.keybinds[keybind]=[]
self.keybinds[keybind].append(kbname)
else:
if keybind not in self.keybinds_nm:
self.keybinds_nm[keybind]=[]
self.keybinds_nm[keybind].append(kbname)
self.kbname[kbname]=handler
self.peng.sendEvent("peng3d:keybind.add",{"peng":self.peng,"keybind":keybind,"kbname":kbname,"handler":handler,"mod":mod}) |
def changeKeybind(self,kbname,combo):
"""
Changes a keybind of a specific keybindname.
:param str kbname: Same as kbname of :py:meth:`add()`
:param str combo: New key combination
"""
for key,value in self.keybinds.items():
if kbname in value:
del value[value.index(kbname)]
break
if combo not in self.keybinds:
self.keybinds[combo]=[]
self.keybinds[combo].append(kbname)
self.peng.sendEvent("peng3d.keybind.change",{"peng":self.peng,"kbname":kbname,"combo":combo}) |
def mod_is_held(self,modname,modifiers):
"""
Helper method to simplify checking if a modifier is held.
:param str modname: Name of the modifier, see :py:data:`MODNAME2MODIFIER`
:param int modifiers: Bitmask to check in, same as the modifiers argument of the on_key_press etc. handlers
"""
modifier = MODNAME2MODIFIER[modname.lower()]
return modifiers&modifier |
def handle_combo(self,combo,symbol,modifiers,release=False,mod=True):
"""
Handles a key combination and dispatches associated events.
First, all keybind handlers registered via :py:meth:`add` will be handled,
then the pyglet event :peng3d:pgevent:`on_key_combo` with params ``(combo,symbol,modifiers,release,mod)`` is sent to the :py:class:`Peng()` instance.
Also sends the events :peng3d:event:`peng3d:keybind.combo`\, :peng3d:event:`peng3d:keybind.combo.press` and :peng3d:event`peng3d:keybind.combo.release`\ .
:params str combo: Key combination pressed
:params int symbol: Key pressed, passed from the same argument within pyglet
:params int modifiers: Modifiers held while the key was pressed
:params bool release: If the combo was released
:params bool mod: If the combo was sent without mods
"""
if self.peng.cfg["controls.keybinds.debug"]:
print("combo: nm=%s %s"%(mod,combo))
if mod:
for kbname in self.keybinds.get(combo,[]):
self.kbname[kbname](symbol,modifiers,release)
else:
for kbname in self.keybinds_nm.get(combo,[]):
self.kbname[kbname](symbol,modifiers,release)
self.peng.sendPygletEvent("on_key_combo",(combo,symbol,modifiers,release,mod))
self.peng.sendEvent("peng3d:keybind.combo",{"peng":self.peng,"combo":combo,"symbol":symbol,"modifiers":modifiers,"release":release,"mod":mod})
if release:
self.peng.sendEvent("peng3d:keybind.combo.release",{"peng":self.peng,"combo":combo,"symbol":symbol,"modifiers":modifiers,"release":release,"mod":mod})
else:
self.peng.sendEvent("peng3d:keybind.combo.press",{"peng":self.peng,"combo":combo,"symbol":symbol,"modifiers":modifiers,"release":release,"mod":mod}) |
def registerEventHandlers(self):
"""
Registers needed keybinds and schedules the :py:meth:`update` Method.
You can control what keybinds are used via the :confval:`controls.controls.forward` etc. Configuration Values.
"""
# Forward
self.peng.keybinds.add(self.peng.cfg["controls.controls.forward"],"peng3d:actor.%s.player.controls.forward"%self.actor.uuid,self.on_fwd_down,False)
# Backward
self.peng.keybinds.add(self.peng.cfg["controls.controls.backward"],"peng3d:actor.%s.player.controls.backward"%self.actor.uuid,self.on_bwd_down,False)
# Strafe Left
self.peng.keybinds.add(self.peng.cfg["controls.controls.strafeleft"],"peng3d:actor.%s.player.controls.strafeleft"%self.actor.uuid,self.on_left_down,False)
# Strafe Right
self.peng.keybinds.add(self.peng.cfg["controls.controls.straferight"],"peng3d:actor.%s.player.controls.straferight"%self.actor.uuid,self.on_right_down,False)
pyglet.clock.schedule_interval(self.update,1.0/60) |
def get_motion_vector(self):
"""
Returns the movement vector according to held buttons and the rotation.
:return: 3-Tuple of ``(dx,dy,dz)``
:rtype: tuple
"""
if any(self.move):
x, y = self.actor._rot
strafe = math.degrees(math.atan2(*self.move))
y_angle = math.radians(y)
x_angle = math.radians(x + strafe)
dy = 0.0
dx = math.cos(x_angle)
dz = math.sin(x_angle)
else:
dy = 0.0
dx = 0.0
dz = 0.0
return (dx, dy, dz) |
def registerEventHandlers(self):
"""
Registers the motion and drag handlers.
Note that because of the way pyglet treats mouse dragging, there is also an handler registered to the on_mouse_drag event.
"""
self.world.registerEventHandler("on_mouse_motion",self.on_mouse_motion)
self.world.registerEventHandler("on_mouse_drag",self.on_mouse_drag) |
def registerEventHandlers(self):
"""
Registers the up and down handlers.
Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps.
"""
# Crouch/fly down
self.peng.keybinds.add(self.peng.cfg["controls.controls.crouch"],"peng3d:actor.%s.player.controls.crouch"%self.actor.uuid,self.on_crouch_down,False)
# Jump/fly up
self.peng.keybinds.add(self.peng.cfg["controls.controls.jump"],"peng3d:actor.%s.player.controls.jump"%self.actor.uuid,self.on_jump_down,False)
pyglet.clock.schedule_interval(self.update,1.0/60) |
def update(self,dt):
"""
Should be called regularly to move the actor.
This method does nothing if the :py:attr:`enabled` property is set to False.
This method is called automatically and should not be called manually.
"""
if not self.enabled:
return
dy = self.speed * dt * self.move
x,y,z = self.actor._pos
newpos = x,dy+y,z
self.actor.pos = newpos |
def update(self,dt):
"""
Internal method used for moving the player.
:param float dt: Time delta since the last call to this method
"""
speed = self.movespeed
d = dt * speed # distance covered this tick.
dx, dy, dz = self.get_motion_vector()
# New position in space, before accounting for gravity.
dx, dy, dz = dx * d, dy * d, dz * d
#dy+=self.vert*VERT_SPEED
x,y,z = self._pos
newpos = dx+x, dy+y, dz+z
self.pos = newpos |
def add_widgets(self,**kwargs):
"""
Called by the initializer to add all widgets.
Widgets are discovered by searching through the :py:attr:`WIDGETS` class attribute.
If a key in :py:attr:`WIDGETS` is also found in the keyword arguments and
not none, the function with the name given in the value of the key will
be called with its only argument being the value of the keyword argument.
For more complex usage scenarios, it is also possible to override this method
in a subclass, but the original method should always be called to ensure
compatibility with classes relying on this feature.
"""
for name,fname in self.WIDGETS.items():
if name in kwargs and kwargs[name] is not None:
assert hasattr(self,fname)
assert callable(getattr(self,fname))
getattr(self,fname)(kwargs[name]) |
def add_label_main(self,label_main):
"""
Adds the main label of the dialog.
This widget can be triggered by setting the label ``label_main`` to a string.
This widget will be centered on the screen.
"""
# Main Label
self.wlabel_main = text.Label("label_main",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw/2,sh/2-bh/2),
size=[0,0],
label=label_main,
#multiline=True, # TODO: implement multine dialog
)
self.wlabel_main.size = lambda sw,sh: (sw,self.wlabel_main._label.font_size)
self.addWidget(self.wlabel_main) |
def add_btn_ok(self,label_ok):
"""
Adds an OK button to allow the user to exit the dialog.
This widget can be triggered by setting the label ``label_ok`` to a string.
This widget will be mostly centered on the screen, but below the main label
by the double of its height.
"""
# OK Button
self.wbtn_ok = button.Button("btn_ok",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw/2,sh/2-bh/2-bh*2),
size=[0,0],
label=label_ok,
borderstyle=self.borderstyle
)
self.wbtn_ok.size = lambda sw,sh: (self.wbtn_ok._label.font_size*8,self.wbtn_ok._label.font_size*2)
self.addWidget(self.wbtn_ok)
def f():
self.doAction("click_ok")
self.exitDialog()
self.wbtn_ok.addAction("click",f) |
def exitDialog(self):
"""
Helper method that exits the dialog.
This method will cause the previously active submenu to activate.
"""
if self.prev_submenu is not None:
# change back to the previous submenu
# could in theory form a stack if one dialog opens another
self.menu.changeSubMenu(self.prev_submenu)
self.prev_submenu = None |
def add_btn_confirm(self,label_confirm):
"""
Adds a confirm button to let the user confirm whatever action they were presented with.
This widget can be triggered by setting the label ``label_confirm`` to a string.
This widget will be positioned slightly below the main label and to the left
of the cancel button.
"""
# Confirm Button
self.wbtn_confirm = button.Button("btn_confirm",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw-4,sh/2-bh/2-bh*2),
size=[0,0],
label=label_confirm,
borderstyle=self.borderstyle
)
self.wbtn_confirm.size = lambda sw,sh: (self.wbtn_confirm._label.font_size*8,self.wbtn_confirm._label.font_size*2)
self.addWidget(self.wbtn_confirm)
def f():
self.doAction("confirm")
self.exitDialog()
self.wbtn_confirm.addAction("click",f) |
def add_btn_cancel(self,label_cancel):
"""
Adds a cancel button to let the user cancel whatever choice they were given.
This widget can be triggered by setting the label ``label_cancel`` to a string.
This widget will be positioned slightly below the main label and to the right
of the confirm button.
"""
# Cancel Button
self.wbtn_cancel = button.Button("btn_cancel",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2+4,sh/2-bh/2-bh*2),
size=[0,0],
label=label_cancel,
borderstyle=self.borderstyle
)
self.wbtn_cancel.size = lambda sw,sh: (self.wbtn_cancel._label.font_size*8,self.wbtn_cancel._label.font_size*2)
self.addWidget(self.wbtn_cancel)
def f():
self.doAction("cancel")
self.exitDialog()
self.wbtn_cancel.addAction("click",f) |
def update_progressbar(self):
"""
Updates the progressbar by re-calculating the label.
It is not required to manually call this method since setting any of the
properties of this class will automatically trigger a re-calculation.
"""
n,nmin,nmax = self.wprogressbar.n,self.wprogressbar.nmin,self.wprogressbar.nmax
if (nmax-nmin)==0:
percent = 0 # prevents ZeroDivisionError
else:
percent = max(min((n-nmin)/(nmax-nmin),1.),0.)*100
dat = {"value":round(n,4),"n":round(n,4),"nmin":round(nmin,4),"nmax":round(nmax,4),"percent":round(percent,4),"p":round(percent,4)}
txt = self._label_progressbar.format(**dat)
self.wprogresslabel.label = txt |
def add_progressbar(self,label_progressbar):
"""
Adds a progressbar and label displaying the progress within a certain task.
This widget can be triggered by setting the label ``label_progressbar`` to
a string.
The progressbar will be displayed centered and below the main label.
The progress label will be displayed within the progressbar.
The label of the progressbar may be a string containing formatting codes
which will be resolved via the ``format()`` method.
Currently, there are six keys available:
``n`` and ``value`` are the current progress rounded to 4 decimal places.
``nmin`` is the minimum progress value rounded to 4 decimal places.
``nmax`` is the maximum progress value rounded to 4 decimal places.
``p`` and ``percent`` are the percentage value that the progressbar is completed
rounded to 4 decimal places.
By default, the progressbar label will be ``{percent}%`` displaying the percentage
the progressbar is complete.
"""
# Progressbar
self.wprogressbar = slider.AdvancedProgressbar("progressbar",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw/2,self.wlabel_main.pos[1]-bh*1.5),
size=[0,0],
#label=label_progressbar # TODO: add label
borderstyle=self.borderstyle
)
self.addWidget(self.wprogressbar)
# Progress Label
self.wprogresslabel = text.Label("progresslabel",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw/2,self.wprogressbar.pos[1]+8),
size=[0,0],
label="", # set by update_progressbar()
)
self.wprogresslabel.size = lambda sw,sh: (sw,self.wprogresslabel._label.font_size)
self.addWidget(self.wprogresslabel)
self.wprogressbar.size = lambda sw,sh: (sw*0.8,self.wprogresslabel._label.font_size+10)
self._label_progressbar = label_progressbar
if getattr(label_progressbar,"_dynamic",False):
def f():
self.label_progressbar = str(label_progressbar)
self.peng.i18n.addAction("setlang",f)
self.wprogressbar.addAction("progresschange",self.update_progressbar)
self.update_progressbar() |
def createWindow(self,cls=None,caption_t=None,*args,**kwargs):
"""
createWindow(cls=window.PengWindow, *args, **kwargs)
Creates a new window using the supplied ``cls``\ .
If ``cls`` is not given, :py:class:`peng3d.window.PengWindow()` will be used.
Any other positional or keyword arguments are passed to the class constructor.
Note that this method currently does not support using multiple windows.
.. todo::
Implement having multiple windows.
"""
if cls is None:
from . import window
cls = window.PengWindow
if self.window is not None:
raise RuntimeError("Window already created!")
self.sendEvent("peng3d:window.create.pre",{"peng":self,"cls":cls})
if caption_t is not None:
kwargs["caption"] = "Peng3d Application"
self.window = cls(self,*args,**kwargs)
self.sendEvent("peng3d:window.create.post",{"peng":self,"window":self.window})
if self.cfg["rsrc.enable"] and self.resourceMgr is None:
self.sendEvent("peng3d:rsrc.init.pre",{"peng":self,"basepath":self.cfg["rsrc.basepath"]})
self.resourceMgr = resource.ResourceManager(self,self.cfg["rsrc.basepath"])
self.rsrcMgr = self.resourceMgr
self.sendEvent("peng3d:rsrc.init.post",{"peng":self,"rsrcMgr":self.resourceMgr})
if self.cfg["i18n.enable"] and self.i18n is None:
self.sendEvent("peng3d:i18n.init.pre",{"peng":self})
self.i18n = i18n.TranslationManager(self)
self._t = self.i18n.t
self._tl = self.i18n.tl
self.sendEvent("peng3d:i18n.init.post",{"peng":self,"i18n":self.i18n})
if caption_t is not None:
self.window.set_caption(self.t(caption_t))
def f():
self.window.set_caption(self.t(caption_t))
self.i18n.addAction("setlang",f)
return self.window |
def run(self,evloop=None):
"""
Runs the application main loop.
This method is blocking and needs to be called from the main thread to avoid OpenGL bugs that can occur.
``evloop`` may optionally be a subclass of :py:class:`pyglet.app.base.EventLoop` to replace the default event loop.
"""
self.sendEvent("peng3d:peng.run",{"peng":self,"window":self.window,"evloop":evloop})
self.window.run(evloop)
self.sendEvent("peng3d:peng.exit",{"peng":self}) |
def sendPygletEvent(self,event_type,args,window=None):
"""
Handles a pyglet event.
This method is called by :py:meth:`PengWindow.dispatch_event()` and handles all events.
See :py:meth:`registerEventHandler()` for how to listen to these events.
This method should be used to send pyglet events.
For new code, it is recommended to use :py:meth:`sendEvent()` instead.
For "tunneling" pyglet events, use event names of the format ``pyglet:<event>``
and for the data use ``{"args":<args as list>,"window":<window object or none>,"src":<event source>,"event_type":<event type>}``
Note that you should send pyglet events only via this method, the above event will be sent automatically.
Do not use this method to send custom events, use :py:meth:`sendEvent` instead.
"""
args = list(args)
self.sendEvent("pyglet:%s"%event_type,{"peng":self,"args":args,"window":window,"src":self,"event_type":event_type})
self.sendEvent("peng3d:pyglet",{"peng":self,"args":args,"window":window,"src":self,"event_type":event_type})
if event_type not in ["on_draw","on_mouse_motion"] and self.cfg["debug.events.dump"]:
print("Event %s with args %s"%(event_type,args))
if event_type in self.pygletEventHandlers:
for whandler in self.pygletEventHandlers[event_type]:
# This allows for proper collection of deleted handler methods by using weak references
handler = whandler()
if handler is None:
del self.pygletEventHandlers[event_type][self.pygletEventHandlers[event_type].index(whandler)]
handler(*args) |
def addPygletListener(self,event_type,handler):
"""
Registers an event handler.
The specified callable handler will be called every time an event with the same ``event_type`` is encountered.
All event arguments are passed as positional arguments.
This method should be used to listen for pyglet events.
For new code, it is recommended to use :py:meth:`addEventListener()` instead.
See :py:meth:`handleEvent()` for information about tunneled pyglet events.
For custom events, use :py:meth:`addEventListener()` instead.
"""
if self.cfg["debug.events.register"]:
print("Registered Event: %s Handler: %s"%(event_type,handler))
if event_type not in self.pygletEventHandlers:
self.pygletEventHandlers[event_type]=[]
# Only a weak reference is kept
if inspect.ismethod(handler):
handler = weakref.WeakMethod(handler)
else:
handler = weakref.ref(handler)
self.pygletEventHandlers[event_type].append(handler) |
def sendEvent(self,event,data=None):
"""
Sends an event with attached data.
``event`` should be a string of format ``<namespace>:<category1>.<subcategory2>.<name>``\ .
There may be an arbitrary amount of subcategories. Also note that this
format is not strictly enforced, but rather recommended by convention.
``data`` may be any Python Object, but it usually is a dictionary containing relevant parameters.
For example, most built-in events use a dictionary containing at least the ``peng`` key set to an instance of this class.
If there are no handlers for the event, a corresponding message will be printed to the log file.
To prevent spam, the maximum amount of ignored messages can be configured via :confval:`events.maxignore` and defaults to 3.
If the config value :confval:`debug.events.dumpfile` is a file path, the event type will be added to an internal list and be saved to the given file during program exit.
"""
if self.cfg["debug.events.dumpfile"]!="" and event not in self.event_list:
self.event_list.add(event)
if event not in self.eventHandlers:
if event not in self.events_ignored or self.events_ignored[event]<=self.cfg["events.maxignore"]: # Prevents spamming logfile with ignored event messages
# TODO: write to logfile
# Needs a logging module first...
self.events_ignored[event] = self.events_ignored.get(event,0)+1
return
for handler in self.eventHandlers[event]:
f = handler[0]
try:
f(event,data)
except Exception:
if not handler[1]:
raise
else:
# TODO: write to logfile
if self.cfg["events.removeonerror"]:
self.delEventListener(event,f) |
def addEventListener(self,event,func,raiseErrors=False):
"""
Adds a handler to the given event.
A event may have an arbitrary amount of handlers, though assigning too
many handlers may slow down event processing.
For the format of ``event``\ , see :py:meth:`sendEvent()`\ .
``func`` is the handler which will be executed with two arguments, ``event_type`` and ``data``\ , as supplied to :py:meth:`sendEvent()`\ .
If ``raiseErrors`` is True, exceptions caused by the handler will be re-raised.
Defaults to ``False``\ .
"""
if not isinstance(event,str):
raise TypeError("Event types must always be strings")
if event not in self.eventHandlers:
self.eventHandlers[event]=[]
self.eventHandlers[event].append([func,raiseErrors]) |
def delEventListener(self,event,func):
"""
Removes the given handler from the given event.
If the event does not exist, a :py:exc:`NameError` is thrown.
If the handler has not been registered previously, also a :py:exc:`NameError` will be thrown.
"""
if event not in self.eventHandlers:
raise NameError("No handlers exist for event %s"%event)
if [func,True] in self.eventHandlers[event]:
del self.eventHandlers[event][self.eventHandlers[event].index(func)]
elif [func,False] in self.eventHandler[event]:
del self.eventHandlers[event][self.eventHandlers[event].index(func)]
else:
raise NameError("This handler is not registered for event %s"%event)
if self.eventHandlers[event] == []:
del self.eventHandlers[event] |
def setLang(self,lang):
"""
Sets the default language for all domains.
For recommendations regarding the format of the language code, see
:py:class:`TranslationManager`\ .
Note that the ``lang`` parameter of both :py:meth:`translate()` and
:py:meth:`translate_lazy()` will override this setting.
Also note that the code won't be checked for existence or plausibility.
This may cause the fallback strings to be displayed instead if the language
does not exist.
Calling this method will cause the ``setlang`` action and the
:peng3d:event`peng3d:i18n.set_lang` event to be triggered. Note that both
action and event will be triggered even if the language did not actually change.
This method also automatically updates the :confval:`i18n.lang` config value.
"""
self.lang = lang
self.peng.cfg["i18n.lang"] = lang
if lang not in self.cache:
self.cache[lang]={}
self.doAction("setlang")
self.peng.sendEvent("peng3d:i18n.set_lang",{"lang":self.lang,"i18n":self}) |
def discoverLangs(self,domain="*"):
"""
Generates a list of languages based on files found on disk.
The optional ``domain`` argument may specify a domain to use when checking
for files. By default, all domains are checked.
This internally uses the :py:mod:`glob` built-in module and the
:confval:`i18n.lang.format` config option to find suitable filenames.
It then applies the regex in :confval:`i18n.discover_regex` to extract the
language code.
"""
rsrc = self.peng.cfg["i18n.lang.format"].format(domain=domain,lang="*")
pattern = self.peng.rsrcMgr.resourceNameToPath(rsrc,self.peng.cfg["i18n.lang.ext"])
files = glob.iglob(pattern)
langs = set()
r = re.compile(self.peng.cfg["i18n.discover_regex"])
for f in files:
m = r.fullmatch(f)
if m is not None:
langs.add(m.group("lang"))
return list(langs) |
def addCamera(self,camera):
"""
Add the camera to the internal registry.
Each camera name must be unique, or else only the most recent version will be used. This behavior should not be relied on because some objects may cache objects.
Additionally, only instances of :py:class:`Camera() <peng3d.camera.Camera>` may be used, everything else raises a :py:exc:`TypeError`\ .
"""
if not isinstance(camera,Camera):
raise TypeError("camera is not of type Camera!")
self.cameras[camera.name]=camera |
def addView(self,view):
"""
Adds the supplied :py:class:`WorldView()` object to the internal registry.
The same restrictions as for cameras apply, e.g. no duplicate names.
Additionally, only instances of :py:class:`WorldView()` may be used, everything else raises a :py:exc:`TypeError`\ .
"""
if not isinstance(view,WorldView):
raise TypeError("view is not of type WorldView!")
self.views[view.name]=view |
def getView(self,name):
"""
Returns the view with name ``name``\ .
Raises a :py:exc:`ValueError` if the view does not exist.
"""
if name not in self.views:
raise ValueError("Unknown world view")
return self.views[name] |
def render3d(self,view=None):
"""
Renders the world in 3d-mode.
If you want to render custom terrain, you may override this method. Be careful that you still call the original method or else actors may not be rendered.
"""
for actor in self.actors.values():
actor.render(view) |
def render3d(self,view=None):
"""
Renders the world.
"""
super(StaticWorld,self).render3d(view)
self.batch3d.draw() |
def setActiveCamera(self,name):
"""
Sets the active camera.
This method also calls the :py:meth:`Camera.on_activate() <peng3d.camera.Camera.on_activate>` event handler if the camera is not already active.
"""
if name == self.activeCamera:
return # Cam is already active
if name not in self.world.cameras:
raise ValueError("Unknown camera name")
old = self.activeCamera
self.activeCamera = name
self.cam.on_activate(old) |
def on_menu_enter(self,old):
"""
Fake event handler, same as :py:meth:`WorldView.on_menu_enter()` but forces mouse exclusivity.
"""
super(WorldViewMouseRotatable,self).on_menu_enter(old)
self.world.peng.window.toggle_exclusivity(True) |
def on_menu_exit(self,new):
"""
Fake event handler, same as :py:meth:`WorldView.on_menu_exit()` but force-disables mouse exclusivity.
"""
super(WorldViewMouseRotatable,self).on_menu_exit(new)
self.world.peng.window.toggle_exclusivity(False) |
def on_key_press(self,symbol,modifiers):
"""
Keyboard event handler handling only the escape key.
If an escape key press is detected, mouse exclusivity is toggled via :py:meth:`PengWindow.toggle_exclusivity()`\ .
"""
if symbol == key.ESCAPE:
self.world.peng.window.toggle_exclusivity()
return pyglet.event.EVENT_HANDLED |
def on_mouse_motion(self, x, y, dx, dy):
"""
Handles mouse motion and rotates the attached camera accordingly.
For more information about how to customize mouse movement, see the class documentation here :py:class:`WorldViewMouseRotatable()`\ .
"""
if not self.world.peng.window.exclusive:
return
m = self.world.peng.cfg["controls.mouse.sensitivity"]
x, y = self.rot
x, y = x + dx * m, y + dy * m
y = max(-90, min(90, y))
x %= 360
newrot = (x,y)
self.rot= newrot |
def step(self, step_name):
"""Start a new step. returns a context manager which allows you to
report an error"""
@contextmanager
def step_context(step_name):
if self.event_receiver.current_case is not None:
raise Exception('cannot open a step within a step')
self.event_receiver.begin_case(step_name, self.now_seconds(), self.name)
try:
yield self.event_receiver
except:
etype, evalue, tb = sys.exc_info()
self.event_receiver.error('%r' % [etype, evalue, tb])
raise
finally:
self.event_receiver.end_case(step_name, self.now_seconds())
return step_context(step_name) |
def resourceNameToPath(self,name,ext=""):
"""
Converts the given resource name to a file path.
A resource path is of the format ``<app>:<cat1>.<cat2>.<name>`` where cat1 and cat2 can be repeated as often as desired.
``ext`` is the file extension to use, e.g. ``.png`` or similar.
As an example, the resource name ``peng3d:some.category.foo`` with the extension ``.png`` results in the path ``<basepath>/assets/peng3d/some/category/foo.png``\ .
This resource naming scheme is used by most other methods of this class.
Note that it is currently not possible to define multiple base paths to search through.
"""
nsplit = name.split(":")[1].split(".")
return os.path.join(self.basepath,"assets",name.split(":")[0],*nsplit)+ext |
def resourceExists(self,name,ext=""):
"""
Returns whether or not the resource with the given name and extension exists.
This must not mean that the resource is meaningful, it simply signals that the file exists.
"""
return os.path.exists(self.resourceNameToPath(name,ext)) |
def addCategory(self,name):
"""
Adds a new texture category with the given name.
If the category already exists, it will be overridden.
"""
self.categories[name]={}
self.categoriesTexCache[name]={}
self.categoriesTexBin[name]=pyglet.image.atlas.TextureBin(self.texsize,self.texsize)
self.peng.sendEvent("peng3d:rsrc.category.add",{"peng":self.peng,"category":name}) |
def getTex(self,name,category):
"""
Gets the texture associated with the given name and category.
``category`` must have been created using :py:meth:`addCategory()` before.
If it was loaded previously, a cached version will be returned.
If it was not loaded, it will be loaded and inserted into the cache.
See :py:meth:`loadTex()` for more information.
"""
if category not in self.categoriesTexCache:
return self.getMissingTex(category)
if name not in self.categoriesTexCache[category]:
self.loadTex(name,category)
return self.categoriesTexCache[category][name] |
def loadTex(self,name,category):
"""
Loads the texture of the given name and category.
All textures currently must be PNG files, although support for more formats may be added soon.
If the texture cannot be found, a missing texture will instead be returned. See :py:meth:`getMissingTexture()` for more information.
Currently, all texture mipmaps will be generated and the filters will be set to
:py:const:`GL_NEAREST` for the magnification filter and :py:const:`GL_NEAREST_MIPMAP_LINEAR` for the minification filter.
This results in a pixelated texture and not a blurry one.
"""
try:
img = pyglet.image.load(self.resourceNameToPath(name,".png"))
except FileNotFoundError:
img = self.getMissingTexture()
texreg = self.categoriesTexBin[category].add(img)
#texreg = texreg.get_transform(True,True) # Mirrors the image due to how pyglets coordinate system works
# Strange behavior, sometimes needed and sometimes not
self.categories[category][name]=texreg
target = texreg.target
texid = texreg.id
texcoords = texreg.tex_coords
# Prevents texture bleeding with texture sizes that are powers of 2, else weird lines may appear at certain angles.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)
glGenerateMipmap(GL_TEXTURE_2D)
out = target,texid,texcoords
self.categoriesTexCache[category][name]=out
self.peng.sendEvent("peng3d:rsrc.tex.load",{"peng":self.peng,"name":name,"category":category})
return out |
def getMissingTexture(self):
"""
Returns a texture to be used as a placeholder for missing textures.
A default missing texture file is provided in the assets folder of the source distribution.
It consists of a simple checkerboard pattern of purple and black, this image may be copied to any project using peng3d for similar behavior.
If this texture cannot be found, a pattern is created in-memory, simply a solid square of purple.
This texture will also be cached separately from other textures.
"""
if self.missingTexture is None:
if self.resourceExists(self.missingtexturename,".png"):
self.missingTexture = pyglet.image.load(self.resourceNameToPath(self.missingtexturename,".png"))
return self.missingTexture
else: # Falls back to create pattern in-memory
self.missingTexture = pyglet.image.create(1,1,pyglet.image.SolidColorImagePattern([255,0,255,255]))
return self.missingTexture
else:
return self.missingTexture |
def addFromTex(self,name,img,category):
"""
Adds a new texture from the given image.
``img`` may be any object that supports Pyglet-style copying in form of the ``blit_to_texture()`` method.
This can be used to add textures that come from non-file sources, e.g. Render-to-texture.
"""
texreg = self.categoriesTexBin[category].add(img)
#texreg = texreg.get_transform(True,True) # Mirrors the image due to how pyglets coordinate system works
# Strange behaviour, sometimes needed and sometimes not
self.categories[category][name]=texreg
target = texreg.target
texid = texreg.id
texcoords = texreg.tex_coords
# Prevents texture bleeding with texture sizes that are powers of 2, else weird lines may appear at certain angles.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)
glGenerateMipmap(GL_TEXTURE_2D)
out = target,texid,texcoords
self.categoriesTexCache[category][name]=out
return out |
def getModel(self,name):
"""
Gets the model object by the given name.
If it was loaded previously, a cached version will be returned.
If it was not loaded, it will be loaded and inserted into the cache.
"""
if name in self.modelobjcache:
return self.modelobjcache[name]
return self.loadModel(name) |
def loadModel(self,name):
"""
Loads the model of the given name.
The model will also be inserted into the cache.
"""
m = model.Model(self.peng,self,name)
self.modelobjcache[name]=m
self.peng.sendEvent("peng3d:rsrc.model.load",{"peng":self.peng,"name":name})
return m |
def getModelData(self,name):
"""
Gets the model data associated with the given name.
If it was loaded, a cached copy will be returned.
It it was not loaded, it will be loaded and cached.
"""
if name in self.modelcache:
return self.modelcache[name]
return self.loadModelData(name) |
def loadModelData(self,name):
"""
Loads the model data of the given name.
The model file must always be a .json file.
"""
path = self.resourceNameToPath(name,".json")
try:
data = json.load(open(path,"r"))
except Exception:
# Temporary
print("Exception during model load: ")
import traceback;traceback.print_exc()
return {}# will probably cause other exceptions later on, TODO
out = {}
if data.get("version",1)==1:
# Currently only one version, basic future-proofing
# This version should get incremented with breaking changes to the structure
# Materials
out["materials"]={}
for name,matdata in data.get("materials",{}).items():
m = model.Material(self,name,matdata)
out["materials"][name]=m
out["default_material"]=out["materials"][data.get("default_material",list(out["materials"].keys())[0])]
# Bones
out["bones"]={"__root__":model.RootBone(self,"__root__",{"start_rot":[0,0],"length":0})}
for name,bonedata in data.get("bones",{}).items():
b = model.Bone(self,name,bonedata)
out["bones"][name]=b
for name,bone in out["bones"].items():
if name == "__root__":
continue
bone.setParent(out["bones"][bone.bonedata["parent"]])
# Regions
out["regions"]={}
for name,regdata in data.get("regions",{}).items():
r = model.Region(self,name,regdata)
r.material = out["materials"][regdata.get("material",out["default_material"])]
r.bone = out["bones"][regdata.get("bone","__root__")]
out["bones"][regdata.get("bone","__root__")].addRegion(r)
out["regions"][name]=r
# Animations
out["animations"]={}
out["animations"]["static"]=model.Animation(self,"static",{"type":"static","bones":{}})
for name,anidata in data.get("animations",{}).items():
a = model.Animation(self,name,anidata)
a.setBones(out["bones"])
out["animations"][name]=a
out["default_animation"]=out["animations"][data.get("default_animation",out["animations"]["static"])]
else:
raise ValueError("Unknown version %s of model '%s'"%(data.get("version",1),name))
self.modelcache[name]=out
return out |
def setBackground(self,bg):
"""
Sets the background of the Container.
Similar to :py:meth:`peng3d.gui.SubMenu.setBackground()`\ , but only effects the region covered by the Container.
"""
self.bg = bg
if isinstance(bg,list) or isinstance(bg,tuple):
if len(bg)==3 and isinstance(bg,list):
bg.append(255)
self.bg_vlist.colors = bg*4
elif bg in ["flat","gradient","oldshadow","material"]:
self.bg = ContainerButtonBackground(self,borderstyle=bg,batch=self.batch2d)
self.redraw() |
def addWidget(self,widget):
"""
Adds a widget to this container.
Note that trying to add the Container to itself will be ignored.
"""
if self is widget: # Prevents being able to add the container to itself, causing a recursion loop on redraw
return
self.widgets[widget.name]=widget |
def draw(self):
"""
Draws the submenu and its background.
Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings.
"""
if not self.visible:
# Simple visibility check, has to be tested to see if it works properly
return
if not isinstance(self.submenu,Container):
glEnable(GL_SCISSOR_TEST)
glScissor(*self.pos+self.size)
SubMenu.draw(self)
if not isinstance(self.submenu,Container):
glDisable(GL_SCISSOR_TEST) |
def on_redraw(self):
"""
Redraws the background and any child widgets.
"""
x,y = self.pos
sx,sy = self.size
self.bg_vlist.vertices = [x,y, x+sx,y, x+sx,y+sy, x,y+sy]
self.stencil_vlist.vertices = [x,y, x+sx,y, x+sx,y+sy, x,y+sy]
if isinstance(self.bg,Background):
if not self.bg.initialized:
self.bg.init_bg()
self.bg.initialized=True
self.bg.redraw_bg() |
def on_redraw(self):
"""
Redraws the background and contents, including scrollbar.
This method will also check the scrollbar for any movement and will be automatically called on movement of the slider.
"""
n = self._scrollbar.n
self.offset_y = -n # Causes the content to move in the opposite direction of the slider
# Size of scrollbar
sx=24 # Currently constant, TODO: add dynamic sx of scrollbar
sy=self.size[1]
# Pos of scrollbar
x=self.size[0]-sx
y=0 # Currently constant, TODO: add dynamic y-pos of scrollbar
# Dynamic pos/size may be added via align/lambda/etc.
# Note that the values are written to the _* variant of the attribute to avoid 3 uneccessary redraws
self._scrollbar._size = sx,sy
self._scrollbar._pos = x,y
self._scrollbar._nmax = self.content_height
super(ScrollableContainer,self).on_redraw() |
def mouse_aabb(mpos,size,pos):
"""
AABB Collision checker that can be used for most axis-aligned collisions.
Intended for use in widgets to check if the mouse is within the bounds of a particular widget.
"""
return pos[0]<=mpos[0]<=pos[0]+size[0] and pos[1]<=mpos[1]<=pos[1]+size[1] |
def addCategory(self,name,nmin=0,n=0,nmax=100):
"""
Adds a category with the given name.
If the category already exists, a :py:exc:`KeyError` will be thrown. Use
:py:meth:`updateCategory()` instead if you want to update a category.
"""
assert isinstance(name,basestring) # py2 compat is done at the top
if name in self.categories:
raise KeyError("Category with name '%s' already exists"%name)
self.categories[name]=[nmin,n,nmax]
self.redraw() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.