code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
#
# Comment tests
#
import unittest
import PloneboardTestCase
from Products.Ploneboard.transforms.url_to_hyperlink import URLToHyperlink
class MockTransformData:
def setData(self, value):
self.data=value
class TestUrlTransform(PloneboardTestCase.PloneboardTestCase):
def runTest(self, testdata):
transform = URLToHyperlink()
data=MockTransformData()
for (input, answer) in testdata:
transform.convert(input, data)
self.failUnlessEqual(data.data, answer)
def testPlainText(self):
testdata = [
("just a simple string", "just a simple string"),
("htXtp:bla invalid scheme", "htXtp:bla invalid scheme"),
]
self.runTest(testdata)
def testPlainUrls(self):
testdata = [
("http://simple.url/", '<a href="http://simple.url/">http://simple.url/</a>'),
# XXX are URI schemes really case insensitive?
("HTtp://simple.url/", '<a href="HTtp://simple.url/">HTtp://simple.url/</a>'),
("https://simple.url/", '<a href="https://simple.url/">https://simple.url/</a>'),
("telnet://simple.url/", '<a href="telnet://simple.url/">telnet://simple.url/</a>'),
]
self.runTest(testdata)
def testUrlElements(self):
testdata = [
("<telnet://simple.url/>", '<telnet://simple.url/>'),
("< telnet://simple.url/>", '< telnet://simple.url/>'),
("<telnet://simple.url />", '<telnet://simple.url />'),
("http://change.this/ <telnet://simple.url/>", '<a href="http://change.this/">http://change.this/</a> <telnet://simple.url/>'),
]
self.runTest(testdata)
def testEmail(self):
testdata = [
("test@example.com", '<a href="mailto:test@example.com">test@example.com</a>'),
("<test@example.com>", "<test@example.com>"),
]
self.runTest(testdata)
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestUrlTransform))
return suite
| [
[
1,
0,
0.0806,
0.0161,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0968,
0.0161,
0,
0.66,
0.2,
964,
0,
1,
0,
0,
964,
0,
0
],
[
1,
0,
0.1129,
0.0161,
0,
0.66,... | [
"import unittest",
"import PloneboardTestCase",
"from Products.Ploneboard.transforms.url_to_hyperlink import URLToHyperlink",
"class MockTransformData:\n def setData(self, value):\n self.data=value",
" def setData(self, value):\n self.data=value",
" self.data=value",
"class Te... |
#
# Ploneboard tests
#
import unittest
from zExceptions import Unauthorized
from zope.interface.verify import verifyClass, verifyObject
from Products.Ploneboard.tests import PloneboardTestCase
from Products.Ploneboard.interfaces import IPloneboard, IForum
from Products.Ploneboard.content.Ploneboard import Ploneboard
from Products.CMFCore.utils import getToolByName
# Catch errors in Install
from Products.Ploneboard.Extensions import Install
from Products.CMFPlone.utils import _createObjectByType
class TestPloneboardBasics(PloneboardTestCase.PloneboardTestCase):
"""Test the basics, like creation"""
def testPloneboardCreation(self):
"""Try creating and deleting a board"""
board_id = 'board'
board = _createObjectByType('Ploneboard', self.portal, board_id)
self.failIfEqual(board, None)
self.failUnless(board_id in self.portal.objectIds())
self.portal._delObject(board_id)
self.failIf(board_id in self.portal.objectIds())
class TestPloneboardInterface(PloneboardTestCase.PloneboardTestCase):
"""Test if it fulfills the interface"""
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
def testInterfaceVerification(self):
self.failUnless(verifyClass(IPloneboard, Ploneboard))
def testInterfaceConformance(self):
self.failUnless(IPloneboard.providedBy(self.board))
self.failUnless(verifyObject(IPloneboard, self.board))
def testAddForum(self):
"""Create new folder in home directory & check its basic
properties and behaviour"""
board = self.board
forum_id = 'forum'
board.addForum(forum_id, 'title', 'description')
self.failUnless(forum_id in board.objectIds())
forum = getattr(board, forum_id)
self.failUnless(IForum.providedBy(forum))
def testRemoveForum(self):
board = self.board
forum_id = 'forum'
board.addForum(forum_id, 'title', 'description')
board.removeForum(forum_id)
self.failIf(forum_id in board.objectIds())
def testGetForum(self):
board = self.board
forum_id = 'forum'
board.addForum(forum_id, 'title', 'description')
forum = board.getForum(forum_id)
self.failUnless(IForum.providedBy(forum))
def testGetForumIds(self):
board = self.board
forum_ids = ['forum1', 'forum2']
for forum_id in forum_ids:
board.addForum(forum_id, 'title', 'description')
self.failUnlessEqual(forum_ids, board.getForumIds())
def testGetForums(self):
board = self.board
forum_ids = ['forum1', 'forum2']
for forum_id in forum_ids:
board.addForum(forum_id, 'title', 'description')
self.failUnlessEqual(
set([board.getForum(forum_id) for forum_id in forum_ids]),
set(board.getForums()))
def testSearchComments(self):
pass
class TestPloneboardWithoutContainment(PloneboardTestCase.PloneboardTestCase):
"""Test a single board used more as a topic, with forums in folders"""
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
def testGetForumsOutsideBoard(self):
forum1 = _createObjectByType('PloneboardForum', self.folder, 'forum1')
forum2 = _createObjectByType('PloneboardForum', self.folder, 'forum2')
forums = self.board.getForums(sitewide=True)
self.failUnless(forum1 in forums)
self.failUnless(forum2 in forums)
class TestPloneboardRSSFeed(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board',
title='Test Board')
self.syn_tool = getToolByName(self.portal, 'portal_syndication')
self.view = self.board.restrictedTraverse("@@RSS")
def testEnablingSyndication(self):
self.assertEqual(self.syn_tool.isSyndicationAllowed(self.board), False)
self.syn_tool.enableSyndication(self.board)
self.assertEqual(self.syn_tool.isSyndicationAllowed(self.board), True)
def testViewNotAllowedWithSyndicationDisabled(self):
self.assertRaises(Unauthorized, self.view.__call__)
def testViewUrl(self):
self.assertEqual(self.view.url(), self.board.absolute_url())
def testViewDate(self):
self.assertEqual(self.view.date(), self.board.modified().HTML4())
def testViewTitle(self):
self.assertEqual(self.view.title(), 'Test Board')
def testHumbleBeginnings(self):
self.view.update()
self.assertEqual(self.view.comments, [])
def testFirstComment(self):
forum=self.board.addForum('forum1', 'Title one', 'Description one')
conv=forum.addConversation('Conversation one', 'Text one')
conv.addComment("comment title", "comment body")
self.view.update()
self.assertEqual(len(self.view.comments), 2) # original text is first comment
def testCommentInfo(self):
forum=self.board.addForum('forum1', 'Title one', 'Description one')
conv=forum.addConversation('Conversation one', 'Text one')
conv.addComment("comment title", "comment body")
self.view.update()
comment=self.view.comments[0]
self.assertEqual(comment['title'], 'comment title')
self.assertEqual(comment['description'], 'comment body')
self.assertEqual(comment['author'], 'test_user_1_')
self.failUnless('date' in comment)
self.failUnless('url' in comment)
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestPloneboardBasics))
suite.addTest(unittest.makeSuite(TestPloneboardInterface))
suite.addTest(unittest.makeSuite(TestPloneboardWithoutContainment))
suite.addTest(unittest.makeSuite(TestPloneboardRSSFeed))
return suite
| [
[
1,
0,
0.0316,
0.0063,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.038,
0.0063,
0,
0.66,
0.0769,
550,
0,
1,
0,
0,
550,
0,
0
],
[
1,
0,
0.0443,
0.0063,
0,
0.6... | [
"import unittest",
"from zExceptions import Unauthorized",
"from zope.interface.verify import verifyClass, verifyObject",
"from Products.Ploneboard.tests import PloneboardTestCase",
"from Products.Ploneboard.interfaces import IPloneboard, IForum",
"from Products.Ploneboard.content.Ploneboard import Ploneb... |
from Products.CMFCore import permissions
from Products.CMFCore.permissions import setDefaultRoles
# Add permissions differ for each type, and are imported by __init__.initialize
# so don't change their names!
ViewBoard = permissions.View
SearchBoard = 'Ploneboard: Search'
AddBoard = AddPloneboard = 'Ploneboard: Add Ploneboard'
ManageBoard = 'Ploneboard: Add Ploneboard'
RequestReview = permissions.RequestReview
AddForum = AddPloneboardForum = 'Ploneboard: Add Forum'
ManageForum = 'Ploneboard: Add Forum'
AddConversation = AddPloneboardConversation = 'Ploneboard: Add Conversation'
ManageConversation = 'Ploneboard: Manage Conversation'
MoveConversation = 'Ploneboard: Move Conversation'
MergeConversation = 'Ploneboard: Merge Conversation'
AddComment = AddPloneboardComment = 'Ploneboard: Add Comment'
EditComment = permissions.ModifyPortalContent
AddAttachment = AddPloneboardAttachment = 'Ploneboard: Add Comment Attachment'
ManageComment = 'Ploneboard: Manage Comment'
ApproveComment = 'Ploneboard: Approve Comment' # Used for moderation
RetractComment = 'Ploneboard: Retract Comment'
ModerateForum = 'Ploneboard: Moderate Forum'
# Note: if this changes, you must also change configure.zcml!
DeleteComment = permissions.DeleteObjects
# Set up default roles for permissions
setDefaultRoles(ViewBoard,
('Anonymous', 'Member', 'Manager'))
setDefaultRoles(SearchBoard,
('Anonymous', 'Member', 'Manager'))
setDefaultRoles(AddBoard,
('Manager', 'Owner'))
setDefaultRoles(ManageBoard,
('Manager', 'Owner'))
setDefaultRoles(AddConversation,
('Authenticated', 'Manager'))
setDefaultRoles(AddComment,
('Authenticated', 'Manager'))
setDefaultRoles(AddAttachment,
('Manager',))
setDefaultRoles(ManageConversation,
('Manager',))
setDefaultRoles(MoveConversation,
('Manager',))
setDefaultRoles(MergeConversation,
('Manager',))
setDefaultRoles(ManageComment,
('Manager',))
setDefaultRoles(ApproveComment,
('Manager',))
setDefaultRoles(RetractComment,
('Manager',))
setDefaultRoles(ModerateForum,
('Manager', 'Reviewer',))
| [
[
1,
0,
0.0132,
0.0132,
0,
0.66,
0,
396,
0,
1,
0,
0,
396,
0,
0
],
[
1,
0,
0.0263,
0.0132,
0,
0.66,
0.0294,
892,
0,
1,
0,
0,
892,
0,
0
],
[
14,
0,
0.0921,
0.0132,
0,
... | [
"from Products.CMFCore import permissions",
"from Products.CMFCore.permissions import setDefaultRoles",
"ViewBoard = permissions.View",
"SearchBoard = 'Ploneboard: Search'",
"AddBoard = AddPloneboard = 'Ploneboard: Add Ploneboard'",
"ManageBoard = 'Ploneboard: Add Ploneboard'",
"RequestReview = permissi... |
from zope.interface import implements
from Products.ATContentTypes.interface import ITextContent
class CommentTextContent(object):
implements(ITextContent)
def __init__(self, context):
self.context = context
def getText(self, **kwargs):
return self.context.getText()
def setText(self, value, **kwargs):
self.context.setText(value, **kwargs)
def CookedBody(self, stx_level='ignored'):
return self.getText()
def EditableBody(self):
return self.getRawText()
| [
[
1,
0,
0.0476,
0.0476,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.1429,
0.0476,
0,
0.66,
0.5,
11,
0,
1,
0,
0,
11,
0,
0
],
[
3,
0,
0.619,
0.8095,
0,
0.66,
... | [
"from zope.interface import implements",
"from Products.ATContentTypes.interface import ITextContent",
"class CommentTextContent(object):\n implements(ITextContent)\n\n def __init__(self, context):\n self.context = context\n\n def getText(self, **kwargs):\n return self.context.getText()",... |
"""Migrate from 0.1b1 to 1.0b.
"""
# Zope imports
from ZODB.PersistentMapping import PersistentMapping
from Acquisition import aq_base
# CMF imports
from Products.CMFCore.utils import getToolByName
# Product imports
class Migration(object):
"""Migrate from 0.1b1 to 1.0b.
"""
def __init__(self, site, out):
self.site = site
self.out = out
self.catalog = getToolByName(self.site, 'portal_catalog')
def migrate(self):
"""Run migration on site object passed to __init__.
"""
print >> self.out, u"Migrating Ploneboard 0.1b1 -> 1.0b"
self.findAndCatalogAndClean()
def findAndCatalogAndClean(self):
"""Manually find all the ploneboard types, recatalog them, and remove
their old index objects that are just ZODB turds now.
"""
# Ploneboard instances themselves should still be cataloged...
pb_brains = self.catalog(portal_type='Ploneboard')
forum_count = 0
conv_count = 0
comm_count = 0
for pb in [brain.getObject() for brain in pb_brains]:
if pb.hasObject('ploneboard_catalog'):
pb._delObject('ploneboard_catalog')
msg = u"Removed stale 'ploneboard_catalog' from Ploneboard at %s."
print >> self.out, msg % '/'.join(pb.getPhysicalPath())
else:
msg = u"Checked for stale 'ploneboard_catalog' object on %s, but not present."
print >> self.out, msg % '/'.join(pb.getPhysicalPath())
# Directly access the stored forums. The Ploneboard API won't work here
for forum in pb.objectValues('PloneboardForum'):
forum.reindexObject()
self._cleanIndex(forum)
forum_count += 1
for conv in forum.objectValues('PloneboardConversation'):
conv.reindexObject()
self._cleanIndex(conv)
conv_count += 1
for comm in conv.objectValues('PloneboardComment'):
comm.reindexObject()
comm_count += 1
msg = "Indexed and cleaned %s forums, %s conversations, and %s comments."
print >> self.out, msg % (forum_count, conv_count, comm_count)
def _cleanIndex(self, ob):
if getattr(aq_base(ob), '_index', None) is not None:
delattr(ob, '_index')
msg = u"Removed stale '_index' from %s at %s."
print >> self.out, msg % (ob.meta_type, '/'.join(ob.getPhysicalPath()))
else:
msg = u"Checked for stale '_index' attribute on '%s' at %s, but not present."
print >> self.out, msg % (ob.meta_type, '/'.join(ob.getPhysicalPath()))
| [
[
8,
0,
0.0221,
0.0294,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0588,
0.0147,
0,
0.66,
0.25,
375,
0,
1,
0,
0,
375,
0,
0
],
[
1,
0,
0.0735,
0.0147,
0,
0.66,
... | [
"\"\"\"Migrate from 0.1b1 to 1.0b.\n\"\"\"",
"from ZODB.PersistentMapping import PersistentMapping",
"from Acquisition import aq_base",
"from Products.CMFCore.utils import getToolByName",
"class Migration(object):\n \"\"\"Migrate from 0.1b1 to 1.0b.\n \"\"\"\n\n def __init__(self, site, out):\n ... |
"""
$Id: __init__.py 53403 2007-11-08 09:54:35Z wichert $
"""
from Products.Archetypes.public import process_types, listTypes
from Products.CMFCore.DirectoryView import registerDirectory
from Products.Ploneboard.PloneboardTool import PloneboardTool
import sys
from Products.Ploneboard.config import SKINS_DIR, GLOBALS, PROJECTNAME
import Products.Ploneboard.catalog
registerDirectory(SKINS_DIR, GLOBALS)
this_module = sys.modules[ __name__ ]
def initialize(context):
##Import Types here to register them
import Products.Ploneboard.content
# If we put this import line to the top of module then
# utils will magically point to Ploneboard.utils
from Products.CMFCore import utils
utils.ToolInit('Ploneboard Tool',
tools=(PloneboardTool,),
icon='tool.gif'
).initialize(context)
content_types, constructors, ftis = process_types(
listTypes(PROJECTNAME),
PROJECTNAME)
# Assign an own permission to all content types
# Heavily based on Bricolite's code from Ben Saller
import permissions as perms
allTypes = zip(content_types, constructors)
for atype, constructor in allTypes:
kind = "%s: %s" % (PROJECTNAME, atype.archetype_name)
utils.ContentInit(
kind,
content_types = (atype,),
# Add permissions look like perms.Add{meta_type}
permission = getattr(perms, 'Add%s' % atype.meta_type),
extra_constructors = (constructor,),
fti = ftis,
).initialize(context)
from AccessControl import allow_class
from batch import Batch
allow_class(Batch)
this_module.Batch = Batch
# Avoid breaking old Ploneboard instances when moving content types modules
# from Ploneboard/types/ to Ploneboard/content/
import content
sys.modules['Products.Ploneboard.types'] = content
| [
[
8,
0,
0.0339,
0.0508,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0847,
0.0169,
0,
0.66,
0.0909,
257,
0,
2,
0,
0,
257,
0,
0
],
[
1,
0,
0.1017,
0.0169,
0,
0.66... | [
"\"\"\"\n$Id: __init__.py 53403 2007-11-08 09:54:35Z wichert $\n\"\"\"",
"from Products.Archetypes.public import process_types, listTypes",
"from Products.CMFCore.DirectoryView import registerDirectory",
"from Products.Ploneboard.PloneboardTool import PloneboardTool",
"import sys",
"from Products.Ploneboa... |
from zope.interface import implements
from zope.app.schema.vocabulary import IVocabularyFactory
from Products.CMFCore.utils import getToolByName
from zope.schema.vocabulary import SimpleVocabulary
class AvailableTransformsVocabulary(object):
"""Vocabulary for available Ploneboard transforms.
"""
implements(IVocabularyFactory)
def __call__(self, context):
context=getattr(context, "context", context)
tool=getToolByName(context, "portal_ploneboard")
items=[(t,t) for t in tool.getTransforms()]
items.sort()
return SimpleVocabulary.fromItems(items)
AvailableTransformsVocabularyFactory=AvailableTransformsVocabulary()
| [
[
1,
0,
0.0526,
0.0526,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.1053,
0.0526,
0,
0.66,
0.2,
93,
0,
1,
0,
0,
93,
0,
0
],
[
1,
0,
0.1579,
0.0526,
0,
0.66,... | [
"from zope.interface import implements",
"from zope.app.schema.vocabulary import IVocabularyFactory",
"from Products.CMFCore.utils import getToolByName",
"from zope.schema.vocabulary import SimpleVocabulary",
"class AvailableTransformsVocabulary(object):\n \"\"\"Vocabulary for available Ploneboard transf... |
"""
$Id: config.py 55779 2007-12-18 14:26:49Z fschulze $
"""
PROJECTNAME = "Ploneboard"
SKINS_DIR = 'skins'
I18N_DOMAIN = PROJECTNAME.lower()
# Transform config
EMOTICON_TRANSFORM_ID = 'text_to_emoticons'
EMOTICON_TRANSFORM_MODULE = 'Products.Ploneboard.transforms.text_to_emoticons'
URL_TRANSFORM_MODULE = 'Products.Ploneboard.transforms.url_to_hyperlink'
SAFE_HTML_TRANSFORM_MODULE = 'Products.PortalTransforms.transforms.safe_html'
PLONEBOARD_TRANSFORMSCHAIN_ID = 'ploneboard_chain'
PLONEBOARD_TOOL = 'portal_ploneboard'
REPLY_RELATIONSHIP = 'ploneboard_reply_to'
# This should be configurable ttw
NUMBER_OF_ATTACHMENTS = 5
GLOBALS = globals()
try:
from Products import SimpleAttachment as SA
HAS_SIMPLEATTACHMENT = True
del SA
except ImportError:
HAS_SIMPLEATTACHMENT = False
| [
[
8,
0,
0.069,
0.1034,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1379,
0.0345,
0,
0.66,
0.0769,
239,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.1724,
0.0345,
0,
0.66,... | [
"\"\"\"\n$Id: config.py 55779 2007-12-18 14:26:49Z fschulze $\n\"\"\"",
"PROJECTNAME = \"Ploneboard\"",
"SKINS_DIR = 'skins'",
"I18N_DOMAIN = PROJECTNAME.lower()",
"EMOTICON_TRANSFORM_ID = 'text_to_emoticons'",
"EMOTICON_TRANSFORM_MODULE = 'Products.Ploneboard.transforms.text_to_emoticons'",
"URL_TRANSF... |
from setuptools import setup, find_packages
version = '2.1b2'
setup(name='Products.Ploneboard',
version=version,
description="A discussion board for Plone.",
long_description=open("README.txt").read() + \
open("docs/INSTALL.txt").read() + \
open("docs/HISTORY.txt").read(),
classifiers=[
"Framework :: Plone",
"Framework :: Zope2",
"Programming Language :: Python",
],
keywords='Zope CMF Plone board forum',
author='Jarn, Wichert Akkerman, Martin Aspeli',
author_email='plone-developers@lists.sourceforge.net',
url='http://svn.plone.org/svn/collective/Ploneboard/trunk',
license='GPL',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['Products'],
include_package_data=True,
zip_safe=False,
download_url='http://plone.org/products/ploneboard',
install_requires=[
'setuptools',
'Products.SimpleAttachment',
'plone.app.controlpanel',
'plone.app.portlets',
'plone.portlets',
'plone.memoize',
'plone.i18n',
'python-dateutil',
'Plone >= 3.3',
],
)
| [
[
1,
0,
0.027,
0.027,
0,
0.66,
0,
182,
0,
2,
0,
0,
182,
0,
0
],
[
14,
0,
0.0811,
0.027,
0,
0.66,
0.5,
623,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.5676,
0.8919,
0,
0.66,
... | [
"from setuptools import setup, find_packages",
"version = '2.1b2'",
"setup(name='Products.Ploneboard',\n version=version,\n description=\"A discussion board for Plone.\",\n long_description=open(\"README.txt\").read() + \\\n open(\"docs/INSTALL.txt\").read() + \\\n ... |
##############################################################################
#
# Copyright (c) 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
$Id: bootstrap.py 75593 2007-05-06 21:11:27Z jim $
"""
import os, shutil, sys, tempfile, urllib2
tmpeggs = tempfile.mkdtemp()
try:
import pkg_resources
except ImportError:
ez = {}
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
import pkg_resources
cmd = 'from setuptools.command.easy_install import main; main()'
if sys.platform == 'win32':
cmd = '"%s"' % cmd # work around spawn lamosity on windows
ws = pkg_resources.working_set
assert os.spawnle(
os.P_WAIT, sys.executable, sys.executable,
'-c', cmd, '-mqNxd', tmpeggs, 'zc.buildout',
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse('setuptools')).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout')
import zc.buildout.buildout
zc.buildout.buildout.main(sys.argv[1:] + ['bootstrap'])
shutil.rmtree(tmpeggs)
| [
[
8,
0,
0.3182,
0.1455,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4182,
0.0182,
0,
0.66,
0.0909,
688,
0,
5,
0,
0,
688,
0,
0
],
[
14,
0,
0.4545,
0.0182,
0,
0.6... | [
"\"\"\"Bootstrap a buildout-based project\n\nSimply run this script in a directory containing a buildout.cfg.\nThe script accepts buildout command-line options, so you can\nuse the -c option to specify an alternate configuration file.\n\n$Id: bootstrap.py 75593 2007-05-06 21:11:27Z jim $\n\"\"\"",
"import os, shu... |
#coding=utf8
__author__ = 'alex'
import datetime
import uuid
from sqlalchemy import Column,Integer,String,DateTime,Boolean,Text,UniqueConstraint,Table, MetaData,ForeignKey, Numeric
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import relationship,backref
from decimal import Decimal
from utils import hash_passwd,read_random, check_passwd
from flask import g
TABLEARGS = {
'mysql_engine': 'InnoDB',
'mysql_charset':'utf8'
}
class DeclaredBase(object):
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
id = Column(Integer, primary_key=True, autoincrement=True)
create_time = Column(DateTime, default=datetime.datetime.now, index=True)
last_modify = Column(DateTime, default=datetime.datetime.now, index=True)
Base = declarative_base(cls=DeclaredBase)
class Admin(Base):
name = Column(String(40))
password = Column(String(40))
nick = Column(String(40))
status = Column(Integer)
__table_args__ = (
UniqueConstraint(name,),
TABLEARGS
)
def __init__(self,name, password, nick):
self.name = name
self.password = hash_passwd(password)
self.nick = nick
self.status = 0
def verify(self, password):
return check_passwd(password,self.password)
class Catalogs(Base):
name = Column(String(20))
forward_id = Column(Integer)
level = Column(Integer)
idx = Column(Integer)
__table_args__ = (
UniqueConstraint(name,),
TABLEARGS
)
def __init__(self,name, forward_id, level, idx):
self.name = name
self.forward_id = forward_id
self.level = level
self.idx = idx
def make_child(self, name):
return g.db.add(Catalogs(name, self.id, self.level+1))
@property
def has_document(self):
return g.db.query(Document).filter(Document.catalog_id==self.id).count()
@property
def nexts(self):
data = list(g.db.query(Catalogs).filter(Catalogs.forward_id==self.id).order_by(Catalogs.idx.asc()))
if not data:
data = list(g.db.query(Document).filter(Document.catalog_id==self.id).order_by(Document.id.desc()))
return data
def indexed_next(self):
data = self.nexts
idx = 0
for d in data:
yield idx,d
idx+=1
@property
def all_childs(self):
data = []
for child in self.nexts:
data.append(child)
if not child.doc_type:
for child_0 in child.nexts:
if not child_0.doc_type:
data.append(child_0)
for child_1 in child_0.nexts:
if not child_1.doc_type:
data.append(child_1)
#data.reverse()
return data
@property
def text(self):
lines = []
for child in self.all_childs:
if not child.doc_type:
lines.append(u"".join(["-"*(child.level),child.name]))
return u"\n".join(lines)
@property
def doc_type(self):
return False
class Document(Base):
title = Column(String(200))
content = Column(Text)
catalog_id = Column(Integer)
poster = Column(String(40))
__table_args__ = (
UniqueConstraint(title,),
TABLEARGS
)
def __init__(self, title, content, catalog_id, poster):
self.title = title
self.content = content
self.catalog_id = catalog_id
self.poster = poster
def append_attachment(self, name, attach_type, content):
return g.db.add(Attachment(self.id, name, attach_type, content))
@property
def attachments(self):
return g.db.query(Attachment).filter(Attachment.document_id==self.id).order_by(Attachment.id.asc())
@property
def path_catalogs(self):
catalog = g.db.query(Catalogs).get(self.catalog_id)
datas = [catalog,]
while True:
try:
catalog = g.db.query(Catalogs).get(catalog.forward_id)
if not catalog:
break
datas.append(catalog)
except:
break
datas.reverse()
return datas
@property
def doc_type(self):
return True
@property
def nexts(self):
return []
class Attachment(Base):
document_id = Column(Integer)
name = Column(String(40))
attachment_type =Column(Integer) #TODO: 0=文本,1=url
text_content = Column(Text)
url_content = Column(String(100))
__table_args__ = TABLEARGS
def __init__(self, document_id, name, attachment_type, content):
self.document_id = document_id
self.name = name
self.attachment_type = attachment_type
if attachment_type:
self.url_content = content
else:
self.text_content = content
def __repr__(self):
return self.url_content if self.attachment_type else self.text_content
@property
def content(self):
return str(self)
| [
[
14,
0,
0.0112,
0.0056,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0169,
0.0056,
0,
0.66,
0.0667,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0225,
0.0056,
0,
0... | [
"__author__ = 'alex'",
"import datetime",
"import uuid",
"from sqlalchemy import Column,Integer,String,DateTime,Boolean,Text,UniqueConstraint,Table, MetaData,ForeignKey, Numeric",
"from sqlalchemy.ext.declarative import declarative_base, declared_attr",
"from sqlalchemy.orm import relationship,backref",
... |
#coding=utf8
__author__ = 'alex'
DEBUG = True
LOCAL = True
MEDIA_ROOT = "/static/"
if LOCAL:
DB_URI = "mysql://root:123456@127.0.0.1:3306/315db?charset=utf8"
else:
DB_URI = "mysql://root:123456@127.0.0.1:3306/315db?charset=utf8"
TIMEOUT = 3600
SECRET_KEY = "11556666433221changge!" | [
[
14,
0,
0.1667,
0.0833,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.3333,
0.0833,
0,
0.66,
0.1667,
309,
1,
0,
0,
0,
0,
4,
0
],
[
14,
0,
0.4167,
0.0833,
0,
0... | [
"__author__ = 'alex'",
"DEBUG = True",
"LOCAL = True",
"MEDIA_ROOT = \"/static/\"",
"if LOCAL:\n DB_URI = \"mysql://root:123456@127.0.0.1:3306/315db?charset=utf8\"\nelse:\n DB_URI = \"mysql://root:123456@127.0.0.1:3306/315db?charset=utf8\"",
" DB_URI = \"mysql://root:123456@127.0.0.1:3306/315db?c... |
#coding=utf8
__author__ = 'alex'
from flask import Blueprint, render_template, abort, g, request, redirect, url_for, session, flash, send_file
from utils import *
from biz import *
from models import *
index = Blueprint('index', __name__,template_folder='templates',url_prefix='/')
@index.app_template_filter(name="content")
def show_content(document):
if document:
lines=document.content.split('\n')
if lines[0].startswith("http://"):
url=lines[0]
content = u"\n".join(lines[1:])
else:
url=None
content = document.content
return render_template("include/content.html",**locals())
else:
return ""
@index.app_template_filter(name="one")
def one(doc_list):
if doc_list:
return doc_list[0]
return None
@index.app_template_filter(name="nav")
def menu(txt):
catalogs = top_level()
return render_template("include/top_nav.html",**locals())
@index.route("")
def front():
return render_template("front.html",**locals())
@index.route("<page_name>.html")
def page(page_name):
return render_template("%s.html"%page_name,**locals())
@index.route("doc/<catalog_id>.html")
def catalog(catalog_id):
catalog = g.db.query(Catalogs).get(catalog_id)
return render_template("document.html",**locals()) | [
[
14,
0,
0.0435,
0.0217,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0652,
0.0217,
0,
0.66,
0.0909,
782,
0,
10,
0,
0,
782,
0,
0
],
[
1,
0,
0.087,
0.0217,
0,
0... | [
"__author__ = 'alex'",
"from flask import Blueprint, render_template, abort, g, request, redirect, url_for, session, flash, send_file",
"from utils import *",
"from biz import *",
"from models import *",
"index = Blueprint('index', __name__,template_folder='templates',url_prefix='/')",
"def show_content... |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0588,
0.0118,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0706,
0.0118,
0,
0.66,
0.125,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0824,
0.0118,
0,
0... | [
"import logging",
"import shutil",
"import sys",
"import urlparse",
"import SimpleHTTPServer",
"import BaseHTTPServer",
"class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Handle playfoursquare.com requests, for testing.\"\"\"\n\n def do_GET(self):\n logging.warn('do_GET: %s, %s',... |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| [
[
1,
0,
0.1111,
0.037,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1481,
0.037,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.6... | [
"import os",
"import subprocess",
"import sys",
"BASEDIR = '../main/src/com/joelapenna/foursquare'",
"TYPESDIR = '../captures/types/v1'",
"captures = sys.argv[1:]",
"if not captures:\n captures = os.listdir(TYPESDIR)",
" captures = os.listdir(TYPESDIR)",
"for f in captures:\n basename = f.split('... |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0631,
0.0991,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1261,
0.009,
0,
0.66,
0.05,
2,
0,
1,
0,
0,
2,
0,
0
],
[
1,
0,
0.1351,
0.009,
0,
0.66,
0.... | [
"\"\"\"\nPull a oAuth protected page from foursquare.\n\nExpects ~/.oget to contain (one on each line):\nCONSUMER_KEY\nCONSUMER_KEY_SECRET\nUSERNAME\nPASSWORD",
"import httplib",
"import os",
"import re",
"import sys",
"import urllib",
"import urllib2",
"import urlparse",
"import user",
"from xml.... |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0201,
0.0067,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0268,
0.0067,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0336,
0.0067,
0,
... | [
"import datetime",
"import sys",
"import textwrap",
"import common",
"from xml.dom import pulldom",
"PARSER = \"\"\"\\\n/**\n * Copyright 2009 Joe LaPenna\n */\n\npackage com.joelapenna.foursquare.parsers;\n\nimport com.joelapenna.foursquare.Foursquare;",
"BOOLEAN_STANZA = \"\"\"\\\n } else i... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| [
[
1,
0,
0.0263,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0439,
0.0088,
0,
0.66,
0.0833,
290,
0,
1,
0,
0,
290,
0,
0
],
[
1,
0,
0.0526,
0.0088,
0,
... | [
"import logging",
"from xml.dom import minidom",
"from xml.dom import pulldom",
"BOOLEAN = \"boolean\"",
"STRING = \"String\"",
"GROUP = \"Group\"",
"DEFAULT_INTERFACES = ['FoursquareType']",
"INTERFACES = {\n}",
"DEFAULT_CLASS_IMPORTS = [\n]",
"CLASS_IMPORTS = {\n# 'Checkin': DEFAULT_CLASS_IMP... |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Main program for Rietveld.
This is also a template for running a Django app under Google App
Engine, especially when using a newer version of Django than provided
in the App Engine standard library.
The site-specific code is all in other files: urls.py, models.py,
views.py, settings.py.
"""
# Standard Python imports.
import os
import sys
import logging
# Log a message each time this module get loaded.
logging.info('Loading %s, app version = %s',
__name__, os.getenv('CURRENT_VERSION_ID'))
import appengine_config
# AppEngine imports.
from google.appengine.ext.webapp import util
# Import webapp.template. This makes most Django setup issues go away.
from google.appengine.ext.webapp import template
# Helper to enter the debugger. This passes in __stdin__ and
# __stdout__, because stdin and stdout are connected to the request
# and response streams. You must import this from __main__ to use it.
# (I tried to make it universally available via __builtin__, but that
# doesn't seem to work for some reason.)
def BREAKPOINT():
import pdb
p = pdb.Pdb(None, sys.__stdin__, sys.__stdout__)
p.set_trace()
# Import various parts of Django.
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
import django.forms
# Work-around to avoid warning about django.newforms in djangoforms.
django.newforms = django.forms
def log_exception(*args, **kwds):
"""Django signal handler to log an exception."""
cls, err = sys.exc_info()[:2]
logging.exception('Exception in request: %s: %s', cls.__name__, err)
# Log all exceptions detected by Django.
django.core.signals.got_request_exception.connect(log_exception)
# Unregister Django's default rollback event handler.
django.core.signals.got_request_exception.disconnect(
django.db._rollback_on_exception)
def real_main():
"""Main program."""
# Create a Django application for WSGI.
application = django.core.handlers.wsgi.WSGIHandler()
# Run the WSGI CGI handler with that application.
util.run_wsgi_app(application)
def profile_main():
"""Main program for profiling."""
import cProfile
import pstats
import StringIO
prof = cProfile.Profile()
prof = prof.runctx('real_main()', globals(), locals())
stream = StringIO.StringIO()
stats = pstats.Stats(prof, stream=stream)
# stats.strip_dirs() # Don't; too many modules are named __init__.py.
stats.sort_stats('time') # 'time', 'cumulative' or 'calls'
stats.print_stats() # Optional arg: how many to print
# The rest is optional.
# stats.print_callees()
# stats.print_callers()
print '\n<hr>'
print '<h1>Profile</h1>'
print '<pre>'
print stream.getvalue()[:1000000]
print '</pre>'
# Set this to profile_main to enable profiling.
main = real_main
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1667,
0.0789,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2281,
0.0088,
0,
0.66,
0.0476,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.2368,
0.0088,
0,
0.66... | [
"\"\"\"Main program for Rietveld.\n\nThis is also a template for running a Django app under Google App\nEngine, especially when using a newer version of Django than provided\nin the App Engine standard library.\n\nThe site-specific code is all in other files: urls.py, models.py,\nviews.py, settings.py.",
"import ... |
# Removes duplicate nicknames (issue99).
#
# To run this script:
# - Make sure App Engine library (incl. yaml) is in PYTHONPATH.
# - Make sure that the remote API is included in app.yaml.
# - Run "tools/appengine_console.py APP_ID".
# - Import this module.
# - update_accounts.run() updates accounts.
# - Use the other two functions to fetch accounts or find duplicates
# without any changes to the datastore.
from google.appengine.ext import db
from codereview import models
def fetch_accounts():
query = models.Account.all()
accounts = {}
results = query.fetch(100)
while results:
last = None
for account in results:
if account.lower_nickname in accounts:
accounts[account.lower_nickname].append(account)
else:
accounts[account.lower_nickname] = [account]
last = account
if last is None:
break
results = models.Account.all().filter('__key__ >',
last.key()).fetch(100)
return accounts
def find_duplicates(accounts):
tbd = []
while accounts:
_, entries = accounts.popitem()
if len(entries) > 1:
# update accounts, except the fist: it's the lucky one
for num, account in enumerate(entries[1:]):
account.nickname = '%s%d' % (account.nickname, num+1)
account.lower_nickname = account.nickname.lower()
account.fresh = True # display "change nickname..."
tbd.append(account)
return tbd
def run():
accounts = fetch_accounts()
print '%d accounts fetched' % len(accounts)
tbd = find_duplicates(accounts)
print 'Updating %d accounts' % len(tbd)
db.put(tbd)
print 'Updated accounts:'
for account in tbd:
print ' %s' % account.email
| [
[
1,
0,
0.2097,
0.0161,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.2419,
0.0161,
0,
0.66,
0.25,
844,
0,
1,
0,
0,
844,
0,
0
],
[
2,
0,
0.4194,
0.2742,
0,
0.... | [
"from google.appengine.ext import db",
"from codereview import models",
"def fetch_accounts():\n query = models.Account.all()\n accounts = {}\n results = query.fetch(100)\n while results:\n last = None\n for account in results:\n if account.lower_nickname in accounts:",
" ... |
"""Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.2')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
# Custom Django configuration.
# NOTE: All "main" scripts must import webapp.template before django.
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
settings._target = None
| [
[
8,
0,
0.0238,
0.0238,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0714,
0.0238,
0,
0.66,
0.0714,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0952,
0.0238,
0,
0.66... | [
"\"\"\"Configuration.\"\"\"",
"import logging",
"import os",
"import re",
"from google.appengine.ext.appstats import recording",
"logging.info('Loading %s from %s', __name__, __file__)",
"def webapp_add_wsgi_middleware(app):\n app = recording.appstats_wsgi_middleware(app)\n return app",
" app = rec... |
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test utils."""
import os
from google.appengine.ext import testbed
from django.test import TestCase as _TestCase
class TestCase(_TestCase):
"""Customized Django TestCase.
This class disables the setup of Django features that are not
available on App Engine (e.g. fixture loading). And it initializes
the Testbad class provided by the App Engine SDK.
"""
def _fixture_setup(self): # defined in django.test.TestCase
pass
def _fixture_teardown(self): # defined in django.test.TestCase
pass
def setUp(self):
super(TestCase, self).setUp()
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_user_stub()
def tearDown(self):
self.testbed.deactivate()
super(TestCase, self).tearDown()
def login(self, email):
"""Logs in a user identified by email."""
os.environ['USER_EMAIL'] = email
def logout(self):
"""Logs the user out."""
os.environ['USER_EMAIL'] = ''
| [
[
8,
0,
0.2727,
0.0182,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3091,
0.0182,
0,
0.66,
0.25,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3455,
0.0182,
0,
0.66,
... | [
"\"\"\"Test utils.\"\"\"",
"import os",
"from google.appengine.ext import testbed",
"from django.test import TestCase as _TestCase",
"class TestCase(_TestCase):\n \"\"\"Customized Django TestCase.\n\n This class disables the setup of Django features that are not\n available on App Engine (e.g. fixture lo... |
#!/usr/bin/env python
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import code
import getpass
import logging
import optparse
import os
import re
import sys
ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
LIB = os.path.join(ROOT, '..', 'google_appengine', 'lib')
sys.path.insert(0, os.path.join(ROOT, '..', 'google_appengine'))
sys.path.append(os.path.join(LIB, 'django_1_2'))
sys.path.append(os.path.join(LIB, 'fancy_urllib'))
sys.path.append(os.path.join(LIB, 'simplejson'))
sys.path.append(os.path.join(LIB, 'webob'))
sys.path.append(os.path.join(LIB, 'yaml', 'lib'))
sys.path.append(ROOT)
from google.appengine.ext.remote_api import remote_api_stub
import yaml
def default_auth_func():
user = os.environ.get('EMAIL_ADDRESS')
if user:
print('User: %s' % user)
else:
user = raw_input('Username:')
return user, getpass.getpass('Password:')
def smart_auth_func():
"""Try to guess first."""
try:
return os.environ['EMAIL_ADDRESS'], open('.pwd').readline().strip()
except (KeyError, IOError):
return default_auth_func()
def default_app_id(directory):
return yaml.load(open(os.path.join(directory, 'app.yaml')))['application']
def setup_env(app_id, host=None, auth_func=None):
"""Setup remote access to a GAE instance."""
auth_func = auth_func or smart_auth_func
host = host or '%s.appspot.com' % app_id
# pylint: disable=W0612
from google.appengine.api import memcache
from google.appengine.api.users import User
from google.appengine.ext import db
remote_api_stub.ConfigureRemoteDatastore(
app_id, '/_ah/remote_api', auth_func, host)
# Initialize environment.
os.environ['SERVER_SOFTWARE'] = ''
import appengine_config
# Create shortcuts.
import codereview
from codereview import models, views
# Symbols presented to the user.
predefined_vars = locals().copy()
del predefined_vars['appengine_config']
del predefined_vars['auth_func']
# Load all the models.
for i in dir(models):
if re.match(r'[A-Z][a-z]', i[:2]):
predefined_vars[i] = getattr(models, i)
return predefined_vars
def main():
parser = optparse.OptionParser()
parser.add_option('-v', '--verbose', action='count')
options, args = parser.parse_args()
if not args:
app_id = default_app_id(ROOT)
else:
app_id = args[0]
host = None
if len(args) > 1:
host = args[1]
if options.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.ERROR)
predefined_vars = setup_env(app_id, host)
prompt = (
'App Engine interactive console for "%s".\n'
'Available symbols:\n'
' %s\n') % (app_id, ', '.join(sorted(predefined_vars)))
code.interact(prompt, None, predefined_vars)
if __name__ == '__main__':
sys.exit(main())
| [
[
1,
0,
0.1345,
0.0084,
0,
0.66,
0,
44,
0,
1,
0,
0,
44,
0,
0
],
[
1,
0,
0.1429,
0.0084,
0,
0.66,
0.0435,
784,
0,
1,
0,
0,
784,
0,
0
],
[
1,
0,
0.1513,
0.0084,
0,
0.... | [
"import code",
"import getpass",
"import logging",
"import optparse",
"import os",
"import re",
"import sys",
"ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')",
"LIB = os.path.join(ROOT, '..', 'google_appengine', 'lib')",
"sys.path.insert(0, os.path.join(ROOT, '..', 'google_a... |
# Copyright 2008-2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Top-level URL mappings for Rietveld."""
# NOTE: Must import *, since Django looks for things here, e.g. handler500.
from django.conf.urls.defaults import *
# If you don't want to run Rietveld from the root level, add the
# subdirectory as shown in the following example:
#
# url(r'subpath/', include('codereview.urls')),
#
urlpatterns = patterns(
'',
url(r'', include('codereview.urls')),
)
| [
[
8,
0,
0.5357,
0.0357,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.6429,
0.0357,
0,
0.66,
0.5,
341,
0,
1,
0,
0,
341,
0,
0
],
[
14,
0,
0.9464,
0.1429,
0,
0.66,
... | [
"\"\"\"Top-level URL mappings for Rietveld.\"\"\"",
"from django.conf.urls.defaults import *",
"urlpatterns = patterns(\n '',\n url(r'', include('codereview.urls')),\n )"
] |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Minimal Django settings."""
import os
from google.appengine.api import app_identity
APPEND_SLASH = False
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
INSTALLED_APPS = (
'codereview',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.http.ConditionalGetMiddleware',
'codereview.middleware.AddUserToRequestMiddleware',
)
ROOT_URLCONF = 'urls'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
TEMPLATE_DEBUG = DEBUG
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
)
FILE_UPLOAD_HANDLERS = (
'django.core.files.uploadhandler.MemoryFileUploadHandler',
)
FILE_UPLOAD_MAX_MEMORY_SIZE = 1048576 # 1 MB
MEDIA_URL = '/static/'
appid = app_identity.get_application_id()
RIETVELD_INCOMING_MAIL_ADDRESS = ('reply@%s.appspotmail.com' % appid)
RIETVELD_INCOMING_MAIL_MAX_SIZE = 500 * 1024 # 500K
RIETVELD_REVISION = '<unknown>'
try:
RIETVELD_REVISION = open(
os.path.join(os.path.dirname(__file__), 'REVISION')
).read()
except:
pass
UPLOAD_PY_SOURCE = os.path.join(os.path.dirname(__file__), 'upload.py')
| [
[
8,
0,
0.25,
0.0167,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2833,
0.0167,
0,
0.66,
0.05,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3167,
0.0167,
0,
0.66,
... | [
"\"\"\"Minimal Django settings.\"\"\"",
"import os",
"from google.appengine.api import app_identity",
"APPEND_SLASH = False",
"DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')",
"INSTALLED_APPS = (\n 'codereview',\n)",
"MIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n... |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""App Engine data model (schema) definition for Rietveld."""
# Python imports
import logging
import md5
import os
import re
import time
# AppEngine imports
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.api import users
# Local imports
import engine
import patching
CONTEXT_CHOICES = (3, 10, 25, 50, 75, 100)
### GQL query cache ###
_query_cache = {}
def gql(cls, clause, *args, **kwds):
"""Return a query object, from the cache if possible.
Args:
cls: a db.Model subclass.
clause: a query clause, e.g. 'WHERE draft = TRUE'.
*args, **kwds: positional and keyword arguments to be bound to the query.
Returns:
A db.GqlQuery instance corresponding to the query with *args and
**kwds bound to the query.
"""
query_string = 'SELECT * FROM %s %s' % (cls.kind(), clause)
query = _query_cache.get(query_string)
if query is None:
_query_cache[query_string] = query = db.GqlQuery(query_string)
query.bind(*args, **kwds)
return query
### Issues, PatchSets, Patches, Contents, Comments, Messages ###
class Issue(db.Model):
"""The major top-level entity.
It has one or more PatchSets as its descendants.
"""
subject = db.StringProperty(required=True)
description = db.TextProperty()
base = db.StringProperty()
local_base = db.BooleanProperty(default=False)
owner = db.UserProperty(auto_current_user_add=True, required=True)
created = db.DateTimeProperty(auto_now_add=True)
modified = db.DateTimeProperty(auto_now=True)
reviewers = db.ListProperty(db.Email)
cc = db.ListProperty(db.Email)
closed = db.BooleanProperty(default=False)
private = db.BooleanProperty(default=False)
n_comments = db.IntegerProperty()
_is_starred = None
@property
def is_starred(self):
"""Whether the current user has this issue starred."""
if self._is_starred is not None:
return self._is_starred
account = Account.current_user_account
self._is_starred = account is not None and self.key().id() in account.stars
return self._is_starred
def user_can_edit(self, user):
"""Return true if the given user has permission to edit this issue."""
return user == self.owner
@property
def edit_allowed(self):
"""Whether the current user can edit this issue."""
account = Account.current_user_account
if account is None:
return False
return self.user_can_edit(account.user)
def update_comment_count(self, n):
"""Increment the n_comments property by n.
If n_comments in None, compute the count through a query. (This
is a transitional strategy while the database contains Issues
created using a previous version of the schema.)
"""
if self.n_comments is None:
self.n_comments = self._get_num_comments()
self.n_comments += n
@property
def num_comments(self):
"""The number of non-draft comments for this issue.
This is almost an alias for self.n_comments, except that if
n_comments is None, it is computed through a query, and stored,
using n_comments as a cache.
"""
if self.n_comments is None:
self.n_comments = self._get_num_comments()
return self.n_comments
def _get_num_comments(self):
"""Helper to compute the number of comments through a query."""
return gql(Comment,
'WHERE ANCESTOR IS :1 AND draft = FALSE',
self).count()
_num_drafts = None
@property
def num_drafts(self):
"""The number of draft comments on this issue for the current user.
The value is expensive to compute, so it is cached.
"""
if self._num_drafts is None:
account = Account.current_user_account
if account is None:
self._num_drafts = 0
else:
query = gql(Comment,
'WHERE ANCESTOR IS :1 AND author = :2 AND draft = TRUE',
self, account.user)
self._num_drafts = query.count()
return self._num_drafts
class PatchSet(db.Model):
"""A set of patchset uploaded together.
This is a descendant of an Issue and has Patches as descendants.
"""
issue = db.ReferenceProperty(Issue) # == parent
message = db.StringProperty()
data = db.BlobProperty()
url = db.LinkProperty()
created = db.DateTimeProperty(auto_now_add=True)
modified = db.DateTimeProperty(auto_now=True)
n_comments = db.IntegerProperty(default=0)
def update_comment_count(self, n):
"""Increment the n_comments property by n."""
self.n_comments = self.num_comments + n
@property
def num_comments(self):
"""The number of non-draft comments for this issue.
This is almost an alias for self.n_comments, except that if
n_comments is None, 0 is returned.
"""
# For older patchsets n_comments is None.
return self.n_comments or 0
class Message(db.Model):
"""A copy of a message sent out in email.
This is a descendant of an Issue.
"""
issue = db.ReferenceProperty(Issue) # == parent
subject = db.StringProperty()
sender = db.EmailProperty()
recipients = db.ListProperty(db.Email)
date = db.DateTimeProperty(auto_now_add=True)
text = db.TextProperty()
draft = db.BooleanProperty(default=False)
_approval = None
@property
def approval(self):
"""Is True when the message represents an approval of the review."""
if self._approval is None:
# Must contain 'lgtm' in a line that doesn't start with '>'.
self._approval = any(
True for line in self.text.lower().splitlines()
if not line.strip().startswith('>') and 'lgtm' in line)
# Must not be issue owner.
self._approval &= self.issue.owner.email() != self.sender
return self._approval
class Content(db.Model):
"""The content of a text file.
This is a descendant of a Patch.
"""
# parent => Patch
text = db.TextProperty()
data = db.BlobProperty()
# Checksum over text or data depending on the type of this content.
checksum = db.TextProperty()
is_uploaded = db.BooleanProperty(default=False)
is_bad = db.BooleanProperty(default=False)
file_too_large = db.BooleanProperty(default=False)
@property
def lines(self):
"""The text split into lines, retaining line endings."""
if not self.text:
return []
return self.text.splitlines(True)
class Patch(db.Model):
"""A single patch, i.e. a set of changes to a single file.
This is a descendant of a PatchSet.
"""
patchset = db.ReferenceProperty(PatchSet) # == parent
filename = db.StringProperty()
status = db.StringProperty() # 'A', 'A +', 'M', 'D' etc
text = db.TextProperty()
content = db.ReferenceProperty(Content)
patched_content = db.ReferenceProperty(Content, collection_name='patch2_set')
is_binary = db.BooleanProperty(default=False)
# Ids of patchsets that have a different version of this file.
delta = db.ListProperty(int)
delta_calculated = db.BooleanProperty(default=False)
_lines = None
@property
def lines(self):
"""The patch split into lines, retaining line endings.
The value is cached.
"""
if self._lines is not None:
return self._lines
if not self.text:
lines = []
else:
lines = self.text.splitlines(True)
self._lines = lines
return lines
_property_changes = None
@property
def property_changes(self):
"""The property changes split into lines.
The value is cached.
"""
if self._property_changes != None:
return self._property_changes
self._property_changes = []
match = re.search('^Property changes on.*\n'+'_'*67+'$', self.text,
re.MULTILINE)
if match:
self._property_changes = self.text[match.end():].splitlines()
return self._property_changes
_num_added = None
@property
def num_added(self):
"""The number of line additions in this patch.
The value is cached.
"""
if self._num_added is None:
self._num_added = self.count_startswith('+') - 1
return self._num_added
_num_removed = None
@property
def num_removed(self):
"""The number of line removals in this patch.
The value is cached.
"""
if self._num_removed is None:
self._num_removed = self.count_startswith('-') - 1
return self._num_removed
_num_chunks = None
@property
def num_chunks(self):
"""The number of 'chunks' in this patch.
A chunk is a block of lines starting with '@@'.
The value is cached.
"""
if self._num_chunks is None:
self._num_chunks = self.count_startswith('@@')
return self._num_chunks
_num_comments = None
@property
def num_comments(self):
"""The number of non-draft comments for this patch.
The value is cached.
"""
if self._num_comments is None:
self._num_comments = gql(Comment,
'WHERE patch = :1 AND draft = FALSE',
self).count()
return self._num_comments
_num_drafts = None
@property
def num_drafts(self):
"""The number of draft comments on this patch for the current user.
The value is expensive to compute, so it is cached.
"""
if self._num_drafts is None:
account = Account.current_user_account
if account is None:
self._num_drafts = 0
else:
query = gql(Comment,
'WHERE patch = :1 AND draft = TRUE AND author = :2',
self, account.user)
self._num_drafts = query.count()
return self._num_drafts
def count_startswith(self, prefix):
"""Returns the number of lines with the specified prefix."""
return len([l for l in self.lines if l.startswith(prefix)])
def get_content(self):
"""Get self.content, or fetch it if necessary.
This is the content of the file to which this patch is relative.
Returns:
a Content instance.
Raises:
engine.FetchError: If there was a problem fetching it.
"""
try:
if self.content is not None:
if self.content.is_bad:
msg = 'Bad content. Try to upload again.'
logging.warn('Patch.get_content: %s', msg)
raise engine.FetchError(msg)
if self.content.is_uploaded and self.content.text == None:
msg = 'Upload in progress.'
logging.warn('Patch.get_content: %s', msg)
raise engine.FetchError(msg)
else:
return self.content
except db.Error:
# This may happen when a Content entity was deleted behind our back.
self.content = None
content = engine.FetchBase(self.patchset.issue.base, self)
content.put()
self.content = content
self.put()
return content
def get_patched_content(self):
"""Get self.patched_content, computing it if necessary.
This is the content of the file after applying this patch.
Returns:
a Content instance.
Raises:
engine.FetchError: If there was a problem fetching the old content.
"""
try:
if self.patched_content is not None:
return self.patched_content
except db.Error:
# This may happen when a Content entity was deleted behind our back.
self.patched_content = None
old_lines = self.get_content().text.splitlines(True)
logging.info('Creating patched_content for %s', self.filename)
chunks = patching.ParsePatchToChunks(self.lines, self.filename)
new_lines = []
for tag, old, new in patching.PatchChunks(old_lines, chunks):
new_lines.extend(new)
text = db.Text(''.join(new_lines))
patched_content = Content(text=text, parent=self)
patched_content.put()
self.patched_content = patched_content
self.put()
return patched_content
@property
def no_base_file(self):
"""Returns True iff the base file is not available."""
return self.content and self.content.file_too_large
class Comment(db.Model):
"""A Comment for a specific line of a specific file.
This is a descendant of a Patch.
"""
patch = db.ReferenceProperty(Patch) # == parent
message_id = db.StringProperty() # == key_name
author = db.UserProperty(auto_current_user_add=True)
date = db.DateTimeProperty(auto_now=True)
lineno = db.IntegerProperty()
text = db.TextProperty()
left = db.BooleanProperty()
draft = db.BooleanProperty(required=True, default=True)
def complete(self, patch):
"""Set the shorttext and buckets attributes."""
# TODO(guido): Turn these into caching proprties instead.
# The strategy for buckets is that we want groups of lines that
# start with > to be quoted (and not displayed by
# default). Whitespace-only lines are not considered either quoted
# or not quoted. Same goes for lines that go like "On ... user
# wrote:".
cur_bucket = []
quoted = None
self.buckets = []
def _Append():
if cur_bucket:
self.buckets.append(Bucket(text="\n".join(cur_bucket),
quoted=bool(quoted)))
lines = self.text.splitlines()
for line in lines:
if line.startswith("On ") and line.endswith(":"):
pass
elif line.startswith(">"):
if quoted is False:
_Append()
cur_bucket = []
quoted = True
elif line.strip():
if quoted is True:
_Append()
cur_bucket = []
quoted = False
cur_bucket.append(line)
_Append()
self.shorttext = self.text.lstrip()[:50].rstrip()
# Grab the first 50 chars from the first non-quoted bucket
for bucket in self.buckets:
if not bucket.quoted:
self.shorttext = bucket.text.lstrip()[:50].rstrip()
break
class Bucket(db.Model):
"""A 'Bucket' of text.
A comment may consist of multiple text buckets, some of which may be
collapsed by default (when they represent quoted text).
NOTE: This entity is never written to the database. See Comment.complete().
"""
# TODO(guido): Flesh this out.
text = db.TextProperty()
quoted = db.BooleanProperty()
### Repositories and Branches ###
class Repository(db.Model):
"""A specific Subversion repository."""
name = db.StringProperty(required=True)
url = db.LinkProperty(required=True)
owner = db.UserProperty(auto_current_user_add=True)
def __str__(self):
return self.name
class Branch(db.Model):
"""A trunk, branch, or a tag in a specific Subversion repository."""
repo = db.ReferenceProperty(Repository, required=True)
# Cache repo.name as repo_name, to speed up set_branch_choices()
# in views.IssueBaseForm.
repo_name = db.StringProperty()
category = db.StringProperty(required=True,
choices=('*trunk*', 'branch', 'tag'))
name = db.StringProperty(required=True)
url = db.LinkProperty(required=True)
owner = db.UserProperty(auto_current_user_add=True)
### Accounts ###
class Account(db.Model):
"""Maps a user or email address to a user-selected nickname, and more.
Nicknames do not have to be unique.
The default nickname is generated from the email address by
stripping the first '@' sign and everything after it. The email
should not be empty nor should it start with '@' (AssertionError
error is raised if either of these happens).
This also holds a list of ids of starred issues. The expectation
that you won't have more than a dozen or so starred issues (a few
hundred in extreme cases) and the memory used up by a list of
integers of that size is very modest, so this is an efficient
solution. (If someone found a use case for having thousands of
starred issues we'd have to think of a different approach.)
"""
user = db.UserProperty(auto_current_user_add=True, required=True)
email = db.EmailProperty(required=True) # key == <email>
nickname = db.StringProperty(required=True)
default_context = db.IntegerProperty(default=engine.DEFAULT_CONTEXT,
choices=CONTEXT_CHOICES)
default_column_width = db.IntegerProperty(default=engine.DEFAULT_COLUMN_WIDTH)
created = db.DateTimeProperty(auto_now_add=True)
modified = db.DateTimeProperty(auto_now=True)
stars = db.ListProperty(int) # Issue ids of all starred issues
fresh = db.BooleanProperty()
uploadpy_hint = db.BooleanProperty(default=True)
notify_by_email = db.BooleanProperty(default=True)
notify_by_chat = db.BooleanProperty(default=False)
# Current user's Account. Updated by middleware.AddUserToRequestMiddleware.
current_user_account = None
lower_email = db.StringProperty()
lower_nickname = db.StringProperty()
xsrf_secret = db.BlobProperty()
# Note that this doesn't get called when doing multi-entity puts.
def put(self):
self.lower_email = str(self.email).lower()
self.lower_nickname = self.nickname.lower()
super(Account, self).put()
@classmethod
def get_account_for_user(cls, user):
"""Get the Account for a user, creating a default one if needed."""
email = user.email()
assert email
key = '<%s>' % email
# Since usually the account already exists, first try getting it
# without the transaction implied by get_or_insert().
account = cls.get_by_key_name(key)
if account is not None:
return account
nickname = cls.create_nickname_for_user(user)
return cls.get_or_insert(key, user=user, email=email, nickname=nickname,
fresh=True)
@classmethod
def create_nickname_for_user(cls, user):
"""Returns a unique nickname for a user."""
name = nickname = user.email().split('@', 1)[0]
next_char = chr(ord(nickname[0].lower())+1)
existing_nicks = [account.lower_nickname
for account in cls.gql(('WHERE lower_nickname >= :1 AND '
'lower_nickname < :2'),
nickname.lower(), next_char)]
suffix = 0
while nickname.lower() in existing_nicks:
suffix += 1
nickname = '%s%d' % (name, suffix)
return nickname
@classmethod
def get_nickname_for_user(cls, user):
"""Get the nickname for a user."""
return cls.get_account_for_user(user).nickname
@classmethod
def get_account_for_email(cls, email):
"""Get the Account for an email address, or return None."""
assert email
key = '<%s>' % email
return cls.get_by_key_name(key)
@classmethod
def get_accounts_for_emails(cls, emails):
"""Get the Accounts for each of a list of email addresses."""
return cls.get_by_key_name(['<%s>' % email for email in emails])
@classmethod
def get_by_key_name(cls, key, **kwds):
"""Override db.Model.get_by_key_name() to use cached value if possible."""
if not kwds and cls.current_user_account is not None:
if key == cls.current_user_account.key().name():
return cls.current_user_account
return super(Account, cls).get_by_key_name(key, **kwds)
@classmethod
def get_multiple_accounts_by_email(cls, emails):
"""Get multiple accounts. Returns a dict by email."""
results = {}
keys = []
for email in emails:
if cls.current_user_account and email == cls.current_user_account.email:
results[email] = cls.current_user_account
else:
keys.append('<%s>' % email)
if keys:
accounts = cls.get_by_key_name(keys)
for account in accounts:
if account is not None:
results[account.email] = account
return results
@classmethod
def get_nickname_for_email(cls, email, default=None):
"""Get the nickname for an email address, possibly a default.
If default is None a generic nickname is computed from the email
address.
Args:
email: email address.
default: If given and no account is found, returned as the default value.
Returns:
Nickname for given email.
"""
account = cls.get_account_for_email(email)
if account is not None and account.nickname:
return account.nickname
if default is not None:
return default
return email.replace('@', '_')
@classmethod
def get_account_for_nickname(cls, nickname):
"""Get the list of Accounts that have this nickname."""
assert nickname
assert '@' not in nickname
return cls.all().filter('lower_nickname =', nickname.lower()).get()
@classmethod
def get_email_for_nickname(cls, nickname):
"""Turn a nickname into an email address.
If the nickname is not unique or does not exist, this returns None.
"""
account = cls.get_account_for_nickname(nickname)
if account is None:
return None
return account.email
def user_has_selected_nickname(self):
"""Return True if the user picked the nickname.
Normally this returns 'not self.fresh', but if that property is
None, we assume that if the created and modified timestamp are
within 2 seconds, the account is fresh (i.e. the user hasn't
selected a nickname yet). We then also update self.fresh, so it
is used as a cache and may even be written back if we're lucky.
"""
if self.fresh is None:
delta = self.created - self.modified
# Simulate delta = abs(delta)
if delta.days < 0:
delta = -delta
self.fresh = (delta.days == 0 and delta.seconds < 2)
return not self.fresh
_drafts = None
@property
def drafts(self):
"""A list of issue ids that have drafts by this user.
This is cached in memcache.
"""
if self._drafts is None:
if self._initialize_drafts():
self._save_drafts()
return self._drafts
def update_drafts(self, issue, have_drafts=None):
"""Update the user's draft status for this issue.
Args:
issue: an Issue instance.
have_drafts: optional bool forcing the draft status. By default,
issue.num_drafts is inspected (which may query the datastore).
The Account is written to the datastore if necessary.
"""
dirty = False
if self._drafts is None:
dirty = self._initialize_drafts()
id = issue.key().id()
if have_drafts is None:
have_drafts = bool(issue.num_drafts) # Beware, this may do a query.
if have_drafts:
if id not in self._drafts:
self._drafts.append(id)
dirty = True
else:
if id in self._drafts:
self._drafts.remove(id)
dirty = True
if dirty:
self._save_drafts()
def _initialize_drafts(self):
"""Initialize self._drafts from scratch.
This mostly exists as a schema conversion utility.
Returns:
True if the user should call self._save_drafts(), False if not.
"""
drafts = memcache.get('user_drafts:' + self.email)
if drafts is not None:
self._drafts = drafts
##logging.info('HIT: %s -> %s', self.email, self._drafts)
return False
# We're looking for the Issue key id. The ancestry of comments goes:
# Issue -> PatchSet -> Patch -> Comment.
issue_ids = set(comment.key().parent().parent().parent().id()
for comment in gql(Comment,
'WHERE author = :1 AND draft = TRUE',
self.user))
self._drafts = list(issue_ids)
##logging.info('INITIALIZED: %s -> %s', self.email, self._drafts)
return True
def _save_drafts(self):
"""Save self._drafts to memcache."""
##logging.info('SAVING: %s -> %s', self.email, self._drafts)
memcache.set('user_drafts:' + self.email, self._drafts, 3600)
def get_xsrf_token(self, offset=0):
"""Return an XSRF token for the current user."""
# This code assumes that
# self.user.email() == users.get_current_user().email()
current_user = users.get_current_user()
if self.user.user_id() != current_user.user_id():
# Mainly for Google Account plus conversion.
logging.info('Updating user_id for %s from %s to %s' % (
self.user.email(), self.user.user_id(), current_user.user_id()))
self.user = current_user
self.put()
if not self.xsrf_secret:
self.xsrf_secret = os.urandom(8)
self.put()
m = md5.new(self.xsrf_secret)
email_str = self.lower_email
if isinstance(email_str, unicode):
email_str = email_str.encode('utf-8')
m.update(self.lower_email)
when = int(time.time()) // 3600 + offset
m.update(str(when))
return m.hexdigest()
| [
[
8,
0,
0.0188,
0.0013,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0225,
0.0013,
0,
0.66,
0.0435,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0238,
0.0013,
0,
0.66... | [
"\"\"\"App Engine data model (schema) definition for Rietveld.\"\"\"",
"import logging",
"import md5",
"import os",
"import re",
"import time",
"from google.appengine.ext import db",
"from google.appengine.api import memcache",
"from google.appengine.api import users",
"import engine",
"import p... |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import md5
from django.contrib.syndication.feeds import Feed
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
import library
import models
class BaseFeed(Feed):
title = 'Code Review'
description = 'Rietveld: Code Review Tool hosted on Google App Engine'
feed_type = Atom1Feed
def link(self):
return reverse('codereview.views.index')
def author_name(self):
return 'rietveld'
def item_guid(self, item):
return 'urn:md5:%s' % (md5.new(str(item.key())).hexdigest())
def item_link(self, item):
if isinstance(item, models.PatchSet):
if item.data is not None:
return reverse('codereview.views.download',
args=[item.issue.key().id(),item.key().id()])
else:
# Patch set is too large, only the splitted diffs are available.
return reverse('codereview.views.show', args=[item.parent_key().id()])
if isinstance(item, models.Message):
return '%s#msg-%s' % (reverse('codereview.views.show',
args=[item.issue.key().id()]),
item.key())
return reverse('codereview.views.show', args=[item.key().id()])
def item_title(self, item):
return 'the title'
def item_author_name(self, item):
if isinstance(item, models.Issue):
return library.get_nickname(item.owner, True)
if isinstance(item, models.PatchSet):
return library.get_nickname(item.issue.owner, True)
if isinstance(item, models.Message):
return library.get_nickname(item.sender, True)
return 'Rietveld'
def item_pubdate(self, item):
if isinstance(item, models.Issue):
return item.modified
if isinstance(item, models.PatchSet):
# Use created, not modified, so that commenting on
# a patch set does not bump its place in the RSS feed.
return item.created
if isinstance(item, models.Message):
return item.date
return None
class BaseUserFeed(BaseFeed):
def get_object(self, bits):
"""Returns the account for the requested user feed.
bits is a list of URL path elements. The first element of this list
should be the user's nickname. A 404 is raised if the list is empty or
has more than one element or if the a user with that nickname
doesn't exist.
"""
if len(bits) != 1:
raise ObjectDoesNotExist
obj = bits[0]
account = models.Account.get_account_for_nickname('%s' % obj)
if account is None:
raise ObjectDoesNotExist
return account
class ReviewsFeed(BaseUserFeed):
title = 'Code Review - All issues I have to review'
def items(self, obj):
return _rss_helper(obj.email, 'closed = FALSE AND reviewers = :1',
use_email=True)
class ClosedFeed(BaseUserFeed):
title = "Code Review - Reviews closed by me"
def items(self, obj):
return _rss_helper(obj.email, 'closed = TRUE AND owner = :1')
class MineFeed(BaseUserFeed):
title = 'Code Review - My issues'
def items(self,obj):
return _rss_helper(obj.email, 'closed = FALSE AND owner = :1')
class AllFeed(BaseFeed):
title = 'Code Review - All issues'
def items(self):
query = models.Issue.gql('WHERE closed = FALSE AND private = FALSE '
'ORDER BY modified DESC')
return query.fetch(RSS_LIMIT)
class OneIssueFeed(BaseFeed):
title = 'Code Review'
def link(self):
return reverse('codereview.views.index')
def get_object(self, bits):
if len(bits) != 1:
raise ObjectDoesNotExist
obj = models.Issue.get_by_id(int(bits[0]))
if obj:
return obj
raise ObjectDoesNotExist
def title(self, obj):
return 'Code review - Issue %d: %s' % (obj.key().id(),obj.subject)
def items(self, obj):
all = list(obj.patchset_set) + list(obj.message_set)
all.sort(key=self.item_pubdate)
return all
### RSS feeds ###
# Maximum number of issues reported by RSS feeds
RSS_LIMIT = 20
def _rss_helper(email, query_string, use_email=False):
account = models.Account.get_account_for_email(email)
if account is None:
issues = []
else:
query = models.Issue.gql('WHERE %s AND private = FALSE '
'ORDER BY modified DESC' % query_string,
use_email and account.email or account.user)
issues = query.fetch(RSS_LIMIT)
return issues
| [
[
1,
0,
0.0904,
0.006,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0964,
0.006,
0,
0.66,
0.0625,
604,
0,
1,
0,
0,
604,
0,
0
],
[
1,
0,
0.1084,
0.006,
0,
0.6... | [
"import datetime",
"import md5",
"from django.contrib.syndication.feeds import Feed",
"from django.core.exceptions import ObjectDoesNotExist",
"from django.core.urlresolvers import reverse",
"from django.utils.feedgenerator import Atom1Feed",
"import library",
"import models",
"class BaseFeed(Feed):... |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Intra-region diff utilities.
Intra-region diff highlights the blocks of code which have been changed or
deleted within a region. So instead of highlighting the whole region marked as
changed, the user can see what exactly was changed within that region.
Terminology:
'region' is a list of consecutive code lines.
'word' is the unit of intra-region diff. Its definition is arbitrary based on
what we think as to be a good unit of difference between two regions.
'block' is a small section of code within a region. It can span multiple
lines. There can be multiple non overlapping blocks within a region. A block
can potentially span the whole region.
The blocks have two representations. One is of the format (offset1, offset2,
size) which is returned by the SequenceMatcher to indicate a match of
length 'size' starting at offset1 in the first/old line and starting at offset2
in the second/new line. We convert this representation to a pair of tuples i.e.
(offset1, size) and (offset2, size) for rendering each side of the diff
separately. This latter representation is also more efficient for doing
compaction of adjacent blocks which reduces the size of the HTML markup. See
CompactBlocks for more details.
SequenceMatcher always returns one special matching block at the end with
contents (len(line1), len(line2), 0). We retain this special block as it
simplifies for loops in rendering the last non-matching block. All functions
which deal with the sequence of blocks assume presence of the special block at
the end of the sequence and retain it.
"""
import cgi
import difflib
import re
# Tag to begin a diff chunk.
BEGIN_TAG = "<span class=\"%s\">"
# Tag to end a diff block.
END_TAG = "</span>"
# Tag used for visual tab indication.
TAB_TAG = "<span class=\"visualtab\">»</span>"
# Color scheme to govern the display properties of diff blocks and matching
# blocks. Each value e.g. 'oldlight' corresponds to a CSS style.
COLOR_SCHEME = {
'old': {
'match': 'oldlight',
'diff': 'olddark',
'bckgrnd': 'oldlight',
},
'new': {
'match': 'newlight',
'diff': 'newdark',
'bckgrnd': 'newlight',
},
'oldmove': {
'match': 'movelight',
'diff': 'oldmovedark',
'bckgrnd': 'movelight'
},
'newmove': {
'match': 'newlight',
'diff': 'newdark',
'bckgrnd': 'newlight'
},
}
# Regular expressions to tokenize lines. Default is 'd'.
EXPRS = {
'a': r'(\w+|[^\w\s]+|\s+)',
'b': r'([A-Za-z0-9]+|[^A-Za-z0-9])',
'c': r'([A-Za-z0-9_]+|[^A-Za-z0-9_])',
'd': r'([^\W_]+|[\W_])',
}
# Maximum total characters in old and new lines for doing intra-region diffs.
# Intra-region diff for larger regions is hard to comprehend and wastes CPU
# time.
MAX_TOTAL_LEN = 10000
def _ExpandTabs(text, column, tabsize, mark_tabs=False):
"""Expand tab characters in a string into spaces.
Args:
text: a string containing tab characters.
column: the initial column for the first character in text
tabsize: tab stops occur at columns that are multiples of tabsize
mark_tabs: if true, leave a tab character as the first character
of the expansion, so that the caller can find where
the tabs were.
Note that calling _ExpandTabs with mark_tabs=True is not idempotent.
"""
expanded = ""
while True:
tabpos = text.find("\t")
if tabpos < 0:
break
fillwidth = tabsize - (tabpos + column) % tabsize
column += tabpos + fillwidth
if mark_tabs:
fill = "\t" + " " * (fillwidth - 1)
else:
fill = " " * fillwidth
expanded += text[0:tabpos] + fill
text = text[tabpos+1:]
return expanded + text
def Break(text, offset=0, limit=80, brk="\n ", tabsize=8, mark_tabs=False):
"""Break text into lines.
Break text, which begins at column offset, each time it reaches
column limit.
To break the text, insert brk, which does not count toward
the column count of the next line and is assumed to be valid HTML.
During the text breaking process, replaces tabs with spaces up
to the next column that is a multiple of tabsize.
If mark_tabs is true, replace the first space of each expanded
tab with TAB_TAG.
Input and output are assumed to be in UTF-8; the computation is done
in Unicode. (Still not good enough if zero-width characters are
present.) If the input is not valid UTF-8, then the encoding is
passed through, potentially breaking up multi-byte characters.
We pass the line through cgi.escape before returning it.
A trailing newline is always stripped from the input first.
"""
assert tabsize > 0, tabsize
if text.endswith("\n"):
text = text[:-1]
try:
text = unicode(text, "utf-8")
except:
pass
# Expand all tabs.
# If mark_tabs is true, we retain one \t character as a marker during
# expansion so that we later replace it with an HTML snippet.
text = _ExpandTabs(text, offset, tabsize, mark_tabs)
# Perform wrapping.
if len(text) > limit - offset:
parts, text = [text[0:limit-offset]], text[limit-offset:]
while len(text) > limit:
parts.append(text[0:limit])
text = text[limit:]
parts.append(text);
text = brk.join([cgi.escape(p) for p in parts])
else:
text = cgi.escape(text)
# Colorize tab markers
text = text.replace("\t", TAB_TAG)
if isinstance(text, unicode):
return text.encode("utf-8", "replace")
return text
def CompactBlocks(blocks):
"""Compacts adjacent code blocks.
In many cases 2 adjacent blocks can be merged into one. This allows
to do some further processing on those blocks.
Args:
blocks: [(offset1, size), ...]
Returns:
A list with the same structure as the input with adjacent blocks
merged. However, the last block (which is always assumed to have
a zero size) is never merged. For example, the input
[(0, 2), (2, 8), (10, 5), (15, 0)]
will produce the output [(0, 15), (15, 0)].
"""
if len(blocks) == 1:
return blocks
result = [blocks[0]]
for block in blocks[1:-1]:
last_start, last_len = result[-1]
curr_start, curr_len = block
if last_start + last_len == curr_start:
result[-1] = last_start, last_len + curr_len
else:
result.append(block)
result.append(blocks[-1])
return result
def FilterBlocks(blocks, filter_func):
"""Gets rid of any blocks if filter_func evaluates false for them.
Args:
blocks: [(offset1, offset2, size), ...]; must have at least 1 entry
filter_func: a boolean function taking a single argument of the form
(offset1, offset2, size)
Returns:
A list with the same structure with entries for which filter_func()
returns false removed. However, the last block is always included.
"""
# We retain the 'special' block at the end.
res = [b for b in blocks[:-1] if filter_func(b)]
res.append(blocks[-1])
return res
def GetDiffParams(expr='d', min_match_ratio=0.6, min_match_size=2, dbg=False):
"""Returns a tuple of various parameters which affect intra region diffs.
Args:
expr: regular expression id to use to identify 'words' in the intra region
diff
min_match_ratio: minimum similarity between regions to qualify for intra
region diff
min_match_size: the smallest matching block size to use. Blocks smaller
than this are ignored.
dbg: to turn on generation of debugging information for the diff
Returns:
4 tuple (expr, min_match_ratio, min_match_size, dbg) that can be used to
customize diff. It can be passed to functions like WordDiff and
IntraLineDiff.
"""
assert expr in EXPRS
assert min_match_size in xrange(1, 5)
assert min_match_ratio > 0.0 and min_match_ratio < 1.0
return (expr, min_match_ratio, min_match_size, dbg)
def CanDoIRDiff(old_lines, new_lines):
"""Tells if it would be worth computing the intra region diff.
Calculating IR diff is costly and is usually helpful only for small regions.
We use a heuristic that if the total number of characters is more than a
certain threshold then we assume it is not worth computing the IR diff.
Args:
old_lines: an array of strings containing old text
new_lines: an array of strings containing new text
Returns:
True if we think it is worth computing IR diff for the region defined
by old_lines and new_lines, False otherwise.
TODO: Let GetDiffParams handle MAX_TOTAL_LEN param also.
"""
total_chars = (sum(len(line) for line in old_lines) +
sum(len(line) for line in new_lines))
return total_chars <= MAX_TOTAL_LEN
def WordDiff(line1, line2, diff_params):
"""Returns blocks with positions indiciating word level diffs.
Args:
line1: string representing the left part of the diff
line2: string representing the right part of the diff
diff_params: return value of GetDiffParams
Returns:
A tuple (blocks, ratio) where:
blocks: [(offset1, offset2, size), ...] such that
line1[offset1:offset1+size] == line2[offset2:offset2+size]
and the last block is always (len(line1), len(line2), 0)
ratio: a float giving the diff ratio computed by SequenceMatcher.
"""
match_expr, min_match_ratio, min_match_size, dbg = diff_params
exp = EXPRS[match_expr]
# Strings may have been left undecoded up to now. Assume UTF-8.
try:
line1 = unicode(line1, "utf8")
except:
pass
try:
line2 = unicode(line2, "utf8")
except:
pass
a = re.findall(exp, line1, re.U)
b = re.findall(exp, line2, re.U)
s = difflib.SequenceMatcher(None, a, b)
matching_blocks = s.get_matching_blocks()
ratio = s.ratio()
# Don't show intra region diffs if both lines are too different and there is
# more than one block of difference. If there is only one change then we
# still show the intra region diff regardless of how different the blocks
# are.
# Note: We compare len(matching_blocks) with 3 because one block of change
# results in 2 matching blocks. We add the one special block and we get 3
# matching blocks per one block of change.
if ratio < min_match_ratio and len(matching_blocks) > 3:
return ([(0, 0, 0)], ratio)
# For now convert to character level blocks because we already have
# the code to deal with folding across lines for character blocks.
# Create arrays lena an lenb which have cumulative word lengths
# corresponding to word positions in a and b
lena = []
last = 0
for w in a:
lena.append(last)
last += len(w)
lenb = []
last = 0
for w in b:
lenb.append(last)
last += len(w)
lena.append(len(line1))
lenb.append(len(line2))
# Convert to character blocks
blocks = []
for s1, s2, blen in matching_blocks[:-1]:
apos = lena[s1]
bpos = lenb[s2]
block_len = lena[s1+blen] - apos
blocks.append((apos, bpos, block_len))
# Recreate the special block.
blocks.append((len(line1), len(line2), 0))
# Filter any matching blocks which are smaller than the desired threshold.
# We don't remove matching blocks with only a newline character as doing so
# results in showing the matching newline character as non matching which
# doesn't look good.
blocks = FilterBlocks(blocks, lambda b: (b[2] >= min_match_size or
line1[b[0]:b[0]+b[2]] == '\n'))
return (blocks, ratio)
def IntraLineDiff(line1, line2, diff_params, diff_func=WordDiff):
"""Computes intraline diff blocks.
Args:
line1: string representing the left part of the diff
line2: string representing the right part of the diff
diff_params: return value of GetDiffParams
diff_func: a function whose signature matches that of WordDiff() above
Returns:
A tuple of (blocks1, blocks2) corresponding to line1 and line2.
Each element of the tuple is an array of (start_pos, length)
tuples denoting a diff block.
"""
blocks, ratio = diff_func(line1, line2, diff_params)
blocks1 = [(start1, length) for (start1, start2, length) in blocks]
blocks2 = [(start2, length) for (start1, start2, length) in blocks]
return (blocks1, blocks2, ratio)
def DumpDiff(blocks, line1, line2):
"""Helper function to debug diff related problems.
Args:
blocks: [(offset1, offset2, size), ...]
line1: string representing the left part of the diff
line2: string representing the right part of the diff
"""
for offset1, offset2, size in blocks:
print offset1, offset2, size
print offset1, size, ": ", line1[offset1:offset1+size]
print offset2, size, ": ", line2[offset2:offset2+size]
def RenderIntraLineDiff(blocks, line, tag, dbg_info=None, limit=80, indent=5,
tabsize=8, mark_tabs=False):
"""Renders the diff blocks returned by IntraLineDiff function.
Args:
blocks: [(start_pos, size), ...]
line: line of code on which the blocks are to be rendered.
tag: 'new' or 'old' to control the color scheme.
dbg_info: a string that holds debugging informaion header. Debug
information is rendered only if dbg_info is not None.
limit: folding limit to be passed to the Fold function.
indent: indentation size to be passed to the Fold function.
tabsize: tab stops occur at columns that are multiples of tabsize
mark_tabs: if True, mark the first character of each expanded tab visually
Returns:
A tuple of two elements. First element is the rendered version of
the input 'line'. Second element tells if the line has a matching
newline character.
"""
res = ""
prev_start, prev_len = 0, 0
has_newline = False
debug_info = dbg_info
if dbg_info:
debug_info += "\nBlock Count: %d\nBlocks: " % (len(blocks) - 1)
for curr_start, curr_len in blocks:
if dbg_info and curr_len > 0:
debug_info += Fold("\n(%d, %d):|%s|" %
(curr_start, curr_len,
line[curr_start:curr_start+curr_len]),
limit, indent, tabsize, mark_tabs)
res += FoldBlock(line, prev_start + prev_len, curr_start, limit, indent,
tag, 'diff', tabsize, mark_tabs)
res += FoldBlock(line, curr_start, curr_start + curr_len, limit, indent,
tag, 'match', tabsize, mark_tabs)
# TODO: This test should be out of loop rather than inside. Once we
# filter out some junk from blocks (e.g. some empty blocks) we should do
# this test only on the last matching block.
if line[curr_start:curr_start+curr_len].endswith('\n'):
has_newline = True
prev_start, prev_len = curr_start, curr_len
return (res, has_newline, debug_info)
def FoldBlock(src, start, end, limit, indent, tag, btype, tabsize=8,
mark_tabs=False):
"""Folds and renders a block.
Args:
src: line of code
start: starting position of the block within 'src'.
end: ending position of the block within 'src'.
limit: folding limit
indent: indentation to use for folding.
tag: 'new' or 'old' to control the color scheme.
btype: block type i.e. 'match' or 'diff' to control the color schme.
tabsize: tab stops occur at columns that are multiples of tabsize
mark_tabs: if True, mark the first character of each expanded tab visually
Returns:
A string representing the rendered block.
"""
text = src[start:end]
# We ignore newlines because we do newline management ourselves.
# Any other new lines with at the end will be stripped off by the Fold
# method.
if start >= end or text == '\n':
return ""
fbegin, lend, nl_plus_indent = GetTags(tag, btype, indent)
# 'bol' is beginning of line.
# The text we care about begins at byte offset start
# but if there are tabs it will have a larger column
# offset. Use len(_ExpandTabs()) to find out how many
# columns the starting prefix occupies.
offset_from_bol = len(_ExpandTabs(src[0:start], 0, tabsize)) % limit
text = Break(text, offset_from_bol, limit, lend + nl_plus_indent + fbegin, tabsize, mark_tabs)
if text:
text = fbegin + text + lend
# If this is the first block of the line and this is not the first line then
# insert newline + indent.
if offset_from_bol == 0 and not start == 0:
text = nl_plus_indent + text
return text
def GetTags(tag, btype, indent):
"""Returns various tags for rendering diff blocks.
Args:
tag: a key from COLOR_SCHEME
btype: 'match' or 'diff'
indent: indentation to use
Returns
A 3 tuple (begin_tag, end_tag, formatted_indent_block)
"""
assert tag in COLOR_SCHEME
assert btype in ['match', 'diff']
fbegin = BEGIN_TAG % COLOR_SCHEME[tag][btype]
bbegin = BEGIN_TAG % COLOR_SCHEME[tag]['bckgrnd']
lend = END_TAG
nl_plus_indent = '\n'
if indent > 0:
nl_plus_indent += bbegin + cgi.escape(" "*indent) + lend
return fbegin, lend, nl_plus_indent
def ConvertToSingleLine(lines):
"""Transforms a sequence of strings into a single line.
Returns the state that can be used to reconstruct the original lines with
the newline separators placed at the original place.
Args:
lines: sequence of strings
Returns:
Returns (single_line, state) tuple. 'state' shouldn't be modified by the
caller. It is only used to pass to other functions which will do certain
operations on this state.
'state' is an array containing a dictionary for each item in lines. Each
dictionary has two elements 'pos' and 'blocks'. 'pos' is the end position
of each line in the final converted string. 'blocks' is an array of blocks
for each line of code. These blocks are added using MarkBlock function.
"""
state = []
total_length = 0
for l in lines:
total_length += len(l)
# TODO: Use a tuple instead.
state.append({'pos': total_length, # the line split point
'blocks': [], # blocks which belong to this line
})
result = "".join(lines)
assert len(state) == len(lines)
return (result, state)
def MarkBlock(state, begin, end):
"""Marks a block on a region such that it doesn't cross line boundaries.
It is an operation that can be performed on the single line which was
returned by the ConvertToSingleLine function. This operation marks arbitrary
block [begin,end) on the text. It also ensures that if [begin,end) crosses
line boundaries in the original region then it splits the section up in 2 or
more blocks such that no block crosses the boundaries.
Args:
state: the state returned by ConvertToSingleLine function. The state
contained is modified by this function.
begin: Beginning of the block.
end: End of the block (exclusive).
Returns:
None.
"""
# TODO: Make sure already existing blocks don't overlap
if begin == end:
return
last_pos = 0
for entry in state:
pos = entry['pos']
if begin >= last_pos and begin < pos:
if end < pos:
# block doesn't cross any line boundary
entry['blocks'].append((begin, end))
else:
# block crosses the line boundary
entry['blocks'].append((begin, pos))
MarkBlock(state, pos, end)
break
last_pos = pos
def GetBlocks(state):
"""Returns all the blocks corresponding to the lines in the region.
Args:
state: the state returned by ConvertToSingleLine().
Returns:
An array of [(start_pos, length), ..] with an entry for each line in the
region.
"""
result = []
last_pos = 0
for entry in state:
pos = entry['pos']
# Calculate block start points from the beginning of individual lines.
blocks = [(s[0]-last_pos, s[1]-s[0]) for s in entry['blocks']]
# Add one end marker block.
blocks.append((pos-last_pos, 0))
result.append(blocks)
last_pos = pos
return result
def IntraRegionDiff(old_lines, new_lines, diff_params):
"""Computes intra region diff.
Args:
old_lines: array of strings
new_lines: array of strings
diff_params: return value of GetDiffParams
Returns:
A tuple (old_blocks, new_blocks) containing matching blocks for old and new
lines.
"""
old_line, old_state = ConvertToSingleLine(old_lines)
new_line, new_state = ConvertToSingleLine(new_lines)
old_blocks, new_blocks, ratio = IntraLineDiff(old_line, new_line, diff_params)
for begin, length in old_blocks:
MarkBlock(old_state, begin, begin+length)
old_blocks = GetBlocks(old_state)
for begin, length in new_blocks:
MarkBlock(new_state, begin, begin+length)
new_blocks = GetBlocks(new_state)
return (old_blocks, new_blocks, ratio)
def NormalizeBlocks(blocks, line):
"""Normalizes block representation of an intra line diff.
One diff can have multiple representations. Some times the diff returned by
the difflib for similar text sections is different even within same region.
For example if 2 already indented lines were indented with one additional
space character, the difflib may return the non matching space character to
be any of the already existing spaces. So one line may show non matching
space character as the first space character and the second line may show it
to be the last space character. This is sometimes confusing. This is the
side effect of the new regular expression we are using in WordDiff for
identifying indvidual words. This regular expression ('b') treats a sequence
of punctuation and whitespace characters as individual characters. It has
some visual advantages for showing a character level punctuation change as
one character change rather than a group of character change.
Making the normalization too generic can have performance implications. So
this implementation of normalize blocks intends to handle only one case.
Let's say S represents the space character and () marks a matching block.
Then the normalize operation will do following:
SSSS(SS)(ABCD) => SSSS(SS)(ABCD)
(SS)SSSS(ABCD) => SSSS(SS)(ABCD)
(SSSS)SS(ABCD) => SS(SSSS)(ABCD)
and so on..
Args:
blocks: An array of (offset, len) tuples defined on 'line'. These blocks
mark the matching areas. Anything between these matching blocks is
considered non-matching.
line: The text string on which the blocks are defined.
Returns:
An array of (offset, len) tuples representing the same diff but in
normalized form.
"""
result = []
prev_start, prev_len = blocks[0]
for curr_start, curr_len in blocks[1:]:
# Note: nm_ is a prefix for non matching and m_ is a prefix for matching.
m_len, nm_len = prev_len, curr_start - (prev_start+prev_len)
# This if condition checks if matching and non matching parts are greater
# than zero length and are comprised of spaces ONLY. The last condition
# deals with most of the observed cases of strange diffs.
# Note: curr_start - prev_start == m_l + nm_l
# So line[prev_start:curr_start] == matching_part + non_matching_part.
text = line[prev_start:curr_start]
if m_len > 0 and nm_len > 0 and text == ' ' * len(text):
# Move the matching block towards the end i.e. normalize.
result.append((prev_start + nm_len, m_len))
else:
# Keep the existing matching block.
result.append((prev_start, prev_len))
prev_start, prev_len = curr_start, curr_len
result.append(blocks[-1])
assert len(result) == len(blocks)
return result
def RenderIntraRegionDiff(lines, diff_blocks, tag, ratio, limit=80, indent=5,
tabsize=8, mark_tabs=False, dbg=False):
"""Renders intra region diff for one side.
Args:
lines: list of strings representing source code in the region
diff_blocks: blocks that were returned for this region by IntraRegionDiff()
tag: 'new' or 'old'
ratio: similarity ratio returned by the diff computing function
limit: folding limit
indent: indentation size
tabsize: tab stops occur at columns that are multiples of tabsize
mark_tabs: if True, mark the first character of each expanded tab visually
dbg: indicates if debug information should be rendered
Returns:
A list of strings representing the rendered version of each item in input
'lines'.
"""
result = []
dbg_info = None
if dbg:
dbg_info = 'Ratio: %.1f' % ratio
for line, blocks in zip(lines, diff_blocks):
blocks = NormalizeBlocks(blocks, line)
blocks = CompactBlocks(blocks)
diff = RenderIntraLineDiff(blocks,
line,
tag,
dbg_info=dbg_info,
limit=limit,
indent=indent,
tabsize=tabsize,
mark_tabs=mark_tabs)
result.append(diff)
assert len(result) == len(lines)
return result
| [
[
8,
0,
0.0417,
0.0417,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0647,
0.0014,
0,
0.66,
0.037,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.0662,
0.0014,
0,
0.66,... | [
"\"\"\"Intra-region diff utilities.\n\nIntra-region diff highlights the blocks of code which have been changed or\ndeleted within a region. So instead of highlighting the whole region marked as\nchanged, the user can see what exactly was changed within that region.\n\nTerminology:\n 'region' is a list of consecuti... |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility to read and apply a unified diff without forking patch(1).
For a discussion of the unified diff format, see my blog on Artima:
http://www.artima.com/weblogs/viewpost.jsp?thread=164293
"""
import difflib
import logging
import re
import sys
_CHUNK_RE = re.compile(r"""
@@
\s+
-
(?: (\d+) (?: , (\d+) )?)
\s+
\+
(?: (\d+) (?: , (\d+) )?)
\s+
@@
""", re.VERBOSE)
def PatchLines(old_lines, patch_lines, name="<patch>"):
"""Patches the old_lines with patches read from patch_lines.
This only reads unified diffs. The header lines are ignored.
Yields (tag, old, new) tuples where old and new are lists of lines.
The tag can either start with "error" or be a tag from difflib: "equal",
"insert", "delete", "replace". After "error" is yielded, no more
tuples are yielded. It is possible that consecutive "equal" tuples
are yielded.
"""
chunks = ParsePatchToChunks(patch_lines, name)
if chunks is None:
return iter([("error: ParsePatchToChunks failed", [], [])])
return PatchChunks(old_lines, chunks)
def PatchChunks(old_lines, chunks):
"""Patche old_lines with chunks.
Yields (tag, old, new) tuples where old and new are lists of lines.
The tag can either start with "error" or be a tag from difflib: "equal",
"insert", "delete", "replace". After "error" is yielded, no more
tuples are yielded. It is possible that consecutive "equal" tuples
are yielded.
"""
if not chunks:
# The patch is a no-op
yield ("equal", old_lines, old_lines)
return
old_pos = 0
for (old_i, old_j), (new_i, new_j), old_chunk, new_chunk in chunks:
eq = old_lines[old_pos:old_i]
if eq:
yield "equal", eq, eq
old_pos = old_i
# Check that the patch matches the target file
if old_lines[old_i:old_j] != old_chunk:
logging.warn("mismatch:%s.%s.", old_lines[old_i:old_j], old_chunk)
yield ("error: old chunk mismatch", old_lines[old_i:old_j], old_chunk)
return
# TODO(guido): ParsePatch knows the diff details, but throws the info away
sm = difflib.SequenceMatcher(None, old_chunk, new_chunk)
for tag, i1, i2, j1, j2 in sm.get_opcodes():
yield tag, old_chunk[i1:i2], new_chunk[j1:j2]
old_pos = old_j
# Copy the final matching chunk if any.
eq = old_lines[old_pos:]
if eq:
yield ("equal", eq, eq)
def ParseRevision(lines):
"""Parse the revision number out of the raw lines of the patch.
Returns 0 (new file) if no revision number was found.
"""
for line in lines[:10]:
if line.startswith('@'):
break
m = re.match(r'---\s.*\(.*\s(\d+)\)\s*$', line)
if m:
return int(m.group(1))
return 0
_NO_NEWLINE_MESSAGE = "\\ No newline at end of file"
def ParsePatchToChunks(lines, name="<patch>"):
"""Parses a patch from a list of lines.
Return a list of chunks, where each chunk is a tuple:
old_range, new_range, old_lines, new_lines
Returns a list of chunks (possibly empty); or None if there's a problem.
"""
lineno = 0
raw_chunk = []
chunks = []
old_range = new_range = None
old_last = new_last = 0
in_prelude = True
for line in lines:
lineno += 1
if in_prelude:
# Skip leading lines until after we've seen one starting with '+++'
if line.startswith("+++"):
in_prelude = False
continue
match = _CHUNK_RE.match(line)
if match:
if raw_chunk:
# Process the lines in the previous chunk
old_chunk = []
new_chunk = []
for tag, rest in raw_chunk:
if tag in (" ", "-"):
old_chunk.append(rest)
if tag in (" ", "+"):
new_chunk.append(rest)
# Check consistency
old_i, old_j = old_range
new_i, new_j = new_range
if len(old_chunk) != old_j - old_i or len(new_chunk) != new_j - new_i:
logging.warn("%s:%s: previous chunk has incorrect length",
name, lineno)
return None
chunks.append((old_range, new_range, old_chunk, new_chunk))
raw_chunk = []
# Parse the @@ header
old_ln, old_n, new_ln, new_n = match.groups()
old_ln, old_n, new_ln, new_n = map(long,
(old_ln, old_n or 1,
new_ln, new_n or 1))
# Convert the numbers to list indices we can use
if old_n == 0:
old_i = old_ln
else:
old_i = old_ln - 1
old_j = old_i + old_n
old_range = old_i, old_j
if new_n == 0:
new_i = new_ln
else:
new_i = new_ln - 1
new_j =new_i + new_n
new_range = new_i, new_j
# Check header consistency with previous header
if old_i < old_last or new_i < new_last:
logging.warn("%s:%s: chunk header out of order: %r",
name, lineno, line)
return None
if old_i - old_last != new_i - new_last:
logging.warn("%s:%s: inconsistent chunk header: %r",
name, lineno, line)
return None
old_last = old_j
new_last = new_j
else:
tag, rest = line[0], line[1:]
if tag in (" ", "-", "+"):
raw_chunk.append((tag, rest))
elif line.startswith(_NO_NEWLINE_MESSAGE):
# TODO(guido): need to check that no more lines follow for this file
if raw_chunk:
last_tag, last_rest = raw_chunk[-1]
if last_rest.endswith("\n"):
raw_chunk[-1] = (last_tag, last_rest[:-1])
else:
# Only log if it's a non-blank line. Blank lines we see a lot.
if line and line.strip():
logging.warn("%s:%d: indecypherable input: %r", name, lineno, line)
if chunks or raw_chunk:
break # Trailing garbage isn't so bad
return None
if raw_chunk:
# Process the lines in the last chunk
old_chunk = []
new_chunk = []
for tag, rest in raw_chunk:
if tag in (" ", "-"):
old_chunk.append(rest)
if tag in (" ", "+"):
new_chunk.append(rest)
# Check consistency
old_i, old_j = old_range
new_i, new_j = new_range
if len(old_chunk) != old_j - old_i or len(new_chunk) != new_j - new_i:
print >>sys.stderr, ("%s:%s: last chunk has incorrect length" %
(name, lineno))
return None
chunks.append((old_range, new_range, old_chunk, new_chunk))
raw_chunk = []
return chunks
def ParsePatchToLines(lines):
"""Parses a patch from a list of lines.
Returns None on error, otherwise a list of 3-tuples:
(old_line_no, new_line_no, line)
A line number can be 0 if it doesn't exist in the old/new file.
"""
# TODO: can we share some of this code with ParsePatchToChunks?
result = []
in_prelude = True
for line in lines:
if in_prelude:
result.append((0, 0, line))
# Skip leading lines until after we've seen one starting with '+++'
if line.startswith("+++"):
in_prelude = False
elif line.startswith("@"):
result.append((0, 0, line))
match = _CHUNK_RE.match(line)
if not match:
logging.warn("ParsePatchToLines match failed on %s", line)
return None
old_ln = int(match.groups()[0])
new_ln = int(match.groups()[2])
else:
if line[0] == "-":
result.append((old_ln, 0, line))
old_ln += 1
elif line[0] == "+":
result.append((0, new_ln, line))
new_ln += 1
elif line[0] == " ":
result.append((old_ln, new_ln, line))
old_ln += 1
new_ln += 1
elif line.startswith(_NO_NEWLINE_MESSAGE):
continue
else: # Something else, could be property changes etc.
result.append((0, 0, line))
return result
| [
[
8,
0,
0.0656,
0.0193,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0811,
0.0039,
0,
0.66,
0.0909,
866,
0,
1,
0,
0,
866,
0,
0
],
[
1,
0,
0.0849,
0.0039,
0,
0.66... | [
"\"\"\"Utility to read and apply a unified diff without forking patch(1).\n\nFor a discussion of the unified diff format, see my blog on Artima:\nhttp://www.artima.com/weblogs/viewpost.jsp?thread=164293\n\"\"\"",
"import difflib",
"import logging",
"import re",
"import sys",
"_CHUNK_RE = re.compile(r\"\"\... |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""URL mappings for the codereview package."""
# NOTE: Must import *, since Django looks for things here, e.g. handler500.
from django.conf.urls.defaults import *
import django.views.defaults
from codereview import feeds
urlpatterns = patterns(
'codereview.views',
(r'^$', 'index'),
(r'^all$', 'all'),
(r'^mine$', 'mine'),
(r'^starred$', 'starred'),
(r'^new$', 'new'),
(r'^upload$', 'upload'),
(r'^(\d+)$', 'show', {}, 'show_bare_issue_number'),
(r'^(\d+)/(show)?$', 'show'),
(r'^(\d+)/add$', 'add'),
(r'^(\d+)/edit$', 'edit'),
(r'^(\d+)/delete$', 'delete'),
(r'^(\d+)/close$', 'close'),
(r'^(\d+)/mail$', 'mailissue'),
(r'^(\d+)/publish$', 'publish'),
(r'^download/issue(\d+)_(\d+)\.diff', 'download'),
(r'^download/issue(\d+)_(\d+)_(\d+)\.diff', 'download_patch'),
(r'^(\d+)/patch/(\d+)/(\d+)$', 'patch'),
(r'^(\d+)/image/(\d+)/(\d+)/(\d+)$', 'image'),
(r'^(\d+)/diff/(\d+)/(.+)$', 'diff'),
(r'^(\d+)/diff2/(\d+):(\d+)/(.+)$', 'diff2'),
(r'^(\d+)/diff_skipped_lines/(\d+)/(\d+)/(\d+)/(\d+)/([tba])/(\d+)$',
'diff_skipped_lines'),
(r'^(\d+)/diff_skipped_lines/(\d+)/(\d+)/$',
django.views.defaults.page_not_found, {}, 'diff_skipped_lines_prefix'),
(r'^(\d+)/diff2_skipped_lines/(\d+):(\d+)/(\d+)/(\d+)/(\d+)/([tba])/(\d+)$',
'diff2_skipped_lines'),
(r'^(\d+)/diff2_skipped_lines/(\d+):(\d+)/(\d+)/$',
django.views.defaults.page_not_found, {}, 'diff2_skipped_lines_prefix'),
(r'^(\d+)/upload_content/(\d+)/(\d+)$', 'upload_content'),
(r'^(\d+)/upload_patch/(\d+)$', 'upload_patch'),
(r'^(\d+)/description$', 'description'),
(r'^(\d+)/fields', 'fields'),
(r'^(\d+)/star$', 'star'),
(r'^(\d+)/unstar$', 'unstar'),
(r'^(\d+)/draft_message$', 'draft_message'),
(r'^api/(\d+)/?$', 'api_issue'),
(r'^api/(\d+)/(\d+)/?$', 'api_patchset'),
(r'^user/(.+)$', 'show_user'),
(r'^inline_draft$', 'inline_draft'),
(r'^repos$', 'repos'),
(r'^repo_new$', 'repo_new'),
(r'^repo_init$', 'repo_init'),
(r'^branch_new/(\d+)$', 'branch_new'),
(r'^branch_edit/(\d+)$', 'branch_edit'),
(r'^branch_delete/(\d+)$', 'branch_delete'),
(r'^settings$', 'settings'),
(r'^account_delete$', 'account_delete'),
(r'^user_popup/(.+)$', 'user_popup'),
(r'^(\d+)/patchset/(\d+)$', 'patchset'),
(r'^(\d+)/patchset/(\d+)/delete$', 'delete_patchset'),
(r'^account$', 'account'),
(r'^use_uploadpy$', 'use_uploadpy'),
(r'^_ah/xmpp/message/chat/', 'incoming_chat'),
(r'^_ah/mail/(.*)', 'incoming_mail'),
(r'^xsrf_token$', 'xsrf_token'),
# patching upload.py on the fly
(r'^static/upload.py$', 'customized_upload_py'),
(r'^search$', 'search'),
)
feed_dict = {
'reviews': feeds.ReviewsFeed,
'closed': feeds.ClosedFeed,
'mine' : feeds.MineFeed,
'all': feeds.AllFeed,
'issue' : feeds.OneIssueFeed,
}
urlpatterns += patterns(
'',
(r'^rss/(?P<url>.*)$', 'django.contrib.syndication.views.feed',
{'feed_dict': feed_dict}),
)
| [
[
8,
0,
0.1546,
0.0103,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1856,
0.0103,
0,
0.66,
0.2,
341,
0,
1,
0,
0,
341,
0,
0
],
[
1,
0,
0.1959,
0.0103,
0,
0.66,
... | [
"\"\"\"URL mappings for the codereview package.\"\"\"",
"from django.conf.urls.defaults import *",
"import django.views.defaults",
"from codereview import feeds",
"urlpatterns = patterns(\n 'codereview.views',\n (r'^$', 'index'),\n (r'^all$', 'all'),\n (r'^mine$', 'mine'),\n (r'^starred$', 's... |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Custom middleware. Some of this may be generally useful."""
from google.appengine.api import users
import models
class AddUserToRequestMiddleware(object):
"""Add a user object and a user_is_admin flag to each request."""
def process_request(self, request):
request.user = users.get_current_user()
request.user_is_admin = users.is_current_user_admin()
# Update the cached value of the current user's Account
account = None
if request.user is not None:
account = models.Account.get_account_for_user(request.user)
models.Account.current_user_account = account
| [
[
8,
0,
0.4545,
0.0303,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5152,
0.0303,
0,
0.66,
0.3333,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.5758,
0.0303,
0,
0.66... | [
"\"\"\"Custom middleware. Some of this may be generally useful.\"\"\"",
"from google.appengine.api import users",
"import models",
"class AddUserToRequestMiddleware(object):\n \"\"\"Add a user object and a user_is_admin flag to each request.\"\"\"\n\n def process_request(self, request):\n request.user =... |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Django template library for Rietveld."""
import cgi
import logging
from google.appengine.api import memcache
from google.appengine.api import users
import django.template
import django.utils.safestring
from django.core.urlresolvers import reverse
import models
register = django.template.Library()
user_cache = {}
def get_links_for_users(user_emails):
"""Return a dictionary of email->link to user page and fill caches."""
link_dict = {}
remaining_emails = set(user_emails)
# initialize with email usernames
for email in remaining_emails:
nick = email.split('@', 1)[0]
link_dict[email] = cgi.escape(nick)
# look in the local cache
for email in remaining_emails:
if email in user_cache:
link_dict[email] = user_cache[email]
remaining_emails = remaining_emails - set(user_cache)
if not remaining_emails:
return link_dict
# then look in memcache
memcache_results = memcache.get_multi(remaining_emails,
key_prefix="show_user:")
for email in memcache_results:
link_dict[email] = memcache_results[email]
user_cache[email] = memcache_results[email]
remaining_emails = remaining_emails - set(memcache_results)
if not remaining_emails:
return link_dict
# and finally hit the datastore
accounts = models.Account.get_accounts_for_emails(remaining_emails)
for account in accounts:
if account and account.user_has_selected_nickname:
ret = ('<a href="%s" onMouseOver="M_showUserInfoPopup(this)">%s</a>' %
(reverse('codereview.views.show_user', args=[account.nickname]),
cgi.escape(account.nickname)))
link_dict[account.email] = ret
datastore_results = dict((e, link_dict[e]) for e in remaining_emails)
memcache.set_multi(datastore_results, 300, key_prefix='show_user:')
user_cache.update(datastore_results)
return link_dict
def get_link_for_user(email):
"""Get a link to a user's profile page."""
links = get_links_for_users([email])
return links[email]
@register.filter
def show_user(email, arg=None, autoescape=None, memcache_results=None):
"""Render a link to the user's dashboard, with text being the nickname."""
if isinstance(email, users.User):
email = email.email()
if not arg:
user = users.get_current_user()
if user is not None and email == user.email():
return 'me'
ret = get_link_for_user(email)
return django.utils.safestring.mark_safe(ret)
@register.filter
def show_users(email_list, arg=None):
"""Render list of links to each user's dashboard."""
new_email_list = []
for email in email_list:
if isinstance(email, users.User):
email = email.email()
new_email_list.append(email)
links = get_links_for_users(new_email_list)
if not arg:
user = users.get_current_user()
if user is not None:
links[user.email()] = 'me'
return django.utils.safestring.mark_safe(', '.join(
links[email] for email in email_list))
class UrlAppendViewSettingsNode(django.template.Node):
"""Django template tag that appends context and column_width parameter.
This tag should be used after any URL that requires view settings.
Example:
<a href='{%url /foo%}{%urlappend_view_settings%}'>
The tag tries to get the current column width and context from the
template context and if they're present it returns '?param1¶m2'
otherwise it returns an empty string.
"""
def __init__(self):
"""Constructor."""
self.view_context = django.template.Variable('context')
self.view_colwidth = django.template.Variable('column_width')
def render(self, context):
"""Returns a HTML fragment."""
url_params = []
current_context = -1
try:
current_context = self.view_context.resolve(context)
except django.template.VariableDoesNotExist:
pass
if current_context is None:
url_params.append('context=')
elif isinstance(current_context, int) and current_context > 0:
url_params.append('context=%d' % current_context)
current_colwidth = None
try:
current_colwidth = self.view_colwidth.resolve(context)
except django.template.VariableDoesNotExist:
pass
if current_colwidth is not None:
url_params.append('column_width=%d' % current_colwidth)
if url_params:
return '?%s' % '&'.join(url_params)
return ''
@register.tag
def urlappend_view_settings(parser, token):
"""The actual template tag."""
return UrlAppendViewSettingsNode()
def get_nickname(email, never_me=False, request=None):
"""Return a nickname for an email address.
If 'never_me' is True, 'me' is not returned if 'email' belongs to the
current logged in user. If 'request' is a HttpRequest, it is used to
cache the nickname returned by models.Account.get_nickname_for_email().
"""
if isinstance(email, users.User):
email = email.email()
if not never_me:
if request is not None:
user = request.user
else:
user = users.get_current_user()
if user is not None and email == user.email():
return 'me'
if request is None:
return models.Account.get_nickname_for_email(email)
else:
if getattr(request, '_nicknames', None) is None:
request._nicknames = {}
if email in request._nicknames:
return request._nicknames[email]
result = models.Account.get_nickname_for_email(email)
request._nicknames[email] = result
return result
class NicknameNode(django.template.Node):
"""Renders a nickname for a given email address.
The return value is cached if a HttpRequest is available in a
'request' template variable.
The template tag accepts one or two arguments. The first argument is
the template variable for the email address. If the optional second
argument evaluates to True, 'me' as nickname is never rendered.
Example usage:
{% cached_nickname msg.sender %}
{% cached_nickname msg.sender True %}
"""
def __init__(self, email_address, never_me=''):
"""Constructor.
'email_address' is the name of the template variable that holds an
email address. If 'never_me' evaluates to True, 'me' won't be returned.
"""
self.email_address = django.template.Variable(email_address)
self.never_me = bool(never_me.strip())
self.is_multi = False
def render(self, context):
try:
email = self.email_address.resolve(context)
except django.template.VariableDoesNotExist:
return ''
request = context.get('request')
if self.is_multi:
return ', '.join(get_nickname(e, self.never_me, request) for e in email)
return get_nickname(email, self.never_me, request)
@register.tag
def nickname(parser, token):
"""Almost the same as nickname filter but the result is cached."""
try:
tag_name, email_address, never_me = token.split_contents()
except ValueError:
try:
tag_name, email_address = token.split_contents()
never_me = ''
except ValueError:
raise django.template.TemplateSyntaxError(
"%r requires exactly one or two arguments" % token.contents.split()[0])
return NicknameNode(email_address, never_me)
@register.tag
def nicknames(parser, token):
"""Wrapper for nickname tag with is_multi flag enabled."""
node = nickname(parser, token)
node.is_multi = True
return node
| [
[
8,
0,
0.0584,
0.0039,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0661,
0.0039,
0,
0.66,
0.05,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.07,
0.0039,
0,
0.66,
... | [
"\"\"\"Django template library for Rietveld.\"\"\"",
"import cgi",
"import logging",
"from google.appengine.api import memcache",
"from google.appengine.api import users",
"import django.template",
"import django.utils.safestring",
"from django.core.urlresolvers import reverse",
"import models",
"... |
import BasicEditor | [
[
1,
0,
1,
1,
0,
0.66,
0,
685,
0,
1,
0,
0,
685,
0,
0
]
] | [
"import BasicEditor"
] |
'''
Created on 2010-04-19
@author: Philippe Beaudoin
'''
from distutils.core import setup
import py2exe
setup(windows=['BasicEditor.py'],
options={
"py2exe": {
"includes": ["ctypes", "logging"],
"excludes": ["OpenGL"],
}
}
) | [
[
8,
0,
0.1875,
0.3125,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.375,
0.0625,
0,
0.66,
0.3333,
152,
0,
1,
0,
0,
152,
0,
0
],
[
1,
0,
0.4375,
0.0625,
0,
0.66,... | [
"'''\nCreated on 2010-04-19\n\n@author: Philippe Beaudoin\n'''",
"from distutils.core import setup",
"import py2exe",
"setup(windows=['BasicEditor.py'],\n options={\n \"py2exe\": {\n \"includes\": [\"ctypes\", \"logging\"],\n \"excludes\": [\"OpenGL\"],\n }... |
import MathLib
x = MathLib.Vector3d()
x.setValues(10,0.44,-132)
print "x = ",
x._print()
y = MathLib.Vector3d()
y.setValues(3,11,2)
print "y = ",
y._print()
x.addScaledVector(y,0.5)
print "x + 0.5y = ",
x._print()
| [
[
1,
0,
0.0714,
0.0714,
0,
0.66,
0,
209,
0,
1,
0,
0,
209,
0,
0
],
[
14,
0,
0.2143,
0.0714,
0,
0.66,
0.0909,
190,
3,
0,
0,
0,
624,
10,
1
],
[
8,
0,
0.2857,
0.0714,
0,
... | [
"import MathLib",
"x = MathLib.Vector3d()",
"x.setValues(10,0.44,-132)",
"print(\"x = \",)",
"x._print()",
"y = MathLib.Vector3d()",
"y.setValues(3,11,2)",
"print(\"y = \",)",
"y._print()",
"x.addScaledVector(y,0.5)",
"print(\"x + 0.5y = \",)",
"x._print()"
] |
import Utils
Utils.test() | [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
842,
0,
1,
0,
0,
842,
0,
0
],
[
8,
0,
1,
0.3333,
0,
0.66,
1,
224,
3,
0,
0,
0,
0,
0,
1
]
] | [
"import Utils",
"Utils.test()"
] |
'''
Created on 2009-09-29
@author: beaudoin
'''
import PyUtils
class Curve(PyUtils.Observable):
"""This class contains a named curve that can be observed."""
def __init__(self, name, trajectory1d, phiPtr = None):
"""Initializes a curve with the given name and attached to the given trajectory."""
self._name = str(name) # No unicode string pass this point
self._trajectory1d = trajectory1d
self._phiPtr = phiPtr
def getName(self):
"""Returns the curve name."""
return self._name
def setName(self, name):
"""Returns the curve name."""
self._name = str(name) # No unicode string pass this point
self.notifyObservers()
def getTrajectory1d(self):
"""Returns the attached trajectory."""
return self._trajectory1d
def getPhiPtr(self):
"""Returns the attached pointer to the phase."""
return self._phiPtr | [
[
8,
0,
0.0909,
0.1515,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2121,
0.0303,
0,
0.66,
0.5,
806,
0,
1,
0,
0,
806,
0,
0
],
[
3,
0,
0.6364,
0.7576,
0,
0.66,
... | [
"'''\nCreated on 2009-09-29\n\n@author: beaudoin\n'''",
"import PyUtils",
"class Curve(PyUtils.Observable):\n \"\"\"This class contains a named curve that can be observed.\"\"\"\n \n def __init__(self, name, trajectory1d, phiPtr = None):\n \"\"\"Initializes a curve with the given name and attach... |
'''
Created on 2009-09-28
@author: beaudoin
'''
import PyUtils
class ObservableList(PyUtils.Observable):
"""An object that contains a list of observable objects of the application (i.e. controllers, characters...)"""
def __init__(self):
super(ObservableList,self).__init__()
self._objects = []
def add(self, object):
"""Adds an object to the list, notify observers."""
if PyUtils.sameObjectInList(object, self._objects) :
raise KeyError ('Cannot add the same object twice to application.')
self._objects.append( object )
self.notifyObservers()
return object
def delete(self, object):
"""Removes an object from the list. Specify either a name, an index, or an instance of the object."""
self._objects.remove( self.get(object) )
self.notifyObservers()
def clear(self):
"""Removes all objects from the list."""
del self._objects[:]
self.notifyObservers()
def get(self, description):
"""
Gets the object at the specified index, or with the specified name.
If description is a string, an object with the specified name will be searched.
If search fails or objects do not have a getName method, a ValueError is raised.
If description is an int, the controller at the specified index will be returned.
If the index is invalid, an IndexError is raised.
Otherwise, the input is returned unmodified. (So, if a controller object is passed, it is returned.)
"""
if isinstance(description,basestring) :
try:
description = [obj.getName() for obj in self._objects].index(description)
except (AttributeError, ValueError): raise ValueError( "No object found with the specified name." )
if isinstance(description,int) :
return self._objects[description]
return description
def getCount(self):
"""Returns the number of controllers."""
return len( self._objects )
| [
[
8,
0,
0.0545,
0.0909,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1091,
0.0182,
0,
0.66,
0.5,
806,
0,
1,
0,
0,
806,
0,
0
],
[
3,
0,
0.5727,
0.8727,
0,
0.66,
... | [
"'''\nCreated on 2009-09-28\n\n@author: beaudoin\n'''",
"import PyUtils",
"class ObservableList(PyUtils.Observable):\n \"\"\"An object that contains a list of observable objects of the application (i.e. controllers, characters...)\"\"\"\n\n def __init__(self):\n super(ObservableList,self).__init__(... |
'''
Created on 2009-10-02
@author: beaudoin
'''
import PyUtils, Core, time, Physics, Utils, wx
class Snapshot(PyUtils.Observable):
"""This class contains a snapshot. That is, the entire state of the world, the controllers and the character."""
def __init__(self, parentBranch):
"""Takes a shot of a world, add it to the specified branch."""
super(Snapshot,self).__init__()
self._time = time.localtime()
# Save the world
world = Physics.world()
self._worldState = Utils.DynamicArrayDouble()
world.getState( self._worldState )
# Save the controllers
app = wx.GetApp()
self._controllers = []
for i in range(app.getControllerCount()):
controller = app.getController(i)
controllerState = Core.SimBiControllerState()
controller.getControllerState( controllerState )
self._controllers.append( (controllerState, PyUtils.wrapCopy( controller )) )
self._parentBranch = parentBranch
self._childBranches = []
self._activeIndex = -1
#
# Public methods
#
def restore(self, restoreControllerParams = True):
"""Restores this snapshot, sets it as active."""
self._parentBranch._setActiveSnapshot( self )
self._restore(restoreControllerParams)
self.notifyObservers()
def getBranch(self, index):
"""Retrieves a branch."""
return self._childBranches[index]
def getBranchCount(self):
"""Retrieves the number of branches."""
return len( self._childBranches )
def getName(self):
"""Retrieves a string for that snapshot."""
return "Snapshot at %(time)s" % { "time" : time.strftime("%H:%M:%S", self._time) }
#
# Private methods
#
def _takeSnapshot(self):
"""Takes a snapshot in the active branch, or add a new active branch if required."""
if self._activeIndex != -1 :
snapshot = self._childBranches[self._activeIndex].takeSnapshot()
if snapshot is not None : return snapshot
# Need to add a new branch
self._childBranches.append( SnapshotBranch(self) )
self._activeIndex = len(self._childBranches) - 1
self.notifyObservers()
return self._childBranches[self._activeIndex].takeSnapshot()
def _restore(self, restoreControllerParams = True):
"""Restores this snapshot, does sets it as active. Should only be called by SnapshotBranch."""
if self._activeIndex >= 0 :
# Make sure the selected branch is deactivated
self._childBranches[self._activeIndex]._deactivate()
# Restore the world
world = Physics.world()
world.setState( self._worldState )
# Restore the controllers
app = wx.GetApp()
assert app.getControllerCount() == len(self._controllers), "Controller list doesn't match snapshot!"
for i in range(app.getControllerCount()):
controller = app.getController(i)
controllerState, wrappedController = self._controllers[i]
if restoreControllerParams :
controller.beginBatchChanges()
try: wrappedController.fillObject(controller)
finally: controller.endBatchChanges()
controller.setControllerState( controllerState )
self.notifyObservers()
def _deactivateAllBranches(self):
"""Indicates that no branch should be active. In other words, the main branch is active."""
self._activeIndex = -1
def _setActiveBranch(self, branch):
"""Indicates that the specified branch should be the active one."""
self._parentBranch._setActiveSnapshot(self)
if self._activeIndex < 0 or branch is not self._childBranches[self._activeIndex] :
for i, myBranch in enumerate( self._childBranches ) :
if myBranch is branch :
self._activeIndex = i
return
raise RuntimeError( "Desired active branch not found!" )
def _getCurrentSnapshot(self):
if self._activeIndex < 0 : return self
return self._childBranches[self._activeIndex].getCurrentSnapshot()
def _restoreActive(self, restoreControllerParams = True):
"""Restores the active snapshot. Can be this one or one in its subbranches."""
if self._activeIndex >= 0 :
snapshot = self._childBranches[self._activeIndex].restoreActive(restoreControllerParams)
if snapshot is not None:
return snapshot
self._restore(restoreControllerParams)
return self
def _previousSnapshot(self, restoreControllerParams = True):
"""Restore previous snapshot and set it as active. Return false if no previous snapshot could be restored,
in which case the previous branch should navigate."""
if self._activeIndex < 0 : return None
return self._childBranches[self._activeIndex].previousSnapshot(restoreControllerParams)
def _nextSnapshot(self, restoreControllerParams = True):
"""Navigates down active branch. Return false if no active branch."""
if self._activeIndex < 0 : return None
return self._childBranches[self._activeIndex].nextSnapshot(restoreControllerParams)
class SnapshotBranch(PyUtils.Observable):
"""A list of world snapshots, including controller states and parameters."""
def __init__(self, parentSnapshot = None):
"""Pass the parent snapshot or None if this is the root branch."""
super(SnapshotBranch,self).__init__()
self._parentSnapshot = parentSnapshot
self._snapshots = []
self._activeIndex = -1
#
# Public methods
#
def takeSnapshot(self):
"""Take a new snapshot and add it at the correct position in this branch, or one of its subbranches.
Return the snapshot if it was taken, None otherwise."""
if self._activeIndex == len(self._snapshots) - 1:
snapshot = Snapshot(self)
self._snapshots.append( snapshot )
self._activeIndex = len(self._snapshots) - 1
self.notifyObservers()
return snapshot
elif self._activeIndex > -1 :
return self._snapshots[self._activeIndex]._takeSnapshot()
else:
return None
def getCurrentSnapshot(self):
"""Returns the currently active snapshot."""
if self._activeIndex < 0 : return self._parentSnapshot
return self._snapshots[self._activeIndex]._getCurrentSnapshot()
def restoreActive(self, restoreControllerParams = True):
"""Restores the currently active snapshot. Returns false if nothing was restored. """
if self._activeIndex < 0 :
return None
return self._snapshots[self._activeIndex]._restoreActive(restoreControllerParams)
def previousSnapshot(self, restoreControllerParams = True):
"""Restore previous snapshot and set it as active. Return false if no previous snapshot could be restored,
in which case the previous branch should navigate."""
if self._activeIndex < 0 :
return None
snapshot = self._snapshots[self._activeIndex]._previousSnapshot(restoreControllerParams)
if snapshot is not None :
return snapshot
# Cannot be handled by active snapshot, go down this branch
if self._activeIndex == 0 and self._parentSnapshot is None :
return self._snapshots[0]
self._activeIndex -= 1
if self._activeIndex == -1:
self._parentSnapshot._restore(restoreControllerParams)
return self._parentSnapshot
self._snapshots[self._activeIndex]._deactivateAllBranches()
self._snapshots[self._activeIndex]._restore(restoreControllerParams)
return self._snapshots[self._activeIndex]
def nextSnapshot(self, restoreControllerParams = True):
"""Restore next snapshot and set it as active. Return false if no next snapshot could be restored."""
if self._activeIndex >= 0 :
snapshot = self._snapshots[self._activeIndex]._nextSnapshot(restoreControllerParams)
if snapshot is not None:
return snapshot
if self._activeIndex < len( self._snapshots ) - 1 :
self._activeIndex += 1
self._snapshots[self._activeIndex]._restore(restoreControllerParams)
return self._snapshots[self._activeIndex]
def getSnapshot(self, index):
"""Access the snapshot at the specified index. Will not change the active snapshot."""
return self._snapshots[index]
def getSnapshotCount(self):
"""Access the total number of snapshots."""
return len(self._snapshots)
#
# Private methods
#
def _deactivate(self):
"""Indicates that this branch is not active and the parent snapshot should be selected."""
self._activeIndex = -1
def _setActiveSnapshot(self, snapshot):
"""Makes sure the specified snapshot is the active one."""
if self._parentSnapshot is not None:
self._parentSnapshot._setActiveBranch(self)
if self._activeIndex < 0 or snapshot is not self._snapshots[self._activeIndex] :
for i, mySnapshot in enumerate( self._snapshots ) :
if mySnapshot is snapshot :
self._activeIndex = i
return
raise RuntimeError( "Desired active snapshot not found!" )
| [
[
8,
0,
0.0122,
0.0204,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0286,
0.0041,
0,
0.66,
0.3333,
806,
0,
6,
0,
0,
806,
0,
0
],
[
3,
0,
0.298,
0.5265,
0,
0.66,... | [
"'''\nCreated on 2009-10-02\n\n@author: beaudoin\n'''",
"import PyUtils, Core, time, Physics, Utils, wx",
"class Snapshot(PyUtils.Observable):\n \"\"\"This class contains a snapshot. That is, the entire state of the world, the controllers and the character.\"\"\"\n \n def __init__(self, parentBranch):\... |
'''
Created on 2009-11-20
@author: beaudoin
'''
from OpenGL.GL import *
import wx, GLUtils, PyUtils, math, traceback, sys
import UI
class CharacterScaler(UI.GLUITools.WindowWithControlPoints):
"""Base class for a simple GL window that display a character with handles to scale its various elements."""
def __init__( self, parent, characterDescription, x=0, y=0, width=0, height=0, minWidth=-1, minHeight=-1 ):
super(CharacterScaler,self).__init__(parent,x,y,width,height, minWidth, minHeight, boundsY = (-0.1,2.1), forceAspectRatio = 'x')
self._characterDescription = characterDescription
class CharacterScalerFront(CharacterScaler):
"""A simple GL window that display a character from the front view with handles to scale its various elements."""
def __init__( self, parent, characterDescription, x=0, y=0, width=0, height=0, minWidth=-1, minHeight=-1 ):
super(CharacterScalerFront,self).__init__(parent,characterDescription,x,y,width,height, minWidth, minHeight)
self.addControlPoint( FrontFootControlPoint(characterDescription,-1) )
self.addControlPoint( FrontFootControlPoint(characterDescription,1) )
self.addControlPoint( FrontKneeControlPoint(characterDescription,-1) )
self.addControlPoint( FrontKneeControlPoint(characterDescription,1) )
self.addControlPoint( FrontLegControlPoint(characterDescription,-1) )
self.addControlPoint( FrontLegControlPoint(characterDescription,1) )
self.addControlPoint( FrontLegAnchorControlPoint(characterDescription,-1) )
self.addControlPoint( FrontLegAnchorControlPoint(characterDescription,1) )
self.addControlPoint( FrontPelvisControlPoint(characterDescription) )
self.addControlPoint( FrontChestControlPoint(characterDescription) )
self.addControlPoint( FrontShoulderControlPoint(characterDescription) )
self.addControlPoint( FrontNeckControlPoint(characterDescription) )
self.addControlPoint( FrontHeadTopControlPoint(characterDescription) )
self.addControlPoint( FrontHeadSideControlPoint(characterDescription) )
self.addControlPoint( FrontElbowControlPoint(characterDescription,-1) )
self.addControlPoint( FrontElbowControlPoint(characterDescription,1) )
self.addControlPoint( FrontWristControlPoint(characterDescription,-1) )
self.addControlPoint( FrontWristControlPoint(characterDescription,1) )
def drawContent(self):
"""Draw the character from front view."""
cd = self._characterDescription
glColor3f(1,1,1)
try:
for side in (-1,1):
glColor4f( 0.5, 0.5, 0.5, 0.84 )
glBegin(GL_QUADS)
halfSize = cd.getFootSizeX(side)/2.0
glVertex2d( cd.getLegPosX(side) - halfSize, cd.getGroundPosY() )
glVertex2d( cd.getLegPosX(side) - halfSize, cd.getAnklePosY(side) )
glVertex2d( cd.getLegPosX(side) + halfSize, cd.getAnklePosY(side) )
glVertex2d( cd.getLegPosX(side) + halfSize, cd.getGroundPosY() )
glEnd()
glColor4f( 0.5, 0.6, 0.8, 0.84 )
glBegin(GL_QUADS)
halfSize = cd.getLowerLegDiameter(side)/2.0
glVertex2d( cd.getLegPosX(side) - halfSize, cd.getAnklePosY(side) )
glVertex2d( cd.getLegPosX(side) - halfSize, cd.getKneePosY(side) )
glVertex2d( cd.getLegPosX(side) + halfSize, cd.getKneePosY(side) )
glVertex2d( cd.getLegPosX(side) + halfSize, cd.getAnklePosY(side) )
glEnd()
glColor4f( 0.5, 0.6, 0.8, 0.84 )
glBegin(GL_QUADS)
halfSize = cd.getUpperLegDiameter(side)/2.0
glVertex2d( cd.getLegPosX(side) - halfSize, cd.getKneePosY(side) )
glVertex2d( cd.getLegPosX(side) - halfSize, cd.getHipPosY() )
glVertex2d( cd.getLegPosX(side) + halfSize, cd.getHipPosY() )
glVertex2d( cd.getLegPosX(side) + halfSize, cd.getKneePosY(side) )
glEnd()
glColor4f( 0.5, 0.6, 0.8, 0.84 )
glBegin(GL_QUADS)
glVertex2d( 0, cd.getHipPosY() )
glVertex2d( side*cd.getPelvisDiameter()/2.0, cd.getHipPosY() )
glVertex2d( side*cd.getPelvisDiameter()/2.0, cd.getWaistPosY() )
glVertex2d( 0, cd.getWaistPosY() )
glEnd()
glColor4f( 0.5, 0.8, 0.6, 0.84 )
glBegin(GL_POLYGON)
glVertex2d( 0, cd.getWaistPosY() )
glVertex2d( side*cd.getTorsoDiameter()/4.0, cd.getWaistPosY() )
glVertex2d( side*cd.getTorsoDiameter()/2.0, cd.getChestPosY() )
glVertex2d( side*cd.getTorsoDiameter()/2.0, cd.getShoulderPosY() )
glVertex2d( 0, cd.getShoulderPosY() )
glEnd()
glColor4f( 0.892, 0.716, 0.602, 0.84 )
glBegin(GL_QUADS)
glVertex2d( 0, cd.getShoulderPosY() )
glVertex2d( side*0.1*cd.getHeadSizeX(), cd.getShoulderPosY() )
glVertex2d( side*0.1*cd.getHeadSizeX(), cd.getNeckPosY() )
glVertex2d( 0, cd.getNeckPosY() )
glEnd()
glColor4f( 0.892, 0.716, 0.602, 0.84 )
glVertex2f( 0, cd.getNeckPosY() + cd.getHeadSizeY()/2.0 )
glBegin(GL_TRIANGLE_FAN)
for i in range(21):
theta = math.pi * i/20.0
x = side * math.sin(theta) * cd.getHeadSizeX()/2.0
y = math.cos(theta) * cd.getHeadSizeY()/2.0 + cd.getNeckPosY() + cd.getHeadSizeY()/2.0
glVertex2f( x, y )
glEnd()
glColor4f( 0.5, 0.8, 0.6, 0.84 )
glBegin(GL_QUADS)
halfSize = cd.getUpperArmDiameter(side)/2.0
glVertex2d( cd.getArmPosX(side)-halfSize, cd.getShoulderPosY() )
glVertex2d( cd.getArmPosX(side)-halfSize, cd.getElbowPosY(side) )
glVertex2d( cd.getArmPosX(side)+halfSize, cd.getElbowPosY(side) )
glVertex2d( cd.getArmPosX(side)+halfSize, cd.getShoulderPosY() )
glEnd()
glColor4f( 0, 0, 0, 1 )
glBegin(GL_LINES)
glVertex2d( cd.getArmPosX(side)-side*halfSize, cd.getShoulderPosY() )
glVertex2d( cd.getArmPosX(side)-side*halfSize, cd.getChestPosY() )
glEnd()
glColor4f( 0.892, 0.716, 0.602, 0.84 )
glBegin(GL_QUADS)
halfSize = cd.getLowerArmDiameter(side)/2.0
glVertex2d( cd.getArmPosX(side)-halfSize, cd.getElbowPosY(side) )
glVertex2d( cd.getArmPosX(side)-halfSize, cd.getWristPosY(side) )
glVertex2d( cd.getArmPosX(side)+halfSize, cd.getWristPosY(side) )
glVertex2d( cd.getArmPosX(side)+halfSize, cd.getElbowPosY(side) )
glEnd()
# Draw control points
glPointSize( 8.0 )
glColor3d(1,1,0)
glBegin( GL_POINTS );
for controlPoint in self._controlPoints:
controlPoint.draw()
glEnd()
except Exception as e:
glEnd()
print "Exception while drawing scaled character interface: " + str(e)
traceback.print_exc(file=sys.stdout)
class CharacterControlPoint(UI.GLUITools.ControlPoint):
def __init__( self, characterDescription):
"""Pass the character description and a 4-tuple (minX, maxX, minY, maxY)."""
super(CharacterControlPoint,self).__init__()
self._characterDescription = characterDescription
class SymmetricCharacterControlPoint(CharacterControlPoint):
def __init__( self, characterDescription, side ):
super(SymmetricCharacterControlPoint,self).__init__(characterDescription)
self._side = side
def draw(self):
if self._characterDescription.isSymmetric() and self._side == -1 : return
super(SymmetricCharacterControlPoint,self).draw()
class FrontFootControlPoint(SymmetricCharacterControlPoint):
def __init__(self, characterDescription, side):
super(FrontFootControlPoint,self).__init__(characterDescription, side)
def getPos(self):
cd = self._characterDescription
return ( cd.getLegPosX(self._side) + self._side*cd.getFootSizeX(self._side)/2.0, cd.getAnklePosY(self._side) )
def setPos(self, pos):
cd = self._characterDescription
cd.setFootSizeX( self._side, (pos[0]-cd.getLegPosX(self._side))*2.0*self._side )
cd.setAnklePosY( self._side, pos[1] )
class FrontKneeControlPoint(SymmetricCharacterControlPoint):
def __init__(self, characterDescription, side):
super(FrontKneeControlPoint,self).__init__(characterDescription, side)
def getPos(self):
cd = self._characterDescription
return ( cd.getLegPosX(self._side) + self._side*cd.getLowerLegDiameter(self._side)/2.0, cd.getKneePosY(self._side) )
def setPos(self, pos):
cd = self._characterDescription
cd.setLowerLegDiameter( self._side, (pos[0]-cd.getLegPosX(self._side))*2.0*self._side )
cd.setKneePosY( self._side, pos[1] )
class FrontLegControlPoint(SymmetricCharacterControlPoint):
def __init__(self, characterDescription, side):
super(FrontLegControlPoint,self).__init__(characterDescription, side)
def getPos(self):
cd = self._characterDescription
return ( cd.getLegPosX(self._side) + self._side*cd.getUpperLegDiameter(self._side)/2.0, cd.getHipPosY() )
def setPos(self, pos):
cd = self._characterDescription
cd.setUpperLegDiameter( self._side, (pos[0]-cd.getLegPosX(self._side))*2.0*self._side )
cd.setHipPosY( pos[1] )
class FrontLegAnchorControlPoint(SymmetricCharacterControlPoint):
def __init__(self, characterDescription, side):
super(FrontLegAnchorControlPoint,self).__init__(characterDescription, side)
def getPos(self):
cd = self._characterDescription
return ( cd.getLegPosX(self._side), cd.getHipPosY() )
def setPos(self, pos):
cd = self._characterDescription
cd.setLegPosX( self._side, pos[0] )
class FrontPelvisControlPoint(CharacterControlPoint):
def __init__(self, characterDescription):
super(FrontPelvisControlPoint,self).__init__(characterDescription)
def getPos(self):
cd = self._characterDescription
return ( cd.getPelvisDiameter()/2.0, cd.getWaistPosY() )
def setPos(self, pos):
cd = self._characterDescription
cd.setPelvisDiameter( pos[0]*2.0 )
cd.setWaistPosY( pos[1] )
class FrontChestControlPoint(CharacterControlPoint):
def __init__(self, characterDescription):
super(FrontChestControlPoint,self).__init__(characterDescription)
def getPos(self):
cd = self._characterDescription
return ( cd.getTorsoDiameter()/2.0, cd.getChestPosY() )
def setPos(self, pos):
cd = self._characterDescription
cd.setTorsoDiameter( pos[0]*2.0 )
cd.setChestPosY( pos[1] )
class FrontShoulderControlPoint(CharacterControlPoint):
def __init__(self, characterDescription):
super(FrontShoulderControlPoint,self).__init__(characterDescription)
def getPos(self):
cd = self._characterDescription
return ( cd.getTorsoDiameter()/2.0, cd.getShoulderPosY() )
def setPos(self, pos):
cd = self._characterDescription
cd.setTorsoDiameter( pos[0]*2.0 )
cd.setShoulderPosY( pos[1] )
class FrontNeckControlPoint(CharacterControlPoint):
def __init__(self, characterDescription):
super(FrontNeckControlPoint,self).__init__(characterDescription)
def getPos(self):
cd = self._characterDescription
return ( 0, cd.getNeckPosY() )
def setPos(self, pos):
cd = self._characterDescription
cd.setNeckPosY( pos[1] )
class FrontHeadTopControlPoint(CharacterControlPoint):
def __init__(self, characterDescription):
super(FrontHeadTopControlPoint,self).__init__(characterDescription)
def getPos(self):
cd = self._characterDescription
return ( 0, cd.getNeckPosY() + cd.getHeadSizeY() )
def setPos(self, pos):
cd = self._characterDescription
cd.setHeadSizeY( pos[1]-cd.getNeckPosY() )
class FrontHeadSideControlPoint(CharacterControlPoint):
def __init__(self, characterDescription):
super(FrontHeadSideControlPoint,self).__init__(characterDescription)
def getPos(self):
cd = self._characterDescription
return ( cd.getHeadSizeX()/2.0, cd.getNeckPosY() + cd.getHeadSizeY()/2.0 )
def setPos(self, pos):
cd = self._characterDescription
cd.setHeadSizeX( pos[0]*2.0 )
class FrontElbowControlPoint(SymmetricCharacterControlPoint):
def __init__(self, characterDescription, side):
super(FrontElbowControlPoint,self).__init__(characterDescription, side)
def getPos(self):
cd = self._characterDescription
return ( self._side*(cd.getTorsoDiameter()/2.0 + cd.getUpperArmDiameter(self._side)), cd.getElbowPosY(self._side) )
def setPos(self, pos):
cd = self._characterDescription
cd.setUpperArmDiameter( self._side, pos[0]*self._side - cd.getTorsoDiameter()/2.0 )
cd.setElbowPosY( self._side, pos[1] )
class FrontWristControlPoint(SymmetricCharacterControlPoint):
def __init__(self, characterDescription, side):
super(FrontWristControlPoint,self).__init__(characterDescription, side)
def getPos(self):
cd = self._characterDescription
return ( cd.getArmPosX(self._side) + self._side*cd.getLowerArmDiameter(self._side)/2.0, cd.getWristPosY(self._side) )
def setPos(self, pos):
cd = self._characterDescription
cd.setLowerArmDiameter( self._side, (pos[0]-cd.getArmPosX(self._side))*2.0*self._side )
cd.setWristPosY( self._side, pos[1] )
| [
[
8,
0,
0.0099,
0.0164,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.023,
0.0033,
0,
0.66,
0.0526,
280,
0,
1,
0,
0,
280,
0,
0
],
[
1,
0,
0.0263,
0.0033,
0,
0.66,... | [
"'''\nCreated on 2009-11-20\n\n@author: beaudoin\n'''",
"from OpenGL.GL import *",
"import wx, GLUtils, PyUtils, math, traceback, sys",
"import UI",
"class CharacterScaler(UI.GLUITools.WindowWithControlPoints):\n \"\"\"Base class for a simple GL window that display a character with handles to scale its v... |
'''
Created on 2009-11-20
@author: beaudoin
'''
import Core, Physics, PyUtils
from MathLib import Vector3d, Point3d
class CharacterDescription(object):
"""A simple description of a character
Be careful:
Left refer to the left-hand-side of the character (which is seen to the right from the front view)
So Right goes towards negative X, while Left goes towards positive X
"""
def getNativeVar(self, varName):
"""Access a native variable by name."""
return self.__getattribute__(varName).get()
def getNativeVarSymmetric(self, varName, side):
"""Access a symmetric native variable by name and side."""
return self.__getattribute__(varName).getSide(side)
def setNativeVar(self, varName, value):
"""Sets a native variable by name."""
variable = self.__getattribute__(varName)
if variable.get() == value : return
self._indirectVarsAreValid = False
variable.set(value)
def setNativeVarSymmetric(self, varName, side, value):
"""Sets a symmetric native variable by name and side."""
variable = self.__getattribute__(varName)
if variable.getSide(side) == value : return
if self._isSymmetric : side = 0
self._indirectVarsAreValid = False
variable.setSide( side, value )
def getIndirectVar(self, varName):
"""Access an indirect variable by name."""
if not self._indirectVarsAreValid : self._computeIndirectVars()
return self.__getattribute__(varName).get()
def getIndirectVarSymmetric(self, varName, side):
"""Access a symmetric indirect variable by name and side."""
if not self._indirectVarsAreValid : self._computeIndirectVars()
return self.__getattribute__(varName).getSide(side)
def _addNativeVar(self, varName, initialValue):
"""Add a variable with he given name, as well as its getter and setter."""
if isinstance(initialValue, _Symmetric) :
self.__setattr__( PyUtils.getterName(varName), lambda side: self.getNativeVarSymmetric(varName, side) )
self.__setattr__( PyUtils.setterName(varName), lambda side, value: self.setNativeVarSymmetric(varName, side, value) )
else :
self.__setattr__( PyUtils.getterName(varName), lambda: self.getNativeVar(varName) )
self.__setattr__( PyUtils.setterName(varName), lambda value: self.setNativeVar(varName, value) )
self.__setattr__( varName, initialValue )
def _addIndirectVar(self, varName, initialValue):
"""Add an indirect variable with the given name, as well as its getter and setter."""
if isinstance(initialValue, _Symmetric) :
self.__setattr__( PyUtils.getterName(varName), lambda side: self.getIndirectVarSymmetric(varName, side) )
else:
self.__setattr__( PyUtils.getterName(varName), lambda: self.getIndirectVar(varName) )
self._indirectVarsAreValid = None
self.__setattr__(varName, initialValue)
def __init__(self):
super(CharacterDescription,self).__init__()
# Roughly based on http://www.idrawdigital.com/wp-content/uploads/2009/01/prop_male.gif
# 1 head unit = 0.2286 meters
hu = 0.2286
self._isSymmetric = True
self._indirectVarsAreValid = False
self._natives = {
'_footSizeX' : _Symmetric( 0.45 * hu, 0.6*hu, hu ),
'_footSizeZ' : _Symmetric(1 * hu, 0.1*hu ),
'_ankleRelativePosY' : _Symmetric(0.05, 0.05, 0.3 ),
'_lowerLegDiameter' : _Symmetric( 0.33 * hu, 0.2*hu, hu ),
'_upperLegDiameter' : _Symmetric( 0.4 * hu, 0.2*hu, hu ),
'_legSizeY' : _Value( 4*hu, 2*hu, 6*hu ),
'_kneeRelativePosY' : _Symmetric( 0.52, 0.2, 0.8 ),
'_legRelativeAnchorX' : _Symmetric( 0.6, 0.2, 0.8 ),
'_pelvisDiameter' : _Value( 1.1 * hu, 0.1*hu, 2.5*hu ),
'_torsoDiameter' : _Value( 1.4 * hu, hu, 2.6*hu ),
'_trunkSizeY' : _Value( 2.66 * hu, 1.8*hu, 3.5*hu ),
'_waistRelativePosY' : _Value( 0.17, 0.1, 0.4 ),
'_chestRelativePosY' : _Value( 0.5, 0.2, 0.8 ),
'_neckSizeY' : _Value( 0.05 * hu, 0.01*hu, 2*hu ),
'_headSizeX' : _Value( 0.9 * hu, 0.1*hu, 2*hu ),
'_headSizeY' : _Value( 1.1 * hu, 0.1*hu, 2*hu ),
'_headSizeZ' : _Value( 1.0 * hu, 0.1*hu, 2*hu ),
'_upperArmDiameter' : _Symmetric( 0.35 * hu, 0.2*hu, hu ),
'_lowerArmDiameter' : _Symmetric( 0.28 * hu, 0.2*hu, hu ),
'_armSizeY' : _Symmetric( 2.7 * hu, 1*hu, 5*hu ),
'_elbowRelativePosY' : _Symmetric( 0.44444444, 0.01, 0.99 ) }
for var, val in self._natives.iteritems() :
self._addNativeVar( var, val )
self._indirects = {
'_legPosX' : _Symmetric(0),
'_groundPosY' : _Value(0),
'_anklePosY' : _Symmetric(0),
'_kneePosY' : _Symmetric(0),
'_hipPosY' : _Value(0),
'_waistPosY' : _Value(0),
'_chestPosY' : _Value(0),
'_shoulderPosY' : _Value(0),
'_neckPosY' : _Value(0),
'_armPosX' : _Symmetric(0),
'_elbowPosY' : _Symmetric(0),
'_wristPosY' : _Symmetric(0)
}
for var, val in self._indirects.iteritems() :
self._addIndirectVar( var, val )
def _computeLegPosX(self, side):
self._legPosX.setSide( side, side*self._pelvisDiameter.get()/2.0*self._legRelativeAnchorX.getSide(side))
def setLegPosX(self, side, value):
self.setLegRelativeAnchorX( side, value/self._pelvisDiameter.get()*2.0*side )
def _computeAnklePosY(self, side):
self._anklePosY.setSide( side, self._groundPosY.get() + self._legSizeY.get() * self._ankleRelativePosY.getSide(side) )
def setAnklePosY(self, side, value):
self.setAnkleRelativePosY( side, (value - self._groundPosY.get())/self._legSizeY.get() )
def _computeKneePosY(self, side):
self._kneePosY.setSide( side, self._anklePosY.getSide(side) + (self._hipPosY.get()-self._anklePosY.getSide(side)) * self._kneeRelativePosY.getSide(side) )
def setKneePosY(self, side, value):
self.setKneeRelativePosY( side, (value - self._anklePosY.getSide(side)) / (self._hipPosY.get()-self._anklePosY.getSide(side)) )
def _computeHipPosY(self):
self._hipPosY.set( self._groundPosY.get() + self._legSizeY.get() )
def setHipPosY(self, value):
self.setLegSizeY( value - self._groundPosY.get() )
def _computeShoulderPosY(self):
self._shoulderPosY.set( self._hipPosY.get() + self._trunkSizeY.get() )
def setShoulderPosY(self, value):
self.setTrunkSizeY( value - self._hipPosY.get() )
def _computeWaistPosY(self):
self._waistPosY.set( self._hipPosY.get() + self._trunkSizeY.get() * self._waistRelativePosY.get() )
def setWaistPosY(self, value):
self.setWaistRelativePosY( (value - self._hipPosY.get())/self._trunkSizeY.get() )
def _computeChestPosY(self):
self._chestPosY.set( self._waistPosY.get() + (self._shoulderPosY.get()-self._waistPosY.get()) * self._chestRelativePosY.get() )
def setChestPosY(self, value):
self.setChestRelativePosY( (value - self._waistPosY.get())/(self._shoulderPosY.get()-self._waistPosY.get()) )
def _computeNeckPosY(self):
self._neckPosY.set( self._shoulderPosY.get() + self._neckSizeY.get() )
def setNeckPosY(self, value):
self.setNeckSizeY( value - self._shoulderPosY.get() )
def _computeArmPosX(self, side):
self._armPosX.setSide(side, side*(self._torsoDiameter.get() + self._upperArmDiameter.getSide(side))/2.0)
def _computeWristPosY(self, side):
self._wristPosY.setSide(side, self._shoulderPosY.get() - self._armSizeY.getSide(side))
def setWristPosY(self, side, value):
self.setArmSizeY( side, self._shoulderPosY.get() - value )
def _computeElbowPosY(self, side):
self._elbowPosY.setSide(side, self._shoulderPosY.get() - self._armSizeY.getSide(side)*self._elbowRelativePosY.getSide(side))
def setElbowPosY(self, side, value):
self.setElbowRelativePosY( side, (self._shoulderPosY.get() - value)/self._armSizeY.getSide(side) )
def _computeIndirectVars(self):
"""Compute all the variables that are not directly part of the editable character description."""
if self._indirectVarsAreValid : return
# Careful! The order in which the _compute functions are called is important!
self._groundPosY.set( 0 )
self._hipPosY.set( self._groundPosY.get() + self._legSizeY.get() )
self._computeHipPosY()
self._computeShoulderPosY()
self._computeWaistPosY()
self._computeChestPosY()
self._computeNeckPosY()
for side in (-1,1) :
self._computeLegPosX( side )
self._computeAnklePosY(side)
self._computeKneePosY(side)
self._computeArmPosX(side)
self._computeWristPosY(side)
self._computeElbowPosY(side)
self._indirectVarsAreValid = True
def isSymmetric(self):
"""True if the character should be symmetrical."""
return self._isSymmetric
def setSymmetric(self, value):
"""Indicates whether the character should be symmetrical."""
if value == self._isSymmetric : return
self._isSymmetric = value
for val in self._natives.itervalues() :
try: val.forceSymmetric()
except AttributeError: pass
self._indirectVarsAreValid = False
def createCharacter(self):
"""Creates a 3D character that follows this description."""
from App import Proxys
blue = ( 0.5, 0.6, 0.8, 1 )
green = ( 0.5, 0.8, 0.6, 1 )
red = ( 0.892, 0.716, 0.602, 1 )
gray = ( 0.5, 0.5, 0.5, 1 )
character = Core.Character()
character.setName("Instant Character")
massScale = 900
pelvisSizeY = self.getWaistPosY() - self.getHipPosY()
pelvisBottomPos = -pelvisSizeY/2.0-self.getLegSizeY()*0.1
pelvisTopPos = pelvisSizeY/2.0
pelvisRadius = self.getPelvisDiameter()/2.0
rootPosY = self.getHipPosY() + pelvisSizeY/2.0 + 0.007
pelvis = PyUtils.RigidBody.createArticulatedTaperedBox(
name = "pelvis",
size = (pelvisRadius*2.0, pelvisSizeY*1.5, pelvisRadius*1.2),
moiScale = 3,
exponentBottom = 2,
exponentSide = 2,
mass = -massScale, pos=(0, rootPosY, 0), colour = blue )
character.setRoot( pelvis )
totalLowerBackSizeY = self.getChestPosY() - self.getWaistPosY()
lowerBackOffsetY = 0 #0.15 * totalLowerBackSizeY
lowerBackSizeX = self.getTorsoDiameter() * 0.7
lowerBackSizeY = totalLowerBackSizeY - lowerBackOffsetY
lowerBackSizeZ = lowerBackSizeX * 0.7
lowerback = PyUtils.RigidBody.createArticulatedTaperedBox(
name = "lowerBack",
size = (lowerBackSizeX, lowerBackSizeY, lowerBackSizeZ),
exponentTop = 3, exponentBottom = 2, exponentSide = 2,
mass = -massScale, colour = green )
character.addArticulatedRigidBody( lowerback )
joint = Proxys.BallInSocketJoint(
name = "pelvis_lowerback",
posInParent = (0, pelvisSizeY/2.0, 0),
posInChild = (0, -lowerBackSizeY/2.0 -lowerBackOffsetY, 0),
swingAxis1 = (1, 0, 0),
twistAxis = (0, 0, 1),
limits = (-1.6, 1.6, -1.6, 1.6, -1.6, 1.6) ).createAndFillObject()
joint.setParent(pelvis)
joint.setChild(lowerback)
character.addJoint(joint)
totalTorsoSizeY = self.getShoulderPosY() - self.getChestPosY()
torsoOffsetY = -0.2 * totalTorsoSizeY
torsoSizeX = self.getTorsoDiameter()
torsoSizeY = totalTorsoSizeY - torsoOffsetY
torsoSizeZ = torsoSizeX * 0.6
torso = PyUtils.RigidBody.createArticulatedTaperedBox(
name = "torso",
size = (torsoSizeX, torsoSizeY, torsoSizeZ),
exponentTop = 2.2, exponentBottom = 4, exponentSide = 3,
mass = -massScale, colour = green )
character.addArticulatedRigidBody( torso )
joint = Proxys.BallInSocketJoint(
name = "lowerback_torso",
posInParent = (0, lowerBackSizeY/2.0, 0),
posInChild = (0, -torsoSizeY/2.0 -torsoOffsetY, 0),
swingAxis1 = (1, 0, 0),
twistAxis = (0, 0, 1),
limits = (-1.6, 1.6, -1.6, 1.6, -1.6, 1.6) ).createAndFillObject()
joint.setParent(lowerback)
joint.setChild(torso)
character.addJoint(joint)
headOffsetY = self.getNeckSizeY()
headSizeX = self.getHeadSizeX()
headSizeY = self.getHeadSizeY()
headSizeZ = self.getHeadSizeZ()
head = PyUtils.RigidBody.createArticulatedEllipsoid(
name = "head",
radius = (headSizeX/2.0, headSizeY/2.0, headSizeZ/2.0),
mass = -massScale, withMesh = False )
character.addArticulatedRigidBody( head )
head.addMeshObj( "data/StockMeshes/head.obj", Vector3d(0,-0.064,0), Vector3d(headSizeX*6.5,headSizeY*4.6,headSizeZ*5.5) )
head.setColour( *red )
head.addMesh( PyUtils.Mesh.createCylinder(
basePoint = (0,-headSizeY/2.0 - headOffsetY - torsoSizeY*0.1,0),
tipPoint = (0,-headSizeY*0.2,0),
radius = 0.12*headSizeX, colour = red ))
joint = Proxys.BallInSocketJoint(
name = "torso_head",
posInParent = (0, torsoSizeY/2.0, 0),
posInChild = (0, -headSizeY/2.0 - headOffsetY, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-1.6, 1.6, -1.6, 1.6, -1.6, 1.6) ).createAndFillObject()
joint.setParent(torso)
joint.setChild(head)
character.addJoint(joint)
leftUpperArmSizeY = self.getShoulderPosY() - self.getElbowPosY(1)
leftUpperArmDiameter = self.getUpperArmDiameter(1)
lUpperArm = PyUtils.RigidBody.createArticulatedCylinder(
name = "lUpperArm",
moiScale = 3,
axis = 0, basePos = -leftUpperArmSizeY/2.0, tipPos = leftUpperArmSizeY/2.0,
radius = leftUpperArmDiameter/2.0,
mass = -massScale, colour = green )
character.addArticulatedRigidBody( lUpperArm )
lUpperArm.addMesh( PyUtils.Mesh.createSphere( (-leftUpperArmSizeY/2.0, 0, 0), leftUpperArmDiameter*0.65, colour = green ) )
lUpperArm.addMesh( PyUtils.Mesh.createSphere( (leftUpperArmSizeY/2.0, 0, 0), leftUpperArmDiameter*0.5, colour = green ) )
joint = Proxys.BallInSocketJoint(
name = "lShoulder",
posInParent = (torsoSizeX*0.52, torsoSizeY*0.32, 0),
posInChild = (-leftUpperArmSizeY/2.0, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = (1, 0, 0),
limits = (-100, 100, -1.5, 1.5, -100, 100) ).createAndFillObject()
joint.setParent(torso)
joint.setChild(lUpperArm)
character.addJoint(joint)
rightUpperArmSizeY = self.getShoulderPosY() - self.getElbowPosY(-1)
rightUpperArmDiameter = self.getUpperArmDiameter(-1)
rUpperArm = PyUtils.RigidBody.createArticulatedCylinder(
name = "rUpperArm",
moiScale = 3,
axis = 0, basePos = -rightUpperArmSizeY/2.0, tipPos = rightUpperArmSizeY/2.0,
radius = rightUpperArmDiameter/2.0,
mass = -massScale, colour = green )
character.addArticulatedRigidBody( rUpperArm )
rUpperArm.addMesh( PyUtils.Mesh.createSphere( (rightUpperArmSizeY/2.0, 0, 0), rightUpperArmDiameter*0.65, colour = green ) )
rUpperArm.addMesh( PyUtils.Mesh.createSphere( (-rightUpperArmSizeY/2.0, 0, 0), rightUpperArmDiameter*0.5, colour = green ) )
joint = Proxys.BallInSocketJoint(
name = "rShoulder",
posInParent = (-torsoSizeX*0.52, torsoSizeY*0.32, 0),
posInChild = (rightUpperArmSizeY/2.0, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = (1, 0, 0),
limits = (-100, 100, -1.5, 1.5, -100, 100) ).createAndFillObject()
joint.setParent(torso)
joint.setChild(rUpperArm)
character.addJoint(joint)
leftLowerArmSizeY = self.getElbowPosY(1) - self.getWristPosY(1)
leftLowerArmDiameter = self.getLowerArmDiameter(1)
lLowerArm = PyUtils.RigidBody.createArticulatedCylinder(
name = "lLowerArm",
moiScale = 3,
axis = 0, basePos = -leftLowerArmSizeY/2.0, tipPos = leftLowerArmSizeY/2.0,
radius = leftLowerArmDiameter/2.0,
mass = -massScale, colour = red )
character.addArticulatedRigidBody( lLowerArm )
lLowerArm.addMesh( PyUtils.Mesh.createTaperedBox(
position=(leftLowerArmSizeY*0.5+leftLowerArmDiameter*0.8,0,0),
size=(leftLowerArmDiameter*1.6, leftLowerArmDiameter*0.5, leftLowerArmDiameter*1.15), colour = red ) )
joint = Proxys.HingeJoint(
name = "lElbow",
posInParent = (leftUpperArmSizeY/2.0, 0, 0),
posInChild = (-leftLowerArmSizeY/2.0, 0, 0),
axis = (0, 1, 0),
limits = (-2.7, 0) ).createAndFillObject()
joint.setParent(lUpperArm)
joint.setChild(lLowerArm)
character.addJoint(joint)
rightLowerArmSizeY = self.getElbowPosY(-1) - self.getWristPosY(-1)
rightLowerArmDiameter = self.getLowerArmDiameter(-1)
rLowerArm = PyUtils.RigidBody.createArticulatedCylinder(
name = "rLowerArm",
moiScale = 3,
axis = 0, basePos = -rightLowerArmSizeY/2.0, tipPos = rightLowerArmSizeY/2.0,
radius = rightLowerArmDiameter/2.0,
mass = -massScale, colour = red )
character.addArticulatedRigidBody( rLowerArm )
rLowerArm.addMesh( PyUtils.Mesh.createTaperedBox(
position=(-rightLowerArmSizeY*0.5-rightLowerArmDiameter*0.8,0,0),
size=(rightLowerArmDiameter*1.6, rightLowerArmDiameter*0.5, rightLowerArmDiameter*1.15), colour = red ) )
joint = Proxys.HingeJoint(
name = "rElbow",
posInParent = (-rightUpperArmSizeY/2.0, 0, 0),
posInChild = (rightLowerArmSizeY/2.0, 0, 0),
axis = (0, -1, 0),
limits = (-2.7, 0) ).createAndFillObject()
joint.setParent(rUpperArm)
joint.setChild(rLowerArm)
character.addJoint(joint)
leftUpperLegSizeY = self.getHipPosY() - self.getKneePosY(1)
leftUpperLegDiameter = self.getUpperLegDiameter(1)
lUpperLeg = PyUtils.RigidBody.createArticulatedCylinder(
name = "lUpperLeg",
axis = 1, basePos = -leftUpperLegSizeY/2.0, tipPos = leftUpperLegSizeY/2.0,
radius = leftUpperLegDiameter/2.0,
moiScale = 4,
mass = -massScale, colour = blue )
character.addArticulatedRigidBody( lUpperLeg )
lUpperLeg.addMesh( PyUtils.Mesh.createSphere( (0, leftUpperLegSizeY/2.0, 0), leftUpperLegDiameter*0.5, colour = blue ) )
lUpperLeg.addMesh( PyUtils.Mesh.createSphere( (0, -leftUpperLegSizeY/2.0, 0), leftUpperLegDiameter*0.5, colour = blue ) )
joint = Proxys.BallInSocketJoint(
name = "lHip",
posInParent = (pelvisRadius*self.getLegRelativeAnchorX(1), -pelvisSizeY/2.0, 0),
posInChild = (0, leftUpperLegSizeY/2.0, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-1.3, 1.9, -1, 1, -1, 1) ).createAndFillObject()
joint.setParent(pelvis)
joint.setChild(lUpperLeg)
character.addJoint(joint)
rightUpperLegSizeY = self.getHipPosY() - self.getKneePosY(-1)
rightUpperLegDiameter = self.getUpperLegDiameter(-1)
rUpperLeg = PyUtils.RigidBody.createArticulatedCylinder(
name = "rUpperLeg",
axis = 1, basePos = -rightUpperLegSizeY/2.0, tipPos = rightUpperLegSizeY/2.0,
radius = rightUpperLegDiameter/2.0,
moiScale = 4,
mass = -massScale, colour = blue )
character.addArticulatedRigidBody( rUpperLeg )
rUpperLeg.addMesh( PyUtils.Mesh.createSphere( (0, -rightUpperLegSizeY/2.0, 0), rightUpperLegDiameter*0.5, colour = blue ) )
rUpperLeg.addMesh( PyUtils.Mesh.createSphere( (0, rightUpperLegSizeY/2.0, 0), rightUpperLegDiameter*0.5, colour = blue ) )
joint = Proxys.BallInSocketJoint(
name = "rHip",
posInParent = (-pelvisRadius*self.getLegRelativeAnchorX(-1), -pelvisSizeY/2.0, 0),
posInChild = (0, rightUpperLegSizeY/2.0, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-1.3, 1.9, -1, 1, -1, 1) ).createAndFillObject()
joint.setParent(pelvis)
joint.setChild(rUpperLeg)
character.addJoint(joint)
leftLowerLegSizeY = self.getKneePosY(1) - self.getAnklePosY(1)
leftLowerLegDiameter = self.getLowerLegDiameter(1)
lLowerLeg = PyUtils.RigidBody.createArticulatedCylinder(
name = "lLowerLeg",
axis = 1, basePos = -leftLowerLegSizeY/2.0, tipPos = leftLowerLegSizeY/2.0,
radius = leftLowerLegDiameter/2.0,
moiScale = 4,
mass = -massScale, colour = blue )
character.addArticulatedRigidBody( lLowerLeg )
joint = Proxys.HingeJoint(
name = "lKnee",
posInParent = (0, -leftUpperLegSizeY/2.0, 0),
posInChild = (0, leftLowerLegSizeY/2.0, 0),
axis = (1, 0, 0),
limits = (0, 2.5) ).createAndFillObject()
joint.setParent(lUpperLeg)
joint.setChild(lLowerLeg)
character.addJoint(joint)
rightLowerLegSizeY = self.getKneePosY(-1) - self.getAnklePosY(-1)
rightLowerLegDiameter = self.getLowerLegDiameter(-1)
rLowerLeg = PyUtils.RigidBody.createArticulatedCylinder(
name = "rLowerLeg",
axis = 1, basePos = -rightLowerLegSizeY/2.0, tipPos = rightLowerLegSizeY/2.0,
radius = rightLowerLegDiameter/2.0,
moiScale = 4,
mass = -massScale, colour = blue )
character.addArticulatedRigidBody( rLowerLeg )
joint = Proxys.HingeJoint(
name = "rKnee",
posInParent = (0, -rightUpperLegSizeY/2.0, 0),
posInChild = (0, rightLowerLegSizeY/2.0, 0),
axis = (1, 0, 0),
limits = (0, 2.5) ).createAndFillObject()
joint.setParent(rUpperLeg)
joint.setChild(rLowerLeg)
character.addJoint(joint)
leftFootSizeX = self.getFootSizeX(1)
leftFootSizeY = self.getAnklePosY(1) - self.getGroundPosY()
leftFootSizeZ = self.getFootSizeZ(1) * 0.75
lFoot = PyUtils.RigidBody.createArticulatedTaperedBox(
name = "lFoot",
size = (leftFootSizeX,leftFootSizeY,leftFootSizeZ),
exponentSide = 20,
groundCoeffs = (0.0005,0.2),
moiScale = 3,
mass = -massScale,
colour = gray )
character.addArticulatedRigidBody( lFoot )
joint = Proxys.UniversalJoint(
name = "lAnkle",
posInParent = (0, -leftLowerLegSizeY/2.0, 0),
posInChild = (0, leftFootSizeY/2.0, -leftFootSizeZ*0.33 + leftLowerLegDiameter/2.0),
parentAxis = (0, 0, 1),
childAxis = (1, 0, 0),
limits = (-0.75, 0.75, -0.75, 0.75) ).createAndFillObject()
joint.setParent(lLowerLeg)
joint.setChild(lFoot)
character.addJoint(joint)
rightFootSizeX = self.getFootSizeX(-1)
rightFootSizeY = self.getAnklePosY(-1) - self.getGroundPosY()
rightFootSizeZ = self.getFootSizeZ(-1) * 0.75
rFoot = PyUtils.RigidBody.createArticulatedTaperedBox(
name = "rFoot",
size = (rightFootSizeX,rightFootSizeY,rightFootSizeZ),
exponentSide = 20,
groundCoeffs = (0.0005,0.2),
moiScale = 3,
mass = -massScale, colour = gray )
character.addArticulatedRigidBody( rFoot )
joint = Proxys.UniversalJoint(
name = "rAnkle",
posInParent = (0, -rightLowerLegSizeY/2.0, 0),
posInChild = (0, rightFootSizeY/2.0, -rightFootSizeZ*0.33 + rightLowerLegDiameter/2.0),
parentAxis = (0, 0, -1),
childAxis = (1, 0, 0),
limits = (-0.75, 0.75, -0.75, 0.75) ).createAndFillObject()
joint.setParent(rLowerLeg)
joint.setChild(rFoot)
character.addJoint(joint)
leftToesSizeX = leftFootSizeX
leftToesSizeY = leftFootSizeY * 0.66
leftToesSizeZ = self.getFootSizeZ(1) - leftFootSizeZ
lToes = PyUtils.RigidBody.createArticulatedTaperedBox(
name = "lToes",
size = (leftToesSizeX,leftToesSizeY,leftToesSizeZ),
exponentSide = 20,
groundCoeffs = (0.0005,0.2),
moiScale = 3,
mass = -massScale, colour = gray )
character.addArticulatedRigidBody( lToes )
joint = Proxys.HingeJoint(
name = "lToeJoint",
posInParent = (0, (leftToesSizeY-leftFootSizeY)/2.0+0.003, leftFootSizeZ/2.0),
posInChild = (0, 0, -leftToesSizeZ/2.0),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.1) ).createAndFillObject()
joint.setParent(lFoot)
joint.setChild(lToes)
character.addJoint(joint)
rightToesSizeX = rightFootSizeX
rightToesSizeY = rightFootSizeY * 0.66
rightToesSizeZ = self.getFootSizeZ(-1) - rightFootSizeZ
rToes = PyUtils.RigidBody.createArticulatedTaperedBox(
name = "rToes",
size = (rightToesSizeX,rightToesSizeY,rightToesSizeZ),
exponentSide = 20,
groundCoeffs = (0.0005,0.2),
moiScale = 3,
mass = -massScale, colour = gray )
character.addArticulatedRigidBody( rToes )
joint = Proxys.HingeJoint(
name = "rToeJoint",
posInParent = (0, (rightToesSizeY-rightFootSizeY)/2.0+0.003, rightFootSizeZ/2.0),
posInChild = (0, 0, -rightToesSizeZ/2.0),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.1) ).createAndFillObject()
joint.setParent(rFoot)
joint.setChild(rToes)
character.addJoint(joint)
return character
class _Value(object):
def __init__(self, value, minValue=None, maxValue=None):
"""Create a native value with a given maximum and minimum"""
self._value = value
if maxValue is not None and minValue is not None and maxValue < minValue :
raise ValueError( 'Max must be equal or greater than minValue!' )
self._minValue = minValue
self._maxValue = maxValue
def get(self):
return self._value
def set(self, value):
self._value = self._clamp(value)
def _clamp(self, value):
if self._minValue is not None and value < self._minValue:
return self._minValue
if self._maxValue is not None and value > self._maxValue:
return self._maxValue
return value
class _Symmetric(_Value):
def __init__(self, value, minValue=None, maxValue=None ):
"""Create a symmetric native value"""
super(_Symmetric,self).__init__(None, minValue, maxValue)
self._side = [value,value]
def getSide(self, side):
"""Gets the right side (-1) or the left side (1) value."""
return self._side[(side+1)/2]
def getRight(self):
"""Gets the right side value."""
return self._side[0]
def getLeft(self):
"""Gets the left side value."""
return self._side[1]
def setSide(self, side, value):
"""Sets the right side (-1) or the left side (1) value or both at once (0)."""
value = self._clamp(value)
if side == 0 :
self._side = [value,value]
return
if side != -1 and side != 1 :
raise IndexError( 'Side must be -1, 0 or 1.' )
self._side[(side+1)/2] = value
def setRight(self, value):
"""Sets the right side value."""
self._side[0] = self._clamp(value)
def setLeft(self, value):
"""Sets the left side value."""
self._side[1] = self._clamp(value)
def forceSymmetric(self):
"""Make sure the value is symmetric by coping the left side (1) into the right side (-1)."""
self._side[0] = self._side[1]
| [
[
8,
0,
0.0045,
0.0075,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0104,
0.0015,
0,
0.66,
0.2,
463,
0,
3,
0,
0,
463,
0,
0
],
[
1,
0,
0.0119,
0.0015,
0,
0.66,
... | [
"'''\nCreated on 2009-11-20\n\n@author: beaudoin\n'''",
"import Core, Physics, PyUtils",
"from MathLib import Vector3d, Point3d",
"class CharacterDescription(object):\n \"\"\"A simple description of a character\n Be careful: \n Left refer to the left-hand-side of the character (which is seen to th... |
'''
Created on 2009-11-23
@author: beaudoin
'''
import wx, GLUtils, PyUtils, Core, Physics, Controllers
from CharacterDescription import CharacterDescription
from CharacterScaler import CharacterScalerFront
from ToolSet import ToolSet
class Model(object):
def __init__(self):
"""Creates a new model for a character description, including the required UI."""
app = wx.GetApp()
glCanvas = app.getGLCanvas()
self._container = glCanvas.addGLUITool( GLUtils.GLUIContainer )
self._container.setVisible(False)
self._optionsObservable = PyUtils.Observable()
self._sizer = GLUtils.GLUIBoxSizer(GLUtils.GLUI_HORIZONTAL)
self._container.setSizer(self._sizer)
self.reset()
self._toolSet = ToolSet(app.getToolPanel(), self)
def isSymmetric(self):
"""True if the character is forced to be symmetrical."""
return self._characterDescription.isSymmetric()
def setSymmetric(self, value):
"""Indicates if the character is forced to be symmetrical."""
if value == self.isSymmetric() : return
self._characterDescription.setSymmetric(value)
self._optionsObservable.notifyObservers()
def displayInterface(self, display):
"""Indicates wheter the interface for scaling the character should be displayed."""
if display != self.getDisplayInterface() :
self._container.setVisible(display)
self._container.getParent().layout()
self._optionsObservable.notifyObservers()
def getDisplayInterface(self):
"""Indicates wheter the interface for scaling the character is currently displayed."""
return self._container.isVisible()
def addOptionsObserver(self, observer):
"""Adds an observer for the options of the instant character model."""
self._optionsObservable.addObserver(observer)
def reset(self):
"""Resets character description to default values."""
self._characterDescription = CharacterDescription()
self._container.detachAllChildren()
self._frontScaler = CharacterScalerFront( self._container, characterDescription = self._characterDescription, minWidth = 250, minHeight = 500 )
# self._sideScaler = CharacterScalerSide( self._container, characterDescription = self._characterDescription, minWidth = 125, minHeight = 250 )
self._sizer.add(self._frontScaler)
# self._sizer.add(self._sideScaler)
self._container.getParent().layout()
self._optionsObservable.notifyObservers()
def create(self):
"""Creates the instant character based on the available description. Attach a reasonable controller, if available."""
app = wx.GetApp()
try:
wrappedController = PyUtils.wrapCopy( app.getController(0) )
except IndexError:
wrappedController = None
try:
character = app.getCharacter(0)
previousMass = character.getMass()
except IndexError:
previousMass = None
app.deleteAllObjects()
PyUtils.load( "RigidBodies.FlatGround" )
character = self._characterDescription.createCharacter()
character.computeMass()
app.addCharacter(character)
if wrappedController is not None:
controller = wrappedController.createAndFillObject(None, character)
if previousMass is not None:
massRatio = character.getMass() / previousMass
controller.scaleGains( massRatio )
app.addController(controller)
controller.setStance( Core.LEFT_STANCE )
self.connectController()
return character
def connectController(self, useCurrentSliders = True):
"""Connects the current controller to a behaviour."""
app = wx.GetApp()
worldOracle = app.getWorldOracle()
character = app.getCharacter(0)
controller = app.getController(0)
behaviour = Core.TurnController(character, controller, worldOracle)
behaviour.initializeDefaultParameters()
controller.setBehaviour(behaviour)
if useCurrentSliders :
behaviour.requestVelocities(self._toolSet.getCurrentSpeed(), 0);
behaviour.requestStepTime(self._toolSet.getCurrentDuration());
behaviour.requestCoronalStepWidth(self._toolSet.getCurrentStepWidth());
behaviour.requestHeading(0);
behaviour.conTransitionPlan();
self._toolSet.update()
app.takeSnapshot()
def getDesiredDuration(self):
"""Return the desired duration of a step."""
try:
return wx.GetApp().getController(0).getBehaviour().getDesiredStepTime()
except Exception:
return 0
def setDesiredDuration(self, duration):
"""Sets the desired duration of a step."""
try:
wx.GetApp().getController(0).getBehaviour().requestStepTime(duration)
except Exception:
pass
def getDesiredSpeed(self):
"""Return the desired speed of the character."""
try:
return wx.GetApp().getController(0).getBehaviour().getDesiredVelocitySagittal()
except Exception:
return 0
def setDesiredSpeed(self, speed):
"""Sets the desired speed of the character."""
try:
wx.GetApp().getController(0).getBehaviour().requestVelocities(speed, 0)
except Exception:
pass
def getDesiredStepWidth(self):
"""Return the desired step width of the character."""
try:
return wx.GetApp().getController(0).getBehaviour().getCoronalStepWidth()
except Exception:
return 0
def setDesiredStepWidth(self, stepWidth):
"""Sets the desired step width of the character."""
try:
wx.GetApp().getController(0).getBehaviour().requestCoronalStepWidth(stepWidth)
except Exception:
pass | [
[
8,
0,
0.0182,
0.0303,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0424,
0.0061,
0,
0.66,
0.2,
666,
0,
6,
0,
0,
666,
0,
0
],
[
1,
0,
0.0545,
0.0061,
0,
0.66,
... | [
"'''\nCreated on 2009-11-23\n\n@author: beaudoin\n'''",
"import wx, GLUtils, PyUtils, Core, Physics, Controllers",
"from CharacterDescription import CharacterDescription",
"from CharacterScaler import CharacterScalerFront",
"from ToolSet import ToolSet",
"class Model(object):\n \n def __init__(self)... |
from Model import Model
from CharacterDescription import CharacterDescription
from CharacterScaler import CharacterScalerFront
from ToolSet import ToolSet | [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
929,
0,
1,
0,
0,
929,
0,
0
],
[
1,
0,
0.5,
0.25,
0,
0.66,
0.3333,
869,
0,
1,
0,
0,
869,
0,
0
],
[
1,
0,
0.75,
0.25,
0,
0.66,
0.6... | [
"from Model import Model",
"from CharacterDescription import CharacterDescription",
"from CharacterScaler import CharacterScalerFront",
"from ToolSet import ToolSet"
] |
'''
Created on 2009-11-23
@author: beaudoin
'''
import UI, wx
class ToolSet(UI.ToolSets.ToolsetBase):
def __init__(self, toolPanel, model):
"""Adds a tool set for the instant character to a toolpanel."""
super(ToolSet,self).__init__()
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Instant Character" )
self.addOption( "Edit character", model.getDisplayInterface, model.displayInterface )
self.addOption( "Symmetrical", model.isSymmetric, model.setSymmetric )
self.addButton( "Create", model.create )
self.addButton( "Reset character", model.reset )
self._speedSlider, self._speedSliderData = self.addSlider( "Speed", min=-1, max=5.0, step=0.01, getter = model.getDesiredSpeed, setter = model.setDesiredSpeed)
self._durationSlider, self._durationSliderData = self.addSlider( "Duration", min=0.2, max=1.0, step=0.01, getter = model.getDesiredDuration, setter = model.setDesiredDuration)
self._stepWidthSlider, self._stepWidthSliderData = self.addSlider( "Width", min=0.0, max=0.3, step=0.01, getter = model.getDesiredStepWidth, setter = model.setDesiredStepWidth)
# Add this as an observer
model.addOptionsObserver(self)
# Initial update
self.update()
def getCurrentSpeed(self):
"""Gets the speed as currently shown on the slider."""
return self._speedSliderData.getSliderValue()
def getCurrentDuration(self):
"""Gets the duration as currently shown on the slider."""
return self._durationSliderData.getSliderValue()
def getCurrentStepWidth(self):
"""Gets the step width as currently shown on the slider."""
return self._stepWidthSliderData.getSliderValue() | [
[
8,
0,
0.0667,
0.1111,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1556,
0.0222,
0,
0.66,
0.5,
587,
0,
2,
0,
0,
587,
0,
0
],
[
3,
0,
0.6111,
0.8,
0,
0.66,
... | [
"'''\nCreated on 2009-11-23\n\n@author: beaudoin\n'''",
"import UI, wx",
"class ToolSet(UI.ToolSets.ToolsetBase):\n \n def __init__(self, toolPanel, model):\n \"\"\"Adds a tool set for the instant character to a toolpanel.\"\"\"\n \n super(ToolSet,self).__init__()\n \n ... |
'''
Created on 2009-09-02
@author: beaudoin
'''
import Proxy, Member
import App
cls = App.ObservableList
ObservableList = Proxy.create( cls,
members = [
Member.ObjectList( 'objects', None, cls.get, cls.getCount, cls.add, embedInParentNode = True ),
] )
cls = App.SnapshotBranch
SnapshotBranch = Proxy.create( cls,
nameGetter = lambda object: "Branch",
icon = "../data/ui/snapshotBranch.png",
members = [
Member.ObjectList( 'snapshots', None, cls.getSnapshot, cls.getSnapshotCount, None, embedInParentNode = True ),
] )
cls = App.Snapshot
Snapshot = Proxy.create( cls,
nameGetter = cls.getName,
icon = "../data/ui/snapshotIcon.png",
members = [
Member.ObjectList( 'branches', None, cls.getBranch, cls.getBranchCount, None, embedInParentNode = True ),
] )
| [
[
8,
0,
0.0968,
0.1613,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2258,
0.0323,
0,
0.66,
0.125,
363,
0,
2,
0,
0,
363,
0,
0
],
[
1,
0,
0.2581,
0.0323,
0,
0.66,... | [
"'''\nCreated on 2009-09-02\n\n@author: beaudoin\n'''",
"import Proxy, Member",
"import App",
"cls = App.ObservableList",
"ObservableList = Proxy.create( cls, \n members = [\n Member.ObjectList( 'objects', None, cls.get, cls.getCount, cls.add, embedInParentNode = True ),\n ] )",
"cls = App.Sn... |
'''
Created on 2009-09-22
@author: beaudoin
This module contains classes representing different possible type of data members within proxy object.
A member knows how to get/set itself from/to the wrapped object.
'''
import MathLib
import PyUtils
class TopLevel(object):
def __init__(self, type, name, default, editable = False, fancyName = None, isObject = False ):
self.name = name
self.default = default
self.editable = editable
self.isObject = isObject
self.type = type
self.fancyName = fancyName
if fancyName == None:
self.fancyName = PyUtils.unCamelCase(name)
def basicInterpret(self,value):
"""Performs basic interpretation, does not coerce into type."""
if self.type not in (str,unicode) and isinstance(value, basestring) :
return eval(value,dict(__builtins__=__builtins__))
return value
def interpret(self, value):
"""This method lets a user have different ways to input a member."""
value = self.basicInterpret(value)
if self.type is None or value is None or isinstance(value, self.type): return value
return self.type(value)
def format(self, value):
"""This method returns the preferred representation of the data."""
return value
class Basic(TopLevel):
def __init__( self, type, name, default, getter, setter, editable = True, fancyName = None, isObject = False ):
super( Basic, self ).__init__( type, name, default, editable, fancyName, isObject )
self._getter = getter
self._setter = setter
def get(self, object):
if self._getter is None : return None
return self._getter(object)
def set(self, object, value, container = None):
if self._setter is None : return
if value is None : return
try: self._setter(object, value, container)
except ( TypeError, NotImplementedError ): self._setter(object, value)
class Tuple(Basic):
"""Can be used when setter takes multiple parameters and getter returns multiple parameters. Otherwise use Basic with type tuple."""
def __init__( self, name, default, getter, setter, editable = True, fancyName = None ):
super( Tuple, self ).__init__( tuple, name, default, getter, setter, editable, fancyName, False )
def get(self, object):
if self._getter is None : return None
# TODO do something here!
return None
def set(self, object, value, container = None):
if self._setter is None : return
if value is None : return
self._setter(object, *value)
class Enum(Basic):
def __init__( self, enum, name, default, getter, setter, editable = True, fancyName = None ):
"""Pass the enum class you want to use for this member"""
super( Enum, self ).__init__( int, name, default, getter, setter, editable, fancyName, False )
self.enum = enum
def interpret(self, value):
if value is None : return None
elif isinstance(value, basestring) : return self.enum.toInt( value )
else : return int( value )
def format(self, value):
return self.enum.toStr(value)
class Vector3d(Basic):
def __init__( self, name, default, getter, setter, editable = True, fancyName = None ):
super( Vector3d, self ).__init__( MathLib.Vector3d, name, default, getter, setter, editable, fancyName, False )
def interpret(self, value):
value = self.basicInterpret(value)
if isinstance(value, MathLib.Vector3d) : return value
else : return PyUtils.toVector3d( value )
def format(self, value):
return PyUtils.fromVector3d(value)
class Point3d(Basic):
def __init__( self, name, default, getter, setter, editable = True, fancyName = None ):
super( Point3d, self ).__init__( MathLib.Point3d, name, default, getter, setter, editable, fancyName, False )
def interpret(self, value):
value = self.basicInterpret(value)
if isinstance(value, MathLib.Point3d) : return value
else : return PyUtils.toPoint3d( value )
def format(self, value):
return PyUtils.fromPoint3d(value)
class Quaternion(Basic):
def __init__( self, name, default, getter, setter, editable = True, fancyName = None ):
super( Quaternion, self ).__init__( MathLib.Quaternion, name, default, getter, setter, editable, fancyName, False )
def interpret(self, value):
value = self.basicInterpret(value)
if isinstance(value, MathLib.Quaternion) : return value
else : return PyUtils.angleAxisToQuaternion( value )
def format(self, value):
return PyUtils.angleAxisFromQuaternion(value)
class Trajectory1d(Basic):
def __init__( self, name, default, getter, setter, editable = True, fancyName = None ):
super( Trajectory1d, self ).__init__( MathLib.Trajectory1d, name, default, getter, setter, editable, fancyName, False )
def interpret(self, value):
value = self.basicInterpret(value)
if isinstance(value, MathLib.Trajectory1d) : return value
else : return PyUtils.toTrajectory1d( value )
def format(self, value):
return PyUtils.fromTrajectory1d(value)
class Object(Basic):
def __init__( self, name, default, getter, setter, editable = True, fancyName = None ):
super( Object, self ).__init__( None, name, default, getter, setter, editable, fancyName, True )
def getObject(self, object):
"""Return unwrapped object."""
return super( Object, self ).get(object)
def get(self, object):
return PyUtils.wrap( self.getObject(object) )
def set(self, object, valueProxy, container = None):
if valueProxy is None : return
try:
# Try to re-fill the existing object
value = self.getObject(object)
try: value.beginBatchChanges()
except AttributeError: pass
try:
valueProxy.fillObject( value, object )
finally:
try: value.endBatchChanges()
except AttributeError: pass
except(AttributeError, TypeError):
value = valueProxy.createObject()
valueProxy.fillObject( value, object )
super( Object, self ).set(object,value,container)
class ObjectList(TopLevel):
def __init__( self, name, default, getAtIndex, getCount, addToContainer, editable = True, fancyName = None, embedInParentNode = False, groupIcon = "../data/ui/objectListIcon.png" ):
super( ObjectList, self ).__init__( None, name, default, editable, fancyName, True )
self._getAtIndex = getAtIndex
self._getCount = getCount
self._addToContainer = addToContainer
self.embedInParentNode = embedInParentNode
self.groupIcon = groupIcon
def getObject(self, object, i):
"""Return unwrapped object."""
return self._getAtIndex(object,i)
def getCount(self, object):
return self._getCount(object)
def get(self, object):
result = []
for i in range( self.getCount(object) ) :
result.append( PyUtils.wrap( self.getObject(object,i) ) )
return result
def _set(self, object, i, valueProxy, container):
if valueProxy is None : return
try:
# Try to re-fill the existing object
if i >= self.getCount(object) : raise IndexError;
value = self.getObject(object, i)
try: value.beginBatchChanges()
except AttributeError: pass
try:
valueProxy.fillObject( value, object )
finally:
try: value.endBatchChanges()
except AttributeError: pass
except(AttributeError, TypeError, IndexError, ValueError):
value = valueProxy.createObject()
if value is None : return
valueProxy.fillObject( value, object )
try: self._addToContainer(object, value, container)
except ( TypeError, NotImplementedError ): self._addToContainer(object, value)
def set(self, object, valueProxyList, container = None):
if valueProxyList is None : return
PyUtils.callOnObjectOrListAndEnumerate( valueProxyList, lambda i, valueProxy: self._set(object,i,valueProxy,container) )
| [
[
8,
0,
0.0206,
0.0367,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0459,
0.0046,
0,
0.66,
0.0833,
209,
0,
1,
0,
0,
209,
0,
0
],
[
1,
0,
0.0505,
0.0046,
0,
0.66... | [
"'''\nCreated on 2009-09-22\n\n@author: beaudoin\n\nThis module contains classes representing different possible type of data members within proxy object.\nA member knows how to get/set itself from/to the wrapped object.\n'''",
"import MathLib",
"import PyUtils",
"class TopLevel(object):\n \n def __init... |
'''
Created on 2009-09-03
@author: beaudoin
'''
import Proxy
import Member
import Physics
def getArb(af, arbName):
if arbName is None : return None
arb = af.getARBByName( arbName )
if arb is None:
raise KeyError( "Articulated rigid body '"+arbName+"' not found in articulated figure '"+af.getName()+"'." )
return arb
def setParent(joint, arbName, af):
joint.setParent( getArb(af,arbName) )
def setChild(joint, arbName, af):
joint.setChild( getArb(af,arbName) )
def getParent(joint):
return joint.getParent().getName()
def getChild(joint):
return joint.getChild().getName()
cls = Physics.Joint
Joint = Proxy.create( cls,
members = [
Member.Basic( str, 'name', 'UnnamedJoint', cls.getName, cls.setName ),
Member.Basic( str, 'parent', None, getParent, setParent ),
Member.Basic( str, 'child', None, getChild, setChild ),
Member.Point3d( 'posInParent', (0.0,0.0,0.0), cls.getParentJointPosition, cls.setParentJointPosition ),
Member.Point3d( 'posInChild', (0.0,0.0,0.0), cls.getChildJointPosition, cls.setChildJointPosition )
] )
cls = Physics.BallInSocketJoint
BallInSocketJoint = Proxy.create( cls, parent = Joint, caster = Physics.castToBallInSocketJoint,
members = [
Member.Vector3d( 'swingAxis1', (1.0,0.0,0.0), cls.getSwingAxis1, cls.setSwingAxis1 ),
Member.Vector3d( 'swingAxis2', None, cls.getSwingAxis2, cls.setSwingAxis2 ),
Member.Vector3d( 'twistAxis', None, cls.getTwistAxis, cls.setTwistAxis ),
Member.Tuple( 'limits', (-3.1416,3.1416,-3.1416,3.1416,-3.1416,3.1416), None, cls.setJointLimits )
] )
cls = Physics.UniversalJoint
UniversalJoint = Proxy.create( cls, parent = Joint, caster = Physics.castToUniversalJoint,
members = [
Member.Vector3d( 'parentAxis', (1.0,0.0,0.0), cls.getParentAxis, cls.setParentAxis ),
Member.Vector3d( 'childAxis', (1.0,0.0,0.0), cls.getChildAxis, cls.setChildAxis ),
Member.Tuple( 'limits', (-3.1416,3.1416,-3.1416,3.1416), None, cls.setJointLimits )
] )
cls = Physics.HingeJoint
HingeJoint = Proxy.create( cls, parent = Joint, caster = Physics.castToHingeJoint,
members = [
Member.Vector3d( 'axis', (1.0,0.0,0.0), cls.getAxis, cls.setAxis ),
Member.Tuple( 'limits', (-3.1416,3.1416), None, cls.setJointLimits )
] )
cls = Physics.StiffJoint
StiffJoint = Proxy.create( cls, parent = Joint, caster = Physics.castToStiffJoint )
| [
[
8,
0,
0.0435,
0.0725,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1159,
0.0145,
0,
0.66,
0.0556,
363,
0,
1,
0,
0,
363,
0,
0
],
[
1,
0,
0.1304,
0.0145,
0,
0.66... | [
"'''\nCreated on 2009-09-03\n\n@author: beaudoin\n'''",
"import Proxy",
"import Member",
"import Physics",
"def getArb(af, arbName):\n if arbName is None : return None\n arb = af.getARBByName( arbName )\n if arb is None: \n raise KeyError( \"Articulated rigid body '\"+arbName+\"' not found i... |
'''
Created on 2009-09-24
@author: beaudoin
'''
import Utils, wx, PyUtils
import Member
from UI.InfoTree import getIconIndex
class NodeData(Utils.Observer):
"""
This class wraps one object presented in a node of the tree.
The wrapped object must be observable (either derived from Utils.Observable for a C++ object
or App.Observable for a Python object).
An object keeps an ordered list of its child objects.
An object also has a list of properties that can be edited or not.
"""
def __init__(self, memberName, object, tree, treeItemId, container = None, index = None):
"""Subclasses must calls this constructor.
Pass a string giving the member name for this node (member should be either App.Proxys.Member.Object or App.Proxys.Member.ObjectList.
Pass the object to observe, the member information for this object (from App.Proxys.Member).
Also pass the tree and the treeItemId where this object is found.
In container, pass the object that contains this node (in an HAS_A or HAS_MANY relationship)
In index, pass the index of this node within its container (in an HAS_MANY relationship)
"""
super( NodeData, self ).__init__()
self._memberName = memberName
self._object = object
self._tree = tree
self._treeItemId = treeItemId
self._container = container
self._index = index
if object is None :
self._proxyClass = None
iconIndex = getIconIndex( '../data/ui/noneIcon.png' )
else:
object.addObserver( self )
self._proxyClass = PyUtils.getProxyClass(object)
iconIndex = getIconIndex( self._proxyClass.getIcon() )
self._tree.SetItemImage( self._treeItemId, iconIndex )
self._subMemberNodes = []
if self._proxyClass is not None :
for subMember in self._proxyClass.getObjectMembers():
self._subMemberNodes.append( _createSubMemberNode(subMember, self._tree, self._treeItemId, object) )
tree.SetItemPyData( treeItemId, self )
# Initial update
self.update()
def __del__(self):
try: self._object.deleteObserver( self )
except AttributeError: pass
def update(self, data = None):
"""Called whenever the attached object is updated."""
self._tree.updateLock()
if self._object is not None :
name = self._proxyClass.getName(self._object)
else:
name = "None (%s)" % self._memberName
self._tree.SetItemText( self._treeItemId, name )
for subMemberNode in self._subMemberNodes:
subMemberNode.update( self._object )
self._tree.updateUnlock()
def getObject(self):
"""Access the object attached to this NodeData."""
return self._object
def _createSubMemberNode( subMember, tree, parentTreeItemId, container ):
"""
Private.
Adds a node to the tree if the subMember is a Member.Object or a non-embedded Member.ObjectList.
If it is an embedded Member.ObjectList, no node is added.
Then creates a subMemberNode that contains enough information to watch this member.
"""
if isinstance( subMember, Member.Object ):
return subMemberObjectNode(subMember, tree, container, parentTreeItemId)
elif isinstance( subMember, Member.ObjectList ):
if subMember.embedInParentNode:
return subMemberEmbeddedObjectListNode(subMember, tree, container, parentTreeItemId)
else:
return subMemberObjectListNode(subMember, tree, container, parentTreeItemId)
else:
raise TypeError( "Unknown object member type: '%s'." % subMember.__class__.__name__ )
class subMemberNode(object):
"""Private class. Information for a submember node."""
def __init__(self, subMember, tree, container):
self._member = subMember
self._tree = tree
self._container = container
class subMemberObjectNode(subMemberNode):
"""Private class. Information for a submember node that wraps a single object."""
def __init__(self, subMember, tree, container, parentTreeItemId):
"""Create a new node inside the tree that wraps the specified submember"""
super(subMemberObjectNode,self).__init__(subMember, tree, container)
self._treeItemId = tree.AppendItem( parentTreeItemId, "" )
if tree.isAutoVisible():
tree.EnsureVisible(self._treeItemId)
def getObject(self):
"""Returns the object associated with this node, or None if no object is associated."""
nodeData = self._tree.GetItemPyData( self._treeItemId )
if nodeData is None :
raise AttributeError( 'No data attached to tree node!' );
return nodeData.getObject()
def update(self, object):
"""Updates the node so that it contains the specified object."""
subObject = self._member.getObject(object)
try:
currentObject = self.getObject()
if PyUtils.sameObject(currentObject, subObject) : return
except AttributeError: pass
nodeData = NodeData( self._member.name, subObject, self._tree, self._treeItemId, self._container )
class subMemberAbstractObjectListNode(subMemberNode):
"""
Private class. provides some methods shared by embedded and non-embedded node lists.
Subclasses must define insertChild()
"""
def __init__(self, subMember, tree, container):
super(subMemberAbstractObjectListNode,self).__init__(subMember, tree, container)
self._subTreeItemIds = []
def getObject(self, index):
"""Returns the object number index associated with this node, or None if no object is associated.
Raises a IndexError if the index is out of bound"""
nodeData = self._tree.GetItemPyData( self._subTreeItemIds[index] )
if nodeData is None :
raise AttributeError( 'No data attached to tree node!' );
return nodeData.getObject()
def removeChildren(self, start=None, end=None):
"""Private. This method removes objects from a tree and a children list.
Objects removed are in the range [start,end).
Runs from object 0 when start==None and until the end when end==None."""
if start is None : start = 0
if end is None : end = len( self._subTreeItemIds )
for child in self._subTreeItemIds[start:end]:
self._tree.Delete(child)
del self._subTreeItemIds[start:end]
def update(self, object):
"""Adjusts the node's _subTreeItemIds list so that it matches an input object list.
TreeItemId s will be deleted or inserted into _subTreeItemIds based on its current content and
that of the input object list."""
count = self._member.getCount(object)
for i in range(count):
inObject = self._member.getObject(object,i)
try:
outObject = self.getObject(i)
areSameObject = PyUtils.sameObject(inObject, outObject)
except IndexError:
outObject = None
areSameObject = False
if not areSameObject:
# Need to delete or insert
# First, check how many objects we should delete
delete = 1
try:
while not PyUtils.sameObject( inObject, self.getObject(i+delete) ) :
delete += 1
except IndexError:
delete = 0
if delete > 0 :
# Delete the specified objects
self.removeChildren(i,i+delete)
else :
# Insert the specified object
self.insertChild(i, inObject)
# Delete any remaining objects
self.removeChildren(count)
class subMemberObjectListNode(subMemberAbstractObjectListNode):
"""Private class. Information for a submember node that wraps a single object."""
def __init__(self, subMember, tree, container, parentTreeItemId):
"""Create a new node inside the tree that wraps the specified submember"""
super(subMemberObjectListNode,self).__init__(subMember, tree, container)
self._listNodeTreeItemId = tree.AppendItem( parentTreeItemId, subMember.fancyName )
tree.SetItemPyData( self._listNodeTreeItemId, (subMember, container) )
iconIndex = getIconIndex( subMember.groupIcon )
tree.SetItemImage( self._listNodeTreeItemId, iconIndex )
if tree.isAutoVisible():
tree.EnsureVisible(self._listNodeTreeItemId)
def insertChild(self, pos, object):
"""Private. Wraps the specified object in a new NodeData and inserts it
at the specified position in the tree."""
treeItemId = self._tree.InsertItemBefore( self._listNodeTreeItemId, pos, "" )
nodeData = NodeData( self._member.name, object, self._tree, treeItemId, self._container, pos )
self._subTreeItemIds.insert(pos, treeItemId)
if self._tree.isAutoVisible():
self._tree.EnsureVisible(treeItemId)
class subMemberEmbeddedObjectListNode(subMemberAbstractObjectListNode):
"""Private class. Information for a submember node that wraps a single object."""
def __init__(self, subMember, tree, container, parentTreeItemId):
"""Create a new node inside the tree that wraps the specified submember"""
super(subMemberEmbeddedObjectListNode,self).__init__(subMember, tree, container)
self._parentTreeItemId = parentTreeItemId
self._previousTreeItemId = tree.GetLastChild(parentTreeItemId) # Will be invalid if there is no last child
def insertChild(self, pos, object):
"""Private. Wraps the specified object in a new NodeData and inserts it
at the specified position in the tree."""
if pos == 0:
# Insertion at the beginning, tricky.
if len(self._subTreeItemIds) == 0 :
# Nothing in the list, add after self._previousTreeItemId
if not self._previousTreeItemId.IsOk():
# At the very top of the tree
treeItemId = self._tree.InsertItemBefore( self._parentTreeItemId, 0, "" )
else:
treeItemId = self._tree.InsertItem( self._parentTreeItemId, self._previousTreeItemId, "" )
else:
# Insert before first object in the tree
prevItemId = self.tree.GetPrevSibling( self._parentTreeItemId, self._subTreeItemIds[0], "" )
if not prevItemId.IsOk():
# At the very top of the tree
treeItemId = self._tree.InsertItemBefore( self._parentTreeItemId, 0, "" )
else:
treeItemId = self._tree.InsertItem( self._parentTreeItemId, prevItemId, "" )
else:
# Insertion in the middle, easy
treeItemId = self._tree.InsertItem( self._parentTreeItemId, self._subTreeItemIds[pos-1], "" )
nodeData = NodeData( self._member.name, object, self._tree, treeItemId, self._container, pos )
self._subTreeItemIds.insert(pos, treeItemId)
if self._tree.isAutoVisible():
self._tree.EnsureVisible(treeItemId)
| [
[
8,
0,
0.0121,
0.0202,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0283,
0.004,
0,
0.66,
0.1,
842,
0,
3,
0,
0,
842,
0,
0
],
[
1,
0,
0.0324,
0.004,
0,
0.66,
... | [
"'''\nCreated on 2009-09-24\n\n@author: beaudoin\n'''",
"import Utils, wx, PyUtils",
"import Member",
"from UI.InfoTree import getIconIndex",
"class NodeData(Utils.Observer):\n \"\"\"\n This class wraps one object presented in a node of the tree.\n The wrapped object must be observable (either deri... |
'''
Created on 2009-09-03
@author: beaudoin
'''
import Proxy
import Member
from PyUtils import enum
import Controllers
import wx, Core
def getControlParams(controller, i):
if i == 0 :
return controller.getRootControlParams()
else :
return controller.getControlParams(i-1)
def getControlParamsCount(controller):
return controller.getControlParamsCount() + 1
cls = Core.SimBiController
SimBiController = Proxy.create( cls, caster = Core.castToSimBiController, loader = wx.GetApp().addController,
nameGetter = cls.getName,
icon = "../data/ui/controllerIcon.png",
members = [
Member.Basic( str, 'name', 'UnnamedSimBiController', cls.getName, cls.setName ),
Member.Basic( int, 'startingState', 0, cls.getStartingState, cls.setStartingState ),
Member.Basic( float, 'stanceHipDamping', 25, cls.getStanceHipDamping, cls.setStanceHipDamping ),
Member.Basic( float, 'stanceHipMaxVelocity', 4, cls.getStanceHipMaxVelocity, cls.setStanceHipMaxVelocity ),
Member.ObjectList( 'controlParamsList', None, getControlParams, getControlParamsCount, cls.addControlParams ),
Member.ObjectList( 'states', None, cls.getState, cls.getStateCount, cls.addState, embedInParentNode = True )
] )
def setJoint(joint, jointName, controller):
if not joint.setJoint( controller.getCharacter().getJointByName(jointName) ):
raise ValueError( "Setting the wrong joint." )
cls = Core.ControlParams
ControlParams = Proxy.create( cls, caster = Core.castToControlParams,
nameGetter = cls.getJointName,
icon = "../data/ui/controlParamsIcon.png",
members = [
Member.Basic( str, 'joint', 'noJointName', cls.getJointName, setJoint, editable = False ),
Member.Basic( float, 'kp', None, cls.getKp, cls.setKp ),
Member.Basic( float, 'kd', None, cls.getKd, cls.setKd ),
Member.Basic( float, 'tauMax', 1000.0, cls.getMaxAbsTorque, cls.setMaxAbsTorque ),
Member.Vector3d( 'scale', (1.0,1.0,1.0), cls.getScale, cls.setScale )
] )
TransitionOn = enum( 'FOOT_CONTACT', 'TIME_UP' )
TO_FOOT_CONTACT = TransitionOn.toInt( 'FOOT_CONTACT' )
TO_TIME_UP = TransitionOn.toInt( 'TIME_UP' )
Stance = enum( { 'LEFT' : Core.SimBiConState.STATE_LEFT_STANCE ,
'RIGHT' : Core.SimBiConState.STATE_RIGHT_STANCE,
'REVERSE' : Core.SimBiConState.STATE_REVERSE_STANCE,
'KEEP' : Core.SimBiConState.STATE_KEEP_STANCE } )
def getTransitionOn(state):
if state.getTransitionOnFootContact(): return TO_FOOT_CONTACT
else: return TO_TIME_UP
def setTransitionOn(state, value):
if value == TO_FOOT_CONTACT : state.setTransitionOnFootContact(True)
elif value == TO_TIME_UP : state.setTransitionOnFootContact(False)
else: raise ValueError( "SimBiConState member 'transitionOn' has invalid value: '" + str(value) + "'" )
cls = Core.SimBiConState
SimBiConState = Proxy.create( cls, caster = Core.castToSimBiConState,
nameGetter = cls.getName,
icon = "../data/ui/fsmstateIcon.png",
members = [
Member.Basic( str, 'name', 'UnnamedSimBiConState', cls.getName, cls.setName ),
Member.Basic( int, 'nextStateIndex', None, cls.getNextStateIndex, cls.setNextStateIndex ),
Member.Enum( TransitionOn, 'transitionOn', TO_FOOT_CONTACT, getTransitionOn, setTransitionOn ),
Member.Enum( Stance, 'stance', Core.SimBiConState.STATE_REVERSE_STANCE, cls.getStance, cls.setStance ),
Member.Basic( float, 'duration', 0.5, cls.getDuration, cls.setDuration ),
Member.Trajectory1d( 'dTrajX', None, cls.getDTrajX, cls.setDTrajX ),
Member.Trajectory1d( 'dTrajZ', None, cls.getDTrajZ, cls.setDTrajZ ),
Member.Trajectory1d( 'vTrajX', None, cls.getVTrajX, cls.setVTrajX ),
Member.Trajectory1d( 'vTrajZ', None, cls.getVTrajZ, cls.setVTrajZ ),
Member.ObjectList( 'externalForces', None, cls.getExternalForce, cls.getExternalForceCount, cls.addExternalForce ),
Member.ObjectList( 'trajectories', None, cls.getTrajectory, cls.getTrajectoryCount, cls.addTrajectory, embedInParentNode = True )
] )
cls = Core.ExternalForce
ExternalForce = Proxy.create( cls, caster = Core.castToExternalForce,
nameGetter = cls.getBodyName,
icon = "../data/ui/externalForceIcon.png",
members = [
Member.Basic( str, 'body', 'UnnamedExternalForce', cls.getBodyName, cls.setBodyName ),
Member.Trajectory1d( 'forceX', None, cls.getForceX, cls.setForceX ),
Member.Trajectory1d( 'forceY', None, cls.getForceY, cls.setForceY ),
Member.Trajectory1d( 'forceZ', None, cls.getForceZ, cls.setForceZ ),
Member.Trajectory1d( 'torqueX', None, cls.getTorqueX, cls.setTorqueX ),
Member.Trajectory1d( 'torqueY', None, cls.getTorqueY, cls.setTorqueY ),
Member.Trajectory1d( 'torqueZ', None, cls.getTorqueZ, cls.setTorqueZ )
] )
ReferenceFrame = enum( 'PARENT_RELATIVE', 'CHARACTER_RELATIVE' )
RF_PARENT_RELATIVE = ReferenceFrame.toInt( 'PARENT_RELATIVE' )
RF_CHARACTER_RELATIVE = ReferenceFrame.toInt( 'CHARACTER_RELATIVE' )
def getReferenceFrame(trajectory):
if trajectory.isRelativeToCharacterFrame(): return RF_CHARACTER_RELATIVE
else: return RF_PARENT_RELATIVE
def setReferenceFrame(trajectory, value):
if value == RF_PARENT_RELATIVE : trajectory.setRelativeToCharacterFrame(False)
elif value == RF_CHARACTER_RELATIVE : trajectory.setRelativeToCharacterFrame(True)
else: raise ValueError( "SimBiConTrajectory member 'referenceFrame' has invalid value: '" + str(value) + "'" )
cls = Core.Trajectory
Trajectory = Proxy.create( cls, caster = Core.castToTrajectory,
nameGetter = cls.getJointName,
icon = "../data/ui/trajectoryIcon.png",
members = [
Member.Basic( str, 'joint', 'UnnamedTrajectory', cls.getJointName, cls.setJointName ),
Member.Trajectory1d( 'strength', None, cls.getStrengthTrajectory, cls.setStrengthTrajectory ),
Member.Enum( ReferenceFrame, 'referenceFrame', RF_PARENT_RELATIVE, getReferenceFrame, setReferenceFrame ),
Member.ObjectList( 'components', None, cls.getTrajectoryComponent, cls.getTrajectoryComponentCount, cls.addTrajectoryComponent, embedInParentNode = True )
] )
ReverseOnStance = enum( { 'LEFT' : Core.TrajectoryComponent.ROS_LEFT ,
'RIGHT' : Core.TrajectoryComponent.ROS_RIGHT,
'DONT_REVERSE' : Core.TrajectoryComponent.ROS_DONT_REVERSE } )
def getTrajectoryComponentName(trajectoryComponent):
"""Called whenever the trajectory component is updated."""
axis = trajectoryComponent.getRotationAxis()
if( axis.x != 0 and axis.y == 0 and axis.z == 0 ) :
return "X axis"
elif( axis.x == 0 and axis.y != 0 and axis.z == 0 ) :
return "Y axis"
elif( axis.x == 0 and axis.y == 0 and axis.z != 0 ) :
return "Z axis"
else :
return "Axis (%f,%f,%f)" % ( axis.x, axis.y, axis.z )
cls = Core.TrajectoryComponent
TrajectoryComponent = Proxy.create( cls, caster = Core.castToTrajectoryComponent,
nameGetter = getTrajectoryComponentName,
icon = "../data/ui/trajectoryComponentIcon.png",
members = [
Member.Vector3d( 'rotationAxis', None, cls.getRotationAxis, cls.setRotationAxis ),
Member.Enum( ReverseOnStance, 'reverseOnStance', Core.TrajectoryComponent.ROS_DONT_REVERSE, cls.getReverseOnStance, cls.setReverseOnStance),
Member.Object( 'feedback', None, cls.getFeedback, cls.setFeedback ),
Member.Trajectory1d( 'baseTrajectory', None, cls.getBaseTrajectory, cls.setBaseTrajectory ),
Member.Trajectory1d( 'dScaledTrajectory', None, cls.getDTrajScale, cls.setDTrajScale ),
Member.Trajectory1d( 'vScaledTrajectory', None, cls.getVTrajScale, cls.setVTrajScale )
] )
def getDLimits(object):
return (object.getDMin(), object.getDMax())
def setDLimits(object, value):
return object.setDLimits(*value)
def getVLimits(object):
return (object.getVMin(), object.getVMax())
def setVLimits(object, value):
return object.setVLimits(*value)
cls = Core.LinearBalanceFeedback
LinearBalanceFeedback = Proxy.create( cls, caster = Core.castToLinearBalanceFeedback,
icon = "../data/ui/feedbackIcon.png",
members = [
Member.Vector3d( 'axis', None, cls.getProjectionAxis, cls.setProjectionAxis ),
Member.Basic( float, 'cd', 0, cls.getCd, cls.setCd ),
Member.Basic( float, 'cv', 0, cls.getCv, cls.setCv ),
Member.Basic( tuple, 'dLimits', (-1000,1000), getDLimits, setDLimits ),
Member.Basic( tuple, 'vLimits', (-1000,1000), getVLimits, setVLimits )
] )
cls = Core.IKVMCController
IKVMCController = Proxy.create( cls, parent = SimBiController, caster = Core.castToIKVMCController, loader = wx.GetApp().addController,
members = [
Member.Trajectory1d( 'sagittalTrajectory', None, cls.getSwingFootTrajectoryDeltaSagittal, cls.setSwingFootTrajectoryDeltaSagittal ),
Member.Trajectory1d( 'coronalTrajectory', None, cls.getSwingFootTrajectoryDeltaCoronal, cls.setSwingFootTrajectoryDeltaCoronal ),
Member.Trajectory1d( 'heightTrajectory', None, cls.getSwingFootTrajectoryDeltaHeight, cls.setSwingFootTrajectoryDeltaHeight )
] )
cls = Controllers.DanceController
DanceController = Proxy.create( cls, parent = IKVMCController, loader = wx.GetApp().addController )
cls = Controllers.WalkController
WalkController = Proxy.create( cls, parent = IKVMCController, loader = wx.GetApp().addController )
| [
[
8,
0,
0.0156,
0.026,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0365,
0.0052,
0,
0.66,
0.0222,
363,
0,
1,
0,
0,
363,
0,
0
],
[
1,
0,
0.0417,
0.0052,
0,
0.66,... | [
"'''\nCreated on 2009-09-03\n\n@author: beaudoin\n'''",
"import Proxy",
"import Member",
"from PyUtils import enum",
"import Controllers",
"import wx, Core",
"def getControlParams(controller, i):\n if i == 0 :\n return controller.getRootControlParams()\n else :\n return controller.ge... |
'''
Created on 2009-09-22
@author: beaudoin
'''
import PyUtils
def create( wrappedClass = None, members = [], parent = None, caster = None, loader = None, verbose = True, icon = None, nameGetter = None ):
"""
Creates a new proxy class (NOT an instance).
This proxy class is meant as a wrapper to the specified wrappedClass.
It contains a specific list of members, these members should be instances of objects in App.Proxys.Member.
The order of the members is important, and will stay as specified.
If it has a parent class, then it inherits all the members from the parent class, as well as the newly specified ones,
the order is: parent's members first, then child's members.
If a member exists both in the parent and the child, then the child's takes precedence, but it appears at the position of the parent
(this allows changing member's default value, for example).
If a caster is specified, then it will be used to cast down the wrapped object whenever it's needed.
If a loader is specified, then the wrapped object can be loaded directly using the load method.
If the wrapper is verbose (default), then its representation will use the long format:
memberName = value
Also, fields having default values will not be represented.
If the wrapper is not verbose, then its representation will be short, all the values will be listed in their correct order.
In icon, specify the filename of a png to use as an icon to represent the object. Pass None to use parent's icon.
In nameGetter, specify the method to call to obtain a string representing the name of this object.
"""
kwargs = {}
for name, var in locals().items():
if name == 'kwargs' : continue
kwargs["_"+name] = var
return _create(**kwargs)
def _create( _wrappedClass, _members, _parent, _caster, _loader, _verbose, _icon, _nameGetter ):
"""Private, forwarded from create for convenience in member name."""
@classmethod
def wrap( cls, object, recursive = True ):
"""
This class method creates an instance of this proxy class wrapping the specified object.
To make sure you use the right proxy class, consider calling App.PyUtils.wrap instead.
Pass recursive = False to only wrap non-object members. The members containing object references or list of objects will not be wrapped and will be None.
"""
if cls._caster is not None : object = cls._caster(object)
kwargs = {}
for member in cls._members:
if not recursive and member.isObject: continue
kwargs[ member.name ] = member.get(object)
return cls( **kwargs )
@classmethod
def getIcon( cls ):
return cls._icon
@classmethod
def getName( cls, object ):
if cls._caster is not None : object = cls._caster(object)
try: return cls._nameGetter( object )
except TypeError: return cls.__name__
@classmethod
def getObjectMembers(cls):
return filter( lambda m : m.isObject, cls._members )
def __init__(self, *args, **kwargs):
"""
Initialize a proxy object of this proxy class.
All the members must be initialized in the order in which they appear or using keyword arguments.
For a specific list of members, look at:
self.members
"""
if len(args) > len( self._members ):
raise TypeError( "Too many arguments when creating proxy '%s'." % type(self).__name__ )
for i, member in enumerate( self._members ):
if i < len(args):
value = args[i]
else :
try:
value = kwargs[ member.name ]
del kwargs[ member.name ]
except KeyError:
value = member.default
self.__setattr__( member.name, member.interpret( value ) )
if len(kwargs) > 0 :
raise AttributeError( "Attribute '%s' not a member of proxy '%s'." % (kwargs.keys()[0], type(self).__name__) )
def __repr__(self) :
"""
Creates a representation of this proxy object. This can be evaluated provided the following includes:
from App.Proxys.All import *
"""
outMembers = []
for member in self._members:
value = self.__getattribute__(member.name)
if self._verbose and PyUtils.safeEqual(value, member.default) : continue
outMember = repr( member.format(value) )
if self._verbose: outMember = member.name + " = " + outMember
outMembers.append( outMember )
return type(self).__name__ + "(" + ','.join(outMembers) + ")"
def setValueAndUpdateObject(self, memberName, value, object, container = None):
"""
Sets the specified value of the specified member and updates the object.
As a container, specify the object (not proxy object) to which this object is attached with an HAS_A or HAS_MANY relationship.
"""
info = self._memberDict[memberName]
newValue = info.interpret(value)
if PyUtils.safeEqual( newValue, self.__getattribute__(memberName) ) : return
self.__setattr__(memberName, newValue)
info.set(object, newValue, container )
def getValueAndInfo(self, index):
"""
Returns a 2-tuple (value, info) for the ith member of this wrapped object.
'value' is the member's value
'info' is a class from module App.Proxys.Member that describes this member
"""
info = self._members[index]
value = self.__getattribute__(info.name)
return ( value, info )
def getMemberCount(self):
"""
Returns the number of members of this proxy class.
"""
return len( self._members )
def createAndFillObject(self, container = None, *args):
"""Same as calling createObject followed by fillObject."""
return self.fillObject( self.createObject(*args), container )
def createObject(self, *args):
"""
Creates a new instance of the object wrapped by this class.
The object will not be filled, you have to call fillObject.
If any extra parameters are specified, they are passed to the object constructor.
Returns the newly created object.
"""
return self._wrappedClass(*args)
def fillObject(self, object, container = None):
"""
Fills every wrapped field in the specified object with the content of this proxy object.
All members are iterated over in the order they were specified.
If the object is an Observable, then the changes are batched.
As a container, specify the object (not proxy object) to which this object is (or will be) attached with an HAS_A or HAS_MANY relationship.
Returns the filled object, the exact same object that was passed in parameter.
"""
try: object.beginBatchChanges()
except AttributeError: pass
try:
for member in self._members:
member.set(object, self.__getattribute__(member.name), container )
finally:
try: object.endBatchChanges()
except AttributeError: pass
return object
def extractFromObject( self, object, recursive = True ):
"""
This method extract the content of the passed object and places it in this wrapper.
Pass recursive = False to only extract non-object members. The members containing object references or list of objects will not be extracted and will remain unchanged.
"""
if self._caster is not None : object = self._caster(object)
for member in self._members:
if not recursive and member.isObject: continue
self.__setattr__( member.name, member.get(object) )
def load(self, *args):
"""
Creates a new instance of the object wrapped by this class,
Fill it with its content,
Then, add it to the framework or to the container object using
the specified loader method.
Returns the newly loaded object.
"""
object = self.createObject(*args)
self.fillObject(object)
if self._loader is not None :
self._loader( object )
return object
# Inherits the parent icon
if _icon is None :
if _parent is not None:
_icon = _parent._icon
# Merge the parent and child's member list
if _parent is not None :
# Merge parent and child members
_members = _parent._members + _members
# Move the child's member to the parent if they have the same name
for i in range( len(_parent._members) ):
for j in range( len(_parent._members), len(_members) ):
if _members[i].name == _members[j].name :
_members[i] = _members[j]
del _members[j]
break
try:
del i
del j
except UnboundLocalError: pass
# Build a dictionnary of members for efficient look-up
_memberDict = {}
for member in _members:
_memberDict[member.name] = member
try: del member
except UnboundLocalError: pass
_nameGetter = staticmethod(_nameGetter)
return type( _wrappedClass.__name__.split('.')[-1], (object,), locals() )
| [
[
8,
0,
0.0129,
0.0216,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0302,
0.0043,
0,
0.66,
0.3333,
806,
0,
1,
0,
0,
806,
0,
0
],
[
2,
0,
0.1078,
0.1422,
0,
0.66... | [
"'''\nCreated on 2009-09-22\n\n@author: beaudoin\n'''",
"import PyUtils",
"def create( wrappedClass = None, members = [], parent = None, caster = None, loader = None, verbose = True, icon = None, nameGetter = None ):\n \"\"\"\n Creates a new proxy class (NOT an instance).\n \n This proxy class is me... |
'''
Created on 2009-09-02
@author: beaudoin
'''
import Proxy
import Member
import Physics
cls = Physics.SphereCDP
SphereCDP = Proxy.create( cls, verbose = False, caster = Physics.castToSphereCDP,
members = [
Member.Point3d( 'center', (0.0,0.0,0.0), cls.getCenter, cls.setCenter ),
Member.Basic( float, 'radius', 1.0, cls.getRadius, cls.setRadius),
] )
cls = Physics.BoxCDP
BoxCDP = Proxy.create( cls, verbose = False, caster = Physics.castToBoxCDP,
members = [
Member.Point3d( 'point1', (-1.0,-1.0,-1.0), cls.getPoint1, cls.setPoint1 ),
Member.Point3d( 'point2', (1.0,1.0,1.0), cls.getPoint2, cls.setPoint2),
] )
cls = Physics.PlaneCDP
PlaneCDP = Proxy.create( cls, verbose = False, caster = Physics.castToPlaneCDP,
members = [
Member.Vector3d( 'normal', (0.0,1.0,0.0), cls.getNormal, cls.setNormal ),
Member.Point3d( 'origin', (0.0,0.0,0.0), cls.getOrigin, cls.setOrigin),
] )
cls = Physics.CapsuleCDP
CapsuleCDP = Proxy.create( cls, verbose = False, caster = Physics.castToCapsuleCDP,
members = [
Member.Point3d( 'point1', (-1.0,0.0,0.0), cls.getPoint1, cls.setPoint1 ),
Member.Point3d( 'point2', (1.0,0.0,0.0), cls.getPoint2, cls.setPoint2 ),
Member.Basic( float, 'radius', 1.0, cls.getRadius, cls.setRadius),
] )
| [
[
8,
0,
0.0769,
0.1282,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1795,
0.0256,
0,
0.66,
0.0909,
363,
0,
1,
0,
0,
363,
0,
0
],
[
1,
0,
0.2051,
0.0256,
0,
0.66... | [
"'''\nCreated on 2009-09-02\n\n@author: beaudoin\n'''",
"import Proxy",
"import Member",
"import Physics",
"cls = Physics.SphereCDP",
"SphereCDP = Proxy.create( cls, verbose = False, caster = Physics.castToSphereCDP,\n members = [\n Member.Point3d( 'center', (0.0,0.0,0.0), cls.getCenter, cls.set... |
from SNMApp import ObservableList, SnapshotBranch, Snapshot
from CDPs import SphereCDP, BoxCDP, PlaneCDP, CapsuleCDP
from RigidBody import RigidBody, ArticulatedRigidBody
from ArticulatedFigure import ArticulatedFigure, Character
from Joints import BallInSocketJoint, UniversalJoint, HingeJoint, StiffJoint
from SimBiController import SimBiController, ControlParams, SimBiConState, ExternalForce, Trajectory, TrajectoryComponent, LinearBalanceFeedback, IKVMCController, DanceController, WalkController | [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
323,
0,
3,
0,
0,
323,
0,
0
],
[
1,
0,
0.3333,
0.1667,
0,
0.66,
0.2,
831,
0,
4,
0,
0,
831,
0,
0
],
[
1,
0,
0.5,
0.1667,
0,
0.66,
... | [
"from SNMApp import ObservableList, SnapshotBranch, Snapshot",
"from CDPs import SphereCDP, BoxCDP, PlaneCDP, CapsuleCDP",
"from RigidBody import RigidBody, ArticulatedRigidBody",
"from ArticulatedFigure import ArticulatedFigure, Character",
"from Joints import BallInSocketJoint, UniversalJoint, HingeJoint,... |
'''
Created on 2009-09-03
@author: beaudoin
'''
import Proxy
import Member
import Physics, Core, wx
cls = Physics.ArticulatedFigure
ArticulatedFigure = Proxy.create( cls, loader = Physics.world().addArticulatedFigure,
members = [
Member.Basic( str, 'name', 'UnnamedArticulatedFigure', cls.getName, cls.setName ),
Member.Object( 'root', None, cls.getRoot, cls.setRoot ),
Member.ObjectList( 'arbs', None, cls.getArticulatedRigidBody, cls.getArticulatedRigidBodyCount, cls.addArticulatedRigidBody ),
Member.ObjectList( 'joints', None, cls.getJoint, cls.getJointCount, cls.addJoint )
] )
cls = Core.Character
Character = Proxy.create( cls, parent = ArticulatedFigure, loader = wx.GetApp().addCharacter )
| [
[
8,
0,
0.1364,
0.2273,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3182,
0.0455,
0,
0.66,
0.1429,
363,
0,
1,
0,
0,
363,
0,
0
],
[
1,
0,
0.3636,
0.0455,
0,
0.66... | [
"'''\nCreated on 2009-09-03\n\n@author: beaudoin\n'''",
"import Proxy",
"import Member",
"import Physics, Core, wx",
"cls = Physics.ArticulatedFigure",
"ArticulatedFigure = Proxy.create( cls, loader = Physics.world().addArticulatedFigure,\n members = [\n Member.Basic( str, 'name', 'UnnamedArticu... |
from SNMApp import SNMApp
from SnapshotTree import SnapshotBranch, Snapshot
from ObservableList import ObservableList
import Scenario
import InstantChar
import KeyframeEditor | [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
323,
0,
1,
0,
0,
323,
0,
0
],
[
1,
0,
0.3333,
0.1667,
0,
0.66,
0.2,
965,
0,
2,
0,
0,
965,
0,
0
],
[
1,
0,
0.5,
0.1667,
0,
0.66,
... | [
"from SNMApp import SNMApp",
"from SnapshotTree import SnapshotBranch, Snapshot",
"from ObservableList import ObservableList",
"import Scenario",
"import InstantChar",
"import KeyframeEditor"
] |
'''
Created on 2009-10-06
@author: beaudoin
'''
import Scenario, PyUtils, Physics, MathLib, math
class Staircase(Scenario.Scenario):
"""A scenario that can be used to setup a staircase."""
def __init__(self, name = "Staircase scenario", staircaseWidth = 0.9, threadDepth = 0.2 , riserHeight = 0.223, stepCount = 10, position = (0,0,0), angle = 0, leftRampHeight = None, rightRampHeight = None ):
"""Setup a staircase"""
super( Staircase, self ).__init__(name)
self._staircaseWidth = staircaseWidth
self._threadDepth = threadDepth
self._riserHeight = riserHeight
self._stepCount = stepCount
self._position = position
self._angle = angle
self._leftRampHeight = leftRampHeight
self._rightRampHeight = rightRampHeight
self._loaded = False
#
# Accessors
#
def getStairWidth(self):
"""Access the staircase width"""
return self._staircaseWidth
def setStairWidth(self, staircaseWidth):
"""Sets the staircase width"""
self._staircaseWidth = staircaseWidth
def getThreadDepth(self):
"""Access the thread depth"""
return self._staircaseWidth
def setThreadDepth(self, threadDepth):
"""Sets the thread depth"""
self._threadDepth = threadDepth
def getRiserHeight(self):
"""Access the riser height"""
return self._riserHeight
def setRiserHeight(self, riserHeight):
"""Sets the riser height"""
self._riserHeight = riserHeight
def getStepCount(self):
"""Access the number of steps"""
return self._stepCount
def setStepCount(self, stepCount):
"""Sets the number of steps (a Point3d)"""
self._stepCount = stepCount
def getPosition(self):
"""
Access the position.
The position is the location on the ground in the middle of the first "virtual step", that
is, right in front of the first real step.
"""
return self._position
def setPosition(self, position):
"""
Sets the position.
The position is the location on the ground in the middle of the first "virtual step", that
is, right in front of the first real step.
"""
self._position = position
def getAngle(self):
"""Access the angle of rotation along the y axis (in radians)"""
return self._oritentation
def setAngle(self, angle):
"""Sets the angle of rotation along the y axis (in radians)"""
self._angle = angle
def getLeftRampHeight(self):
"""Access the height of the left ramp, or None if no left ramp is desired"""
return self._leftRampHeight
def setLeftRampHeight(self, leftRampHeight):
"""Sets the height of the left ramp, or None if no left ramp is desired"""
self._leftRampHeight = leftRampHeight
def getRightRampHeight(self):
"""Access the height of the right ramp, or None if no right ramp is desired"""
return self._rightRampHeight
def setRightRampHeight(self, rightRampHeight):
"""Sets the height of the right ramp, or None if no right ramp is desired"""
self._rightRampHeight = rightRampHeight
#
# Public methods
#
def load(self):
assert not self._loaded, "Cannot load scenario twice!"
self._loaded = True
# Create the rigid bodies for the main staircase
orientation = PyUtils.angleAxisToQuaternion( (self._angle,(0,1,0)) )
size = MathLib.Vector3d( self._staircaseWidth, self._riserHeight, self._threadDepth )
pos = PyUtils.toPoint3d( self._position ) + MathLib.Vector3d( 0, -self._riserHeight/2.0, 0 )
delta = MathLib.Vector3d(size)
delta.x = 0
delta = orientation.rotate( delta )
for i in range(self._stepCount):
box = PyUtils.RigidBody.createBox( size, pos = pos + delta * (i+1), locked = True, orientation=orientation )
Physics.world().addRigidBody(box)
# Create the rigid bodies for both ramps
rampHeights = ( self._leftRampHeight, self._rightRampHeight )
deltaRamp = MathLib.Vector3d(self._staircaseWidth/2.0,0,0)
deltaRamp = orientation.rotate( deltaRamp )
deltaRamps = (deltaRamp, deltaRamp * -1)
for deltaRamp, rampHeight in zip( deltaRamps, rampHeights ):
if rampHeight is None: continue
deltaRamp.y = rampHeight/2.0
box = PyUtils.RigidBody.createBox( (0.02,rampHeight,0.02), pos = pos + deltaRamp + delta , locked = True, orientation=orientation )
Physics.world().addRigidBody(box)
box = PyUtils.RigidBody.createBox( (0.02,rampHeight,0.02), pos = pos + deltaRamp + (delta * self._stepCount) , locked = True, orientation=orientation )
Physics.world().addRigidBody(box)
deltaRamp.y = rampHeight
rampOrientation = orientation * PyUtils.angleAxisToQuaternion( (math.atan2(self._riserHeight, self._threadDepth), (-1,0,0)) )
rampLen = self._stepCount * math.sqrt( self._riserHeight*self._riserHeight + self._threadDepth*self._threadDepth )
box = PyUtils.RigidBody.createBox( (0.04,0.02,rampLen), pos = pos + deltaRamp + (delta * ((self._stepCount+1) * 0.5)) , locked = True, orientation=rampOrientation )
Physics.world().addRigidBody(box)
| [
[
8,
0,
0.0201,
0.0336,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.047,
0.0067,
0,
0.66,
0.5,
700,
0,
5,
0,
0,
700,
0,
0
],
[
3,
0,
0.5067,
0.8993,
0,
0.66,
... | [
"'''\nCreated on 2009-10-06\n\n@author: beaudoin\n'''",
"import Scenario, PyUtils, Physics, MathLib, math",
"class Staircase(Scenario.Scenario):\n \"\"\"A scenario that can be used to setup a staircase.\"\"\"\n \n def __init__(self, name = \"Staircase scenario\", staircaseWidth = 0.9, threadDepth = 0.2... |
'''
Created on 2009-10-06
@author: beaudoin
'''
import PyUtils
class Scenario(PyUtils.Observable):
"""The base class for a scenario. Each scenarios should have the following methods:
load()
Called when the scenario has been filled so that its resources can be created (like rigid bodies, etc.)
update()
Called whenever a character has moved and the scenario must update the character-related information."""
def __init__(self, name = "Unnamed scenario"):
"""Initializes a scenario with a specific name"""
super(Scenario, self).__init__()
self._name = name
#
# Accessors
#
def getName(self):
"""Access the scenario name."""
return self._name
def setName(self, name):
"""Sets the name of the scenario."""
self._name = name
| [
[
8,
0,
0.0938,
0.1562,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2188,
0.0312,
0,
0.66,
0.5,
806,
0,
1,
0,
0,
806,
0,
0
],
[
3,
0,
0.6406,
0.75,
0,
0.66,
... | [
"'''\nCreated on 2009-10-06\n\n@author: beaudoin\n'''",
"import PyUtils",
"class Scenario(PyUtils.Observable):\n \"\"\"The base class for a scenario. Each scenarios should have the following methods:\n load()\n Called when the scenario has been filled so that its resources can be created... |
from Staircase import Staircase | [
[
1,
0,
1,
1,
0,
0.66,
0,
849,
0,
1,
0,
0,
849,
0,
0
]
] | [
"from Staircase import Staircase"
] |
'''
Created on 2009-12-02
@author: beaudoin
'''
from OpenGL.GL import *
import UI, Core, GLUtils
from MathLib import Point3d, Vector3d, Quaternion
import math
class CheckBoxCallback(GLUtils.GLUICallback):
def __init__(self, editorWindow):
"""Private callback class."""
super(CheckBoxCallback,self).__init__()
self._editorWindow = editorWindow
def execute(self):
"""Callback execution"""
self._editorWindow._checkBoxChanged()
class EditorWindow(GLUtils.GLUIContainer):
def __init__( self, parent, posableCharacter, handlesSide, handlesFront, stanceKneeHandle, swingFootHandleSagittal, swingFootHandleCoronal, swingFootHandleHeight,
time, controller, stanceFootToSwingFootTrajectory, minWidth=-1, minHeight=-1, checkBoxVisible=True):
super(EditorWindow,self).__init__(parent)
self._sizer = GLUtils.GLUIBoxSizer(GLUtils.GLUI_VERTICAL)
self.setSizer(self._sizer)
handleVisible = len(handlesSide) != 0 and handlesSide[0].hasKeyframeAtTime(time)
if checkBoxVisible:
self._checkBox = GLUtils.GLUICheckBox(self,0,0,0,0,-1,-1,handleVisible)
self._sizer.add(self._checkBox, 0, GLUtils.GLUI_EXPAND )
self._callback = CheckBoxCallback(self)
self._checkBox.setCheckBoxCallback(self._callback)
else:
self._spacer = GLUtils.GLUIWindow(self)
self._sizer.add(self._spacer, 1, GLUtils.GLUI_EXPAND )
self._editorSide = CharacterEditorWindow(self,
posableCharacter,
handlesSide,
stanceKneeHandle,
swingFootHandleSagittal,
swingFootHandleHeight,
time,
controller,
stanceFootToSwingFootTrajectory,
ConverterZY(),
0, 0, 0, 0, minWidth, minHeight )
self._sizer.add(self._editorSide)
self._editorSide.addHandlesVisibilityChangedCallback( self._setCheckBox )
self._editorFront = CharacterEditorWindow(self,
posableCharacter,
handlesFront,
None,
swingFootHandleCoronal,
swingFootHandleHeight,
time,
controller,
stanceFootToSwingFootTrajectory,
ConverterXY(),
0, 0, 0, 0, minWidth, minHeight )
self._sizer.add(self._editorFront)
self._editorFront.addHandlesVisibilityChangedCallback( self._setCheckBox )
self._checkBoxCallbacks = []
def addCheckBoxCallback(self, callback):
"""Adds a function that will be called back whenever the checkbox state is changed."""
self._checkBoxCallbacks.append(callback)
def _setCheckBox(self, checked):
try:
if checked != self._checkBox.isChecked():
self._checkBox.setChecked(checked)
except AttributeError:
pass
def _checkBoxChanged(self):
"""Called whenever the checkbox is changed."""
for callback in self._checkBoxCallbacks:
callback(self._checkBox.isChecked())
class CharacterEditorWindow(UI.GLUITools.WindowWithControlPoints):
def __init__( self, parent, posableCharacter, handles, stanceKneeHandle, swingFootHandleX, swingFootHandleY,
time, controller, stanceFootToSwingFootTrajectory, converter, x=0, y=0, width=0, height=0, minWidth=-1, minHeight=-1 ):
"""A keyframe edition window. Character are always forced to left stance."""
super(CharacterEditorWindow,self).__init__(parent,x,y,width,height, minWidth, minHeight, boundsY=(-0.1,1.9), forceAspectRatio='x')
self._converter = converter
self._posableCharacter = posableCharacter
self._character = posableCharacter.getCharacter()
self._handles = handles
self._stanceKneeHandle = stanceKneeHandle
self._swingFootHandleX = swingFootHandleX
self._swingFootHandleY = swingFootHandleY
self._time = time
self._controller = controller
self._stanceFootToSwingFootTrajectory = stanceFootToSwingFootTrajectory
self._lineTorso = [ '_pelvis', 'pelvis_lowerback', 'lowerback_torso', 'torso_head', '_head' ]
self._lArm = [ '_torso', 'lShoulder', 'lElbow', '_lLowerArm' ]
self._rArm = [ '_torso', 'rShoulder', 'rElbow', '_rLowerArm' ]
self._lLeg = [ '_pelvis', 'lHip', 'lKnee', 'lAnkle', 'lToeJoint' ]
self._rLeg = [ '_pelvis', 'rHip', 'rKnee', 'rAnkle', 'rToeJoint' ]
self._handlesVisibilityChangedCallbacks = []
self._handlesVisible = None
self._updateHandlesVisibility()
def _setHandlesVisible(self, visible):
"""Make sure the handles are visible or not."""
if self._handlesVisible == visible: return
self._handlesVisible = visible
self.deleteAllControlPoints()
if visible:
for handle in self._handles:
self.addControlPoint( HandleControlPoint(self._posableCharacter, self._time, self._converter, handle) )
if self._stanceKneeHandle is not None:
self.addControlPoint( HandleStanceKneeControlPoint(self._posableCharacter, self._time, self._converter, self._stanceKneeHandle) )
if self._time > 0 and self._time < 1 and self._swingFootHandleX is not None and self._swingFootHandleY is not None:
self.addControlPoint( SwingFootControlPoint(self._posableCharacter, self._time, self._converter, self._swingFootHandleX, self._swingFootHandleY) )
for callback in self._handlesVisibilityChangedCallbacks:
callback(visible)
def _updateHandlesVisibility(self):
"""Check if the control points should be visible.
Only check the first handle. Assume they all have keyframes at the same time."""
if len(self._handles) == 0 :
return
else:
self._setHandlesVisible( self._handles[0].hasKeyframeAtTime(self._time) )
def addHandlesVisibilityChangedCallback(self, callback):
"""Adds a callback that will be called whenever the visibility of the handles change.
The callback should take one boolean parameter, true if they are visible, false otherwise."""
self._handlesVisibilityChangedCallbacks.append(callback)
def areHandlesVisible(self):
"""Return true if the handles are visible, false otherwise."""
return self._handlesVisible
def drawContent(self):
"""Draw the character from front view."""
self._updateHandlesVisibility()
self._posableCharacter.updatePose( self._time, self._stanceFootToSwingFootTrajectory.evaluate_catmull_rom(self._time) )
try:
glColor3d(0.4,0.5,0.0)
self._drawLine( self._lArm )
self._drawLine( self._lLeg )
glColor3d(1,1,1)
self._drawLine( self._rArm )
self._drawLine( self._rLeg )
self._drawLine( self._lineTorso )
except Exception as e:
glEnd()
print "Exception while drawing scaled character interface: " + str(e)
traceback.print_exc(file=sys.stdout)
def _drawLine(self, line ):
glBegin( GL_LINE_STRIP )
for name in line:
if name[0] == '_' :
pos = self._character.getARBByName(name[1:]).getCMPosition()
else:
joint = self._character.getJointByName(name)
arb = joint.getParent()
pos = arb.getWorldCoordinates( joint.getParentJointPosition() )
glVertex2d( *self._converter.to2d(pos) )
glEnd()
class _Type(object):
circular = 0
perpendicular = 1
class BaseControlPoint(UI.GLUITools.ControlPoint):
def __init__( self, posableCharacter, time, converter ):
super(BaseControlPoint,self).__init__()
self._posableCharacter = posableCharacter
self._character = posableCharacter.getCharacter()
self._time = time
self._converter = converter
class BaseHandleControlPoint(BaseControlPoint):
def __init__( self, posableCharacter, time, converter, handle ):
super(BaseHandleControlPoint,self).__init__(posableCharacter, time, converter)
self._handle = handle
perpendicularSpeed = 3 # Increase this to make perpendicular handle rotate more quickly
stanceKneeSpeed = 4.2 # Increase this to make stance knee handle rotate more quickly
class HandleControlPoint(BaseHandleControlPoint):
def __init__( self, posableCharacter, time, converter, handle ):
super(HandleControlPoint,self).__init__(posableCharacter, time, converter, handle)
characterJointName = handle.getJointName().replace("STANCE_","l").replace("SWING_","r")
joint = self._character.getJointByName( characterJointName )
self._jointChild = joint.getChild()
self._pivotPosInChild = joint.getChildJointPosition()
self._handlePosInChild = handle.getPosInChild()
type = handle.getType()
if type == 'circular':
self._type = _Type.circular
self._sign = 1
elif type == 'reverseCircular':
self._type = _Type.circular
self._sign = -1
elif type == 'perpendicular':
self._type = _Type.perpendicular
self._sign = 1
elif type == 'reversePerpendicular':
self._type = _Type.perpendicular
self._sign = -1
else:
raise ValueError( 'Handle, supported type = "circular", "reverseCircular", "perpendicular", or "reversePerpendicular"' )
def getPos(self):
posHandle = self._jointChild.getWorldCoordinates( self._handlePosInChild )
return self._converter.to2d( posHandle )
def setPos(self, pos):
if self._type == _Type.circular :
posPivot = self._jointChild.getWorldCoordinates( self._pivotPosInChild )
self._converter.project( posPivot )
v1 = Vector3d( posPivot, Point3d(*self._converter.to3d(self._previousMousePos) ) ).unit()
v2 = Vector3d( posPivot, Point3d(*self._converter.to3d(pos) ) ).unit()
cos = v1.dotProductWith(v2)
sin = v1.crossProductWith(v2).dotProductWith(Vector3d(*self._converter.normal())) * self._sign
theta = math.atan2(sin, cos)
else: # _Type.perpendicular
posPivot = self._jointChild.getWorldCoordinates( self._pivotPosInChild )
handlePos = self._jointChild.getWorldCoordinates( self._handlePosInChild )
vector = Vector3d( posPivot, handlePos ).unit().crossProductWith( Vector3d(*self._converter.normal()) )
vector2d = self._converter.to2d( vector )
theta = (vector2d[0]*(pos[0]-self._previousMousePos[0]) + vector2d[1]*(pos[1]-self._previousMousePos[1])) * self._sign * perpendicularSpeed
index = self._handle.getIndexForTime(self._time)
if index is None:
return
value = self._handle.getKeyframeValue(index)
self._handle.setKeyframeValue(index, value+theta)
class HandleStanceKneeControlPoint(BaseHandleControlPoint):
def __init__( self, posableCharacter, time, converter, handle ):
super(HandleStanceKneeControlPoint,self).__init__(posableCharacter, time, converter, handle)
joint = self._character.getJointByName( 'lHip' )
self._jointChild = joint.getChild()
self._handlePosInChild = joint.getChildJointPosition()
def getPos(self):
posHandle = self._jointChild.getWorldCoordinates( self._handlePosInChild )
return self._converter.to2d( posHandle )
def setPos(self, pos):
theta = (self._previousMousePos[1]-pos[1]) * stanceKneeSpeed
index = self._handle.getIndexForTime(self._time)
if index is None:
return
value = self._handle.getKeyframeValue(index)
self._handle.setKeyframeValue(index, value+theta)
class SwingFootControlPoint(BaseControlPoint):
def __init__( self, posableCharacter, time, converter, handleX, handleY ):
super(SwingFootControlPoint,self).__init__(posableCharacter, time, converter)
joint = self._character.getJointByName( 'rAnkle' )
self._jointChild = joint.getChild()
self._handlePosInChild = joint.getChildJointPosition()
self._handleX = handleX
self._handleY = handleY
def getPos(self):
posHandle = self._jointChild.getWorldCoordinates( self._handlePosInChild )
return self._converter.to2d( posHandle )
def setPos(self, pos):
deltaX = pos[0]-self._previousMousePos[0]
deltaY = pos[1]-self._previousMousePos[1]
index = self._handleX.getIndexForTime(self._time)
if index is None:
return
assert index == self._handleY.getIndexForTime(self._time), 'Unexpected error: handle X and Y keyframes are out-of-sync.'
valueX = self._handleX.getKeyframeValue(index)
valueY = self._handleY.getKeyframeValue(index)
self._handleX.setKeyframeValue(index, valueX+deltaX)
self._handleY.setKeyframeValue(index, valueY+deltaY)
return
class ConverterZY(object):
def to2d(self,vec):
return (vec.z, vec.y)
def to3d(self,vec):
return (0, vec[1], vec[0])
def normal(self):
return (1,0,0)
def project(self, vec):
vec.x = 0
class ConverterXY(object):
def to2d(self,vec):
return (vec.x, vec.y)
def to3d(self,vec):
return (vec[0], vec[1], 0)
def normal(self):
return (0,0,1)
def project(self, vec):
vec.z = 0
| [
[
8,
0,
0.0085,
0.0142,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0199,
0.0028,
0,
0.66,
0.0588,
280,
0,
1,
0,
0,
280,
0,
0
],
[
1,
0,
0.0228,
0.0028,
0,
0.66... | [
"'''\nCreated on 2009-12-02\n\n@author: beaudoin\n'''",
"from OpenGL.GL import *",
"import UI, Core, GLUtils",
"from MathLib import Point3d, Vector3d, Quaternion",
"import math",
"class CheckBoxCallback(GLUtils.GLUICallback):\n \n def __init__(self, editorWindow):\n \"\"\"Private callback cla... |
'''
Created on 2009-12-08
@author: beaudoin
'''
import Core
from MathLib import Vector3d, Point3d, Quaternion
import math
class PosableCharacter(object):
"""A character that can be posed and edited in the keyframe editor."""
def __init__(self, character, controller):
"""Initializes and attach to a standard Core.Character and Core.SimBiController."""
self._character = character
self._controller = controller
self._leftLowerLeg = self._character.getARBByName('lLowerLeg')
self._rightLowerLeg = self._character.getARBByName('rLowerLeg')
self._leftFoot = self._character.getARBByName('lFoot')
self._rightFoot = self._character.getARBByName('rFoot')
self._leftHipJointIndex = self._character.getJointIndex( "lHip" )
self._rightHipJointIndex = self._character.getJointIndex( "rHip" )
self._leftHipJointIndex = self._character.getJointIndex( "lHip" )
self._rightHipJointIndex = self._character.getJointIndex( "rHip" )
self._leftKneeJointIndex = self._character.getJointIndex( "lKnee" )
self._rightKneeJointIndex = self._character.getJointIndex( "rKnee" )
self._leftAnkleJointIndex = self._character.getJointIndex( "lAnkle" )
self._rightAnkleJointIndex = self._character.getJointIndex( "rAnkle" )
self._leftHipJoint = self._character.getJoint( self._leftHipJointIndex )
self._rightHipJoint = self._character.getJoint( self._rightHipJointIndex )
self._leftHipJoint = self._character.getJoint( self._leftHipJointIndex )
self._rightHipJoint = self._character.getJoint( self._rightHipJointIndex )
self._leftKneeJoint = self._character.getJoint( self._leftKneeJointIndex )
self._rightKneeJoint = self._character.getJoint( self._rightKneeJointIndex )
self._leftAnkle = self._character.getJoint( self._leftAnkleJointIndex )
self._rightAnkle = self._character.getJoint( self._rightAnkleJointIndex )
self._pelvis = self._leftHipJoint.getParent()
self._leftUpperLeg = self._leftHipJoint.getChild()
self._rightUpperLeg = self._rightHipJoint.getChild()
self._leftAnkleInStanceLowerLeg = self._leftAnkle.getParentJointPosition()
self._rightAnkleInStanceLowerLeg = self._rightAnkle.getParentJointPosition()
self._leftHipJointInPelvis = self._leftHipJoint.getParentJointPosition()
self._rightHipJointInPelvis = self._rightHipJoint.getParentJointPosition()
self._leftHipJointInPelvis = self._leftHipJoint.getParentJointPosition()
self._rightHipJointInPelvis = self._rightHipJoint.getParentJointPosition()
self._leftHipToKneeVectorInUpperLeg = Vector3d( self._leftHipJoint.getChildJointPosition(),
self._leftKneeJoint.getParentJointPosition() )
self._rightHipToKneeVectorInUpperLeg = Vector3d( self._rightHipJoint.getChildJointPosition(),
self._rightKneeJoint.getParentJointPosition() )
self._leftKneeToAnkleVectorInLowerLeg = Vector3d( self._leftKneeJoint.getChildJointPosition(),
self._leftAnkle.getParentJointPosition() )
self._rightKneeToAnkleVectorInLowerLeg = Vector3d( self._rightKneeJoint.getChildJointPosition(),
self._rightAnkle.getParentJointPosition() )
def getCharacter(self):
"""Access the character."""
return self._character
def updatePose(self, time, stanceFootToSwingFoot, stance = Core.LEFT_STANCE, dontMoveStanceAnkle = False):
"""Updates the pose of the character to match the one at the specified time.
Always use left stance.
stanceFootToSwingFoot is a Vector3d for the vector linking the stance foot to the swing foot
"""
# Setup the stance leg
if stance == Core.LEFT_STANCE:
stanceLowerLeg = self._leftLowerLeg
stanceAnkleInStanceLowerLeg = self._leftAnkleInStanceLowerLeg
stanceHipJointInPelvis = self._leftHipJointInPelvis
stanceHipJointIndex = self._leftHipJointIndex
swingHipJointInPelvis = self._rightHipJointInPelvis
swingHipToKneeVectorInUpperLeg = self._rightHipToKneeVectorInUpperLeg
swingKneeToAnkleVectorInLowerLeg = self._rightKneeToAnkleVectorInLowerLeg
swingKneeJointIndex = self._rightKneeJointIndex
swingHipJointIndex = self._rightHipJointIndex
else:
stanceLowerLeg = self._rightLowerLeg
stanceAnkleInStanceLowerLeg = self._rightAnkleInStanceLowerLeg
stanceHipJointInPelvis = self._rightHipJointInPelvis
stanceHipJointIndex = self._rightHipJointIndex
swingHipJointInPelvis = self._leftHipJointInPelvis
swingHipToKneeVectorInUpperLeg = self._leftHipToKneeVectorInUpperLeg
swingKneeToAnkleVectorInLowerLeg = self._leftKneeToAnkleVectorInLowerLeg
swingKneeJointIndex = self._leftKneeJointIndex
swingHipJointIndex = self._leftHipJointIndex
if dontMoveStanceAnkle :
finalStanceAnkleInWorld = stanceLowerLeg.getWorldCoordinates( stanceAnkleInStanceLowerLeg )
pose = Core.ReducedCharacterStateArray()
self._controller.updateTrackingPose(pose, time, stance)
reducedCharacter = Core.ReducedCharacterState(pose)
# Update stanceFootToSwingFoot, adding in the delta
stanceFootToSwingFoot += self._controller.computeSwingFootDelta(time, stance)
# Recenter and reorient the character
pos = reducedCharacter.getPosition()
pos.x = pos.z = 0
reducedCharacter.setPosition(pos)
reducedCharacter.setOrientation(Quaternion())
self._character.setState(pose, 0, False)
leftFootWorldOrientation = self._leftFoot.getOrientation()
rightFootWorldOrientation = self._rightFoot.getOrientation()
currentStanceAnkleInWorld = stanceLowerLeg.getWorldCoordinates( stanceAnkleInStanceLowerLeg )
currentStanceAnkleInPelvis = self._pelvis.getLocalCoordinates( currentStanceAnkleInWorld )
currentStanceHipToAnkleInPelvis = Vector3d( stanceHipJointInPelvis, currentStanceAnkleInPelvis )
lengthStanceHipToAnkle = currentStanceHipToAnkleInPelvis.length()
stanceHipJointInWorld = self._pelvis.getWorldCoordinates(stanceHipJointInPelvis)
desiredStanceAnkleInWorld = Point3d(stanceFootToSwingFoot*-0.5)
yLentgh2 = lengthStanceHipToAnkle*lengthStanceHipToAnkle - \
desiredStanceAnkleInWorld.x*desiredStanceAnkleInWorld.x - \
desiredStanceAnkleInWorld.z*desiredStanceAnkleInWorld.z
if yLentgh2 <= 0:
desiredStanceAnkleInWorld.y = stanceHipJointInWorld.y
else:
desiredStanceAnkleInWorld.y = stanceHipJointInWorld.y - math.sqrt( yLentgh2 )
desiredStanceAnkleInPelvis = self._pelvis.getLocalCoordinates( desiredStanceAnkleInWorld )
desiredStanceHipToAnkleInPelvis = Vector3d( stanceHipJointInPelvis, desiredStanceAnkleInPelvis )
currentStanceHipToAnkleInPelvis.toUnit()
desiredStanceHipToAnkleInPelvis.toUnit()
rot = Quaternion( currentStanceHipToAnkleInPelvis, desiredStanceHipToAnkleInPelvis )
currQuat = reducedCharacter.getJointRelativeOrientation(stanceHipJointIndex)
currQuat *= rot
reducedCharacter.setJointRelativeOrientation(currQuat, stanceHipJointIndex)
pos = reducedCharacter.getPosition()
pos.y -= desiredStanceAnkleInWorld.y
reducedCharacter.setPosition(pos)
self._character.setState(pose, 0, False)
# Setup the swing leg
currentStanceAnkleInWorld = stanceLowerLeg.getWorldCoordinates( stanceAnkleInStanceLowerLeg )
desiredSwingAnkleInWorld = currentStanceAnkleInWorld + stanceFootToSwingFoot
targetInPelvis = self._pelvis.getLocalCoordinates( desiredSwingAnkleInWorld )
qParent = Quaternion()
qChild = Quaternion()
Core.TwoLinkIK_getIKOrientations(
swingHipJointInPelvis,
targetInPelvis,
Vector3d(-1,0,0), swingHipToKneeVectorInUpperLeg,
Vector3d(-1,0,0), swingKneeToAnkleVectorInLowerLeg, qParent, qChild)
reducedCharacter.setJointRelativeOrientation(qChild, swingKneeJointIndex)
reducedCharacter.setJointRelativeOrientation(qParent, swingHipJointIndex)
self._character.setState(pose,0,False)
leftAnkleLocalOrientation = self._leftLowerLeg.getOrientation().getInverse() * leftFootWorldOrientation
rightAnkleLocalOrientation = self._rightLowerLeg.getOrientation().getInverse() * rightFootWorldOrientation
reducedCharacter.setJointRelativeOrientation(leftAnkleLocalOrientation, self._leftAnkleJointIndex)
reducedCharacter.setJointRelativeOrientation(rightAnkleLocalOrientation, self._rightAnkleJointIndex)
if dontMoveStanceAnkle :
delta = finalStanceAnkleInWorld - stanceLowerLeg.getWorldCoordinates( stanceAnkleInStanceLowerLeg )
pos = reducedCharacter.getPosition() + delta
reducedCharacter.setPosition(pos)
self._character.setState(pose,0,False)
| [
[
8,
0,
0.0164,
0.0273,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0383,
0.0055,
0,
0.66,
0.25,
463,
0,
1,
0,
0,
463,
0,
0
],
[
1,
0,
0.0437,
0.0055,
0,
0.66,
... | [
"'''\nCreated on 2009-12-08\n\n@author: beaudoin\n'''",
"import Core",
"from MathLib import Vector3d, Point3d, Quaternion",
"import math",
"class PosableCharacter(object):\n \"\"\"A character that can be posed and edited in the keyframe editor.\"\"\"\n \n def __init__(self, character, controller):\... |
'''
Created on 2009-12-02
@author: beaudoin
'''
import math, MathLib
class BaseHandle(object):
def __init__( self, trajectory, oppositeTrajectory = None, reverseOppositeJoint = False, minValue = -1000, maxValue = 1000 ):
"""
Creates a handle that can be manipulated and is linked to a trajectory
"""
self._trajectory = trajectory
self._oppositeTrajectory = oppositeTrajectory
if reverseOppositeJoint:
self._oppositeSign = -1
else:
self._oppositeSign = 1
self._minValue = minValue
self._maxValue = maxValue
def forceKeyframesAt(self,forcedTimeArray,allowedTimeArray):
"""Make sure keyframes are found only at specific times.
The function first create keyframes at every time found in forcedTimeArray.
Then it deletes any keyframe that does not fall in allowedTimeArray.
In general all the times in forcedTimeArray should also be found in allowedTimeArray.
The resulting curve will be an approximation of the current curve."""
values = []
for time in forcedTimeArray:
values.append( (time, self._trajectory.evaluate_catmull_rom(time)) )
for time in allowedTimeArray:
if forcedTimeArray.count(time) == 0:
index = self.getIndexForTime(time)
if index is not None:
values.append( (time, self._trajectory.getKnotValue(index)) )
self._trajectory.clear()
for time, value in values:
self._trajectory.addKnot(time, value)
def addKeyframeAt(self,time):
"""Adds a single keyframe at the specified time. The curve might be slightly modified as a result."""
self._trajectory.addKnot(time, self._trajectory.evaluate_catmull_rom(time))
def getIndexForTime(self, time):
"""Gets the index for the keyframe at the specified time. None if no keyframe found at that time."""
for i in range( self._trajectory.getKnotCount() ):
if math.fabs( time - self._trajectory.getKnotPosition(i) ) < 0.00001 :
return i
return None
def removeKeyframe(self, index):
"""Removes the keyframe at the specified index."""
self._trajectory.removeKnot(index)
def hasKeyframeAtTime(self, time):
"""Checks if this handle has a keyframe at the specified time."""
return self.getIndexForTime(time) != None
def getKeyframeValue(self, index):
"""Returns the keyframe value at the specified index"""
return self._trajectory.getKnotValue(index)
def enforceSymmetry(self):
"""Make sure the beginning of the trajectory matches the end (of the other stance)."""
self.setKeyframeValue(0, self.getKeyframeValue(0))
def setKeyframeValue(self, index, value):
"""Changes the value of the keyframe at the specified index."""
value = self.clampValue(value)
self._trajectory.setKnotValue(index, value)
# This forces the symmetry
lastIndex = self._trajectory.getKnotCount()-1
try:
otherLastIndex = self._oppositeTrajectory.getKnotCount()-1
if lastIndex != otherLastIndex or self._trajectory.getKnotPosition(lastIndex) != self._oppositeTrajectory.getKnotPosition(lastIndex) :
return
if index == 0 :
self._oppositeTrajectory.setKnotValue(lastIndex, value * self._oppositeSign )
elif index == lastIndex :
self._oppositeTrajectory.setKnotValue(0, value * self._oppositeSign )
except AttributeError:
if index == 0 :
self._trajectory.setKnotValue(lastIndex, value * self._oppositeSign )
elif index == lastIndex :
self._trajectory.setKnotValue(0, value * self._oppositeSign )
def clampValue(self, value):
"""Return the value clamped to lie between supported extreme values."""
if value < self._minValue: return self._minValue
if value > self._maxValue: return self._maxValue
return value
class Handle(BaseHandle):
def __init__( self, controller, jointName, componentIndex, type='unknown', posInChild=MathLib.Point3d(), oppositeJointName = None, reverseOppositeJoint = False, minValue = -1000, maxValue = 1000 ):
"""
Creates a handle that can be used to access a specific component in a controller in a standard (direct) way.
type should be 'circular', 'reverseCircular', 'perpendicular', 'reversePerpendicular' or 'unknown' to indicate how the handle behaves
posInChild should be of type MathLib.Point3d
reverse should be True if the handle works in a reverse way (i.e. going clockwise increase the angle (?))
oppositeJointName should be the name of the corresponding joint on the other stance.
reverseOppositeJoint should be True if the opposite joint sign is different
"""
self._controller = controller
self._jointName = jointName
trajectory = controller.getState(0).getTrajectory(jointName).getTrajectoryComponent(componentIndex).getBaseTrajectory()
self._oppositeJointName = oppositeJointName
self._posInChild = posInChild
if oppositeJointName is not None:
oppositeTrajectory = controller.getState(0).getTrajectory(oppositeJointName).getTrajectoryComponent(componentIndex).getBaseTrajectory()
else:
oppositeTrajectory = None
self._type = type
super(Handle,self).__init__(trajectory, oppositeTrajectory, reverseOppositeJoint, minValue, maxValue)
def getController(self):
"""Gets the controller associated with that handle."""
return self._controller
def getJointName(self):
"""Return the joint name for this handle."""
return self._jointName
def getType(self):
"""Return the type desired for this handle."""
return self._type
def getPosInChild(self):
"""Return the position of the handle in child coordinate."""
return self._posInChild
| [
[
8,
0,
0.0205,
0.0342,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0479,
0.0068,
0,
0.66,
0.3333,
526,
0,
2,
0,
0,
526,
0,
0
],
[
3,
0,
0.3801,
0.6301,
0,
0.66... | [
"'''\nCreated on 2009-12-02\n\n@author: beaudoin\n'''",
"import math, MathLib",
"class BaseHandle(object):\n \n def __init__( self, trajectory, oppositeTrajectory = None, reverseOppositeJoint = False, minValue = -1000, maxValue = 1000 ):\n \"\"\"\n Creates a handle that can be manipulated an... |
'''
Created on 2009-12-02
@author: beaudoin
'''
import wx, PyUtils, GLUtils
from Handle import BaseHandle, Handle
from PosableCharacter import PosableCharacter
from ToolSet import ToolSet
from EditorWindow import EditorWindow
from MathLib import Vector3d, Point3d, Trajectory3dv
class Model(object):
def __init__(self, nbEditors = 5):
self._nbEditors = nbEditors
app = wx.GetApp()
app.addControllerObserver(self)
app = wx.GetApp()
glCanvas = app.getGLCanvas()
self._container = glCanvas.addGLUITool( GLUtils.GLUIContainer )
self._sizer = GLUtils.GLUIBoxSizer(GLUtils.GLUI_HORIZONTAL)
self._container.setSizer(self._sizer)
self._optionsObservable = PyUtils.Observable()
self._create()
self._toolSet = ToolSet(app.getToolPanel(), self)
def addOptionsObserver(self, observer):
"""Adds an observer for the options of the style edition model."""
self._optionsObservable.addObserver(observer)
def displayInterface(self, display):
"""Indicates wheter the interface for editing style should be displayed."""
if display != self.getDisplayInterface() :
self._container.setVisible(display)
self._container.getParent().layout()
self._optionsObservable.notifyObservers()
def getDisplayInterface(self):
"""Indicates wheter the interface for editing style is currently displayed."""
return self._container.isVisible()
def update(self, observable, data= None):
"""Called whenever something important is modified, recreate everything."""
self._destroy()
self._create()
def _destroy(self):
self._handles = []
self._editors = []
self._container.detachAllChildren()
self._container.getParent().layout()
def _create(self):
"""Creates the basic model class for the simple keyframe editor. Characters are always forced to left stance."""
app = wx.GetApp()
try:
self._controller = app.getController(0)
except IndexError:
return
self._character = self._controller.getCharacter()
handlesSide = []
handlesFront = []
self._handles = []
handlesSide.append( self._addHandle( 'SWING_Shoulder', 2, 'SWING_Elbow', minValue = -3.14, maxValue = 3.14 ) )
handlesSide.append( self._addHandle( 'STANCE_Shoulder', 2, 'STANCE_Elbow', minValue = -3.14, maxValue = 3.14 ) )
handlesSide.append( self._addHandle( 'SWING_Elbow', 0, reverseOppositeJoint = True, minValue = -2.8, maxValue = 0 ) )
handlesSide.append( self._addHandle( 'STANCE_Elbow', 0, type = 'reverseCircular', reverseOppositeJoint = True,minValue = 0, maxValue = 2.8 ) )
handlesSide.append( self._addHandle( 'SWING_Ankle', 0, 'SWING_ToeJoint' ) )
handlesSide.append( self._addHandle( 'STANCE_Ankle', 0, 'STANCE_ToeJoint' ) )
handlesSide.append( self._addHandle( 'pelvis_lowerback', 2, 'lowerback_torso', minValue = -1.2, maxValue = 1.2 ) )
handlesSide.append( self._addHandle( 'lowerback_torso', 2, 'torso_head', minValue = -1.2, maxValue = 1.2 ) )
handlesSide.append( self._addHandle( 'torso_head', 2, minValue = -1.2, maxValue = 1.2 ) )
handlesFront.append( self._addHandle( 'SWING_Shoulder', 1, 'SWING_Elbow', type = 'reverseCircular', reverseOppositeJoint = True, minValue = -2, maxValue = 2 ) )
handlesFront.append( self._addHandle( 'STANCE_Shoulder', 1, 'STANCE_Elbow', type = 'reverseCircular', reverseOppositeJoint = True, minValue = -2, maxValue = 2 ) )
handlesFront.append( self._addHandle( 'SWING_Shoulder', 0, type = 'reversePerpendicular', minValue = -3.3, maxValue = 3.3 ) )
handlesFront.append( self._addHandle( 'STANCE_Shoulder', 0, type = 'perpendicular', minValue = -3.3, maxValue = 3.3 ) )
handlesFront.append( self._addHandle( 'pelvis_lowerback', 1, 'lowerback_torso', reverseOppositeJoint = True, minValue = -1.2, maxValue = 1.2 ) )
handlesFront.append( self._addHandle( 'lowerback_torso', 1, 'torso_head', reverseOppositeJoint = True, minValue = -1.2, maxValue = 1.2 ) )
handlesFront.append( self._addHandle( 'torso_head', 1, reverseOppositeJoint = True, minValue = -1.2, maxValue = 1.2 ) )
stanceKneeHandle = Handle( self._controller, 'STANCE_Knee', 0, minValue = 0.1, maxValue = 2.2 )
self._handles.append( stanceKneeHandle )
swingFootHandleSagittal = BaseHandle( self._controller.getSwingFootTrajectoryDeltaSagittal() )
swingFootHandleCoronal = BaseHandle( self._controller.getSwingFootTrajectoryDeltaCoronal() )
swingFootHandleHeight = BaseHandle( self._controller.getSwingFootTrajectoryDeltaHeight() )
self._handles.append( swingFootHandleSagittal )
self._handles.append( swingFootHandleCoronal )
self._handles.append( swingFootHandleHeight )
self._editors = []
self._times = [ i / float(self._nbEditors-1) for i in range(self._nbEditors) ]
for handle in self._handles:
handle.forceKeyframesAt([0,1],self._times)
for handle in self._handles:
handle.enforceSymmetry()
stanceFootToSwingFootTrajectory = Trajectory3dv()
stanceFootToSwingFootTrajectory.addKnot(0,Vector3d(-0.2,0,-0.4))
stanceFootToSwingFootTrajectory.addKnot(0.5,Vector3d(-0.2,0.125,0))
stanceFootToSwingFootTrajectory.addKnot(1,Vector3d(-0.2,0,0.4))
glCanvasSize = wx.GetApp().getGLCanvas().GetSize()
minWidth = glCanvasSize.x / self._nbEditors - 50
minHeight = glCanvasSize.y / 2
for i, time in enumerate(self._times) :
posableCharacter = PosableCharacter(PyUtils.copy(self._character), self._controller)
if i == 0 or i == self._nbEditors-1:
checkBoxVisible = False
else :
checkBoxVisible = True
editor = EditorWindow( self._container,
posableCharacter = posableCharacter,
handlesSide = handlesSide,
handlesFront = handlesFront,
stanceKneeHandle = stanceKneeHandle,
swingFootHandleSagittal = swingFootHandleSagittal,
swingFootHandleCoronal = swingFootHandleCoronal,
swingFootHandleHeight = swingFootHandleHeight,
time = time,
controller = self._controller,
stanceFootToSwingFootTrajectory = stanceFootToSwingFootTrajectory,
minWidth = minWidth, minHeight = minHeight,
checkBoxVisible = checkBoxVisible )
functor = SetKeyframeVisibilityFunctor(self,i)
editor.addCheckBoxCallback( functor.execute )
self._sizer.add(editor, 0, GLUtils.GLUI_EXPAND )
self._editors.append(editor)
self._container.getParent().layout()
def setKeyframeVisibility(self, i, visible):
"""Sets wheter the keyframes of the editor at index i should be visible/editable or not."""
if visible == self.isKeyframeVisible(i) : return
time = self._times[i]
if visible:
for handle in self._handles:
handle.addKeyframeAt(time)
else:
for handle in self._handles:
index = handle.getIndexForTime(time)
if index is not None :
handle.removeKeyframe( index )
def isKeyframeVisible(self, i):
"""Returns true if the keyframes of editor at index i are visible/editable."""
time = self._times[i]
return self._handles[0].hasKeyframeAtTime(time)
def getHandles(self):
"""Return the list of handles."""
return self._handles
def _updateKeyframes(self):
"""Make sure the keyframes are at the right location."""
self._keyframeTimes = [ time for (time, state) in zip(self._times, self._keyframeVisible) if state ]
def _addHandle(self, jointName, componentIndex, handleInfo = None, type = 'circular', reverseOppositeJoint = False, minValue = -10000, maxValue = 10000 ):
"""
Adds a handle to the model.
handleInfo can be the name of an joint where the handle should be located
"""
oppositeJointName = jointName.replace("STANCE_","TEMP_").replace("SWING_","STANCE_").replace("TEMP_","SWING_")
try:
handleJointName = handleInfo.replace("STANCE_","l").replace("SWING_","r")
posInChild = self._character.getJointByName(handleJointName).getParentJointPosition()
except AttributeError:
posInChild = Point3d(0,0,0)
handle = Handle(self._controller, jointName, componentIndex, type, posInChild, oppositeJointName, reverseOppositeJoint, minValue, maxValue )
self._handles.append( handle )
return handle
class SetKeyframeVisibilityFunctor(object):
def __init__(self,model,i):
self._model = model
self._i = i
def execute(self,state):
self._model.setKeyframeVisibility(self._i,state)
| [
[
8,
0,
0.0144,
0.0239,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0335,
0.0048,
0,
0.66,
0.125,
666,
0,
3,
0,
0,
666,
0,
0
],
[
1,
0,
0.0383,
0.0048,
0,
0.66,... | [
"'''\nCreated on 2009-12-02\n\n@author: beaudoin\n'''",
"import wx, PyUtils, GLUtils",
"from Handle import BaseHandle, Handle",
"from PosableCharacter import PosableCharacter",
"from ToolSet import ToolSet",
"from EditorWindow import EditorWindow",
"from MathLib import Vector3d, Point3d, Trajectory3dv",... |
from Model import Model
| [
[
1,
0,
1,
1,
0,
0.66,
0,
929,
0,
1,
0,
0,
929,
0,
0
]
] | [
"from Model import Model"
] |
'''
Created on 2009-11-23
@author: beaudoin
'''
import UI, wx
class ToolSet(UI.ToolSets.ToolsetBase):
def __init__(self, toolPanel, model):
"""Adds a tool set for the keyframe editor to a toolpanel."""
super(ToolSet,self).__init__()
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Style Editor" )
self.addOption( "Edit style", model.getDisplayInterface, model.displayInterface )
# Add this as an observer
model.addOptionsObserver(self)
# Initial update
self.update() | [
[
8,
0,
0.1154,
0.1923,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2692,
0.0385,
0,
0.66,
0.5,
587,
0,
2,
0,
0,
587,
0,
0
],
[
3,
0,
0.6923,
0.6538,
0,
0.66,
... | [
"'''\nCreated on 2009-11-23\n\n@author: beaudoin\n'''",
"import UI, wx",
"class ToolSet(UI.ToolSets.ToolsetBase):\n \n def __init__(self, toolPanel, model):\n \"\"\"Adds a tool set for the keyframe editor to a toolpanel.\"\"\"\n \n super(ToolSet,self).__init__()\n \n ... |
'''
Created on 2009-09-08
@author: beaudoin
Contains a abstract syntactic tree visitor for printing
nested function calls in a nice way. Used for cleaning-up
output of the serialize method.
See the python standard ast module for details.
'''
import ast
class Fancify( ast.NodeVisitor ):
def __init__(self):
super( Fancify, self ).__init__()
self._tabLevel = 0
self._spacesPerTab = 4
def visitListElements(self, elements):
"""Inserts commas between elements and will go multi-line if needed."""
# Try single line
content = ", ".join( elements ) + " "
nbCR = content.count('\n')
long = len(content) > 100 or nbCR > 0
veryLong = long and nbCR > 40
if long:
# Too long, go multi-line
spacer = "\n" + " " * (self._tabLevel * self._spacesPerTab)
if veryLong : spacer = "\n" + spacer
content = spacer
spacer = "," + spacer
content += spacer.join( elements )
if veryLong :
content += "\n" + " " * ((self._tabLevel-1) * self._spacesPerTab)
else :
content += " "
return content
def visitListType(self, list):
"""Visits anything that looks like a list of AST nodes."""
self._tabLevel += 1
elements = map( self.visit, list )
result = self.visitListElements( elements )
self._tabLevel -= 1
return result
def visit_Call(self, node):
"""Fancify a function a call or an object creation."""
assert node.starargs is None and node.kwargs is None, "Star arguments not supported by fancify"
return self.visit(node.func) + "( " + self.visitListType( node.args + node.keywords ) + ")"
def visit_List(self, node):
"""Fancify a list."""
return "[ " + self.visitListType( node.elts ) + "]"
def visit_Dict(self, node):
"""Fancify a dictionary."""
self._tabLevel += 1
keys = map( self.visit, node.keys )
values = map( self.visit, node.values )
elements = []
for key, value in zip(keys,values):
elements.append( key + ' : ' + value )
result = "{ " + self.visitListElements( elements ) + "}"
self._tabLevel -= 1
return result
def visit_Tuple(self, node):
"""Fancify a tuple."""
return "( " + self.visitListType( node.elts ) + ")"
def visit_Name(self, node):
"""Visits a simple identifier"""
return node.id
def visit_Attribute(self, node):
"""Visits an 'object.attribute' node"""
return self.visit(node.value) + '.' + node.attr
def visit_keyword(self, node):
"""Fancify a keyword within a function a call or an object creation."""
return str(node.arg) + " = " + self.visit( node.value )
def visit_Str(self, node):
"""Fancify a simple string"""
return repr(node.s)
def visit_Num(self, node):
"""Fancify a number"""
return str(node.n)
def generic_visit(self, node):
return "\n".join( map( self.visit, ast.iter_child_nodes(node) ) )
| [
[
8,
0,
0.0606,
0.1111,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1313,
0.0101,
0,
0.66,
0.5,
809,
0,
1,
0,
0,
809,
0,
0
],
[
3,
0,
0.5606,
0.8283,
0,
0.66,
... | [
"'''\nCreated on 2009-09-08\n\n@author: beaudoin\n\nContains a abstract syntactic tree visitor for printing\nnested function calls in a nice way. Used for cleaning-up \noutput of the serialize method.",
"import ast",
"class Fancify( ast.NodeVisitor ):\n \n def __init__(self):\n super( Fancify, self... |
'''
Created on 2009-10-06
@author: beaudoin
A collection of useful functions for creating stock rigid bodies
'''
import Physics, MathLib, Mesh, PyUtils, math
from MathLib import Point3d, Vector3d
def createBox( size=(1,1,1), colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a box of the specified size. Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, size[0]*size[1]*size[2] )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createBox( proxy, size, colour, moiScale, withMesh )
def createArticulatedBox( size=(1,1,1), colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for a box of the specified size. Other articulated rigid body parameters can be specified with keyword arguments, look at
App.Proxys.ArticulatedRigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If mass is negative, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, size[0]*size[1]*size[2] )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createBox( proxy, size, colour, moiScale, withMesh )
def createTaperedBox( size=(1,1,1), colour=(0.6,0.6,0.6), exponentBottom = 5, exponentTop = 5, exponentSide = 5, moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a box of the specified size with tapered ends. Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, size[0]*size[1]*size[2] )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createTaperedBox( proxy, size, colour, exponentBottom, exponentTop, exponentSide, moiScale, withMesh )
def createArticulatedTaperedBox( size=(1,1,1), colour=(0.6,0.6,0.6), exponentBottom = 5, exponentTop = 5, exponentSide = 5, moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for a box of the specified size with tapered ends. Other articulated rigid body parameters can be specified with keyword arguments, look at
App.Proxys.ArticulatedRigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If mass is negative, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, size[0]*size[1]*size[2] )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createTaperedBox( proxy, size, colour, exponentBottom, exponentTop, exponentSide, moiScale, withMesh )
def createEllipsoid( radius=(1,1,1), colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for an ellipsoid with the specified attributes . Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, 4.0/3.0 * math.pi*radius*radius*radius )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createEllipsoid( proxy, radius, colour, moiScale, withMesh )
def createArticulatedEllipsoid( radius=(1,1,1), colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for an ellipsoid with the specified attributes . Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, 4.0/3.0 * math.pi*radius[0]*radius[1]*radius[2] )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createEllipsoid( proxy, radius, colour, moiScale, withMesh )
def createCylinder( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a cylinder with the specified attributes (axis is 0:x, 1:y, 2:z). Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, math.pi*radius*radius*math.fabs(tipPos-basePos) )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createCylinder( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh )
def createArticulatedCylinder( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for a cylinder with the specified attributes (axis is 0:x, 1:y, 2:z). Other articulated rigid body parameters can be specified with keyword arguments, look at
App.Proxys.ArticulatedRigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, math.pi*radius*radius*math.fabs(tipPos-basePos) )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createCylinder( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh )
def createCone( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a cone with the specified attributes (axis is 0:x, 1:y, 2:z). Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, math.pi*radius*radius*math.fabs(tipPos-basePos) )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createCone( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh )
def createArticulatedCone( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for a cone with the specified attributes (axis is 0:x, 1:y, 2:z). Other articulated rigid body parameters can be specified with keyword arguments, look at
App.Proxys.ArticulatedRigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, math.pi*radius*radius*math.fabs(tipPos-basePos) )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createCone( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh )
def _fixMass( kwargs, volume ):
"""
Private function.
If kwargs['mass'] is defined and negative, it is made positive and scaled by volume. (Considered as density.)
"""
try:
if kwargs['mass'] < 0 :
kwargs['mass'] = -kwargs['mass'] * volume
except KeyError:
pass
def _createBox( proxy, size, colour, moiScale, withMesh ):
"""
Private function.
Use createBox() or createArticulatedBox() instead.
"""
# Mesh and cdps will be set manually
proxy.meshes = None
proxy.cdps = None
# Compute box moi
size = PyUtils.toVector3d(size)
proxy.moi = MathLib.Vector3d( size.y*size.y + size.z*size.z,
size.x*size.x + size.z*size.z,
size.x*size.x + size.y*size.y, ) * 1.0/12.0 * proxy.mass * moiScale
box = proxy.createAndFillObject()
cdp = Physics.BoxCDP()
halfSize = PyUtils.toVector3d(size) * 0.5
cdp.setPoint1( MathLib.Point3d( halfSize * -1 ) )
cdp.setPoint2( MathLib.Point3d( halfSize ) )
box.addCollisionDetectionPrimitive( cdp )
if withMesh:
mesh = Mesh.createBox( size = size, colour = colour )
box.addMesh(mesh)
return box
def _createTaperedBox( proxy, size, colour, exponentBottom, exponentTop, exponentSide, moiScale, withMesh ):
"""
Private function.
Use createTaperedBox() or createArticulatedTaperedBox() instead.
"""
taperedBox = _createBox( proxy, size, colour, moiScale = moiScale, withMesh = False )
if withMesh:
mesh = Mesh.createEllipsoid(position=(0,0,0), radius=(size[0]/2.0, size[1]/2.0, size[2]/2.0), colour = colour,
exponentBottom = exponentBottom,
exponentTop = exponentTop,
exponentSide = exponentSide)
taperedBox.addMesh(mesh)
return taperedBox
def _createEllipsoid( proxy, radius, colour, moiScale, withMesh ):
"""
Private function.
Use createEllipsoid() or createArticulatedEllipsoid() instead.
"""
# Mesh and cdps will be set manually
proxy.meshes = None
proxy.cdps = None
# Compute box moi
moi = [0,0,0]
for i in range(3):
j = (i+1)%3
k = (i+2)%3
moi[i] = proxy.mass * (radius[j]*radius[j]+radius[k]*radius[k]) / 5.0
proxy.moi = PyUtils.toVector3d(moi) * moiScale
ellipsoid = proxy.createAndFillObject()
cdp = Physics.SphereCDP()
cdp.setCenter( Point3d(0,0,0) )
cdp.setRadius( min(radius) )
ellipsoid.addCollisionDetectionPrimitive( cdp )
if withMesh:
mesh = Mesh.createEllipsoid((0,0,0), radius, colour)
ellipsoid.addMesh(mesh)
return ellipsoid
def _createCylinder( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh ):
"""
Private function.
Use createCylinder() or createArticulatedCylinder() instead.
"""
if axis != 0 and axis != 1 and axis != 2 :
raise ValueError( 'Axis must be 0 for x, 1 for y or 2 for z.' )
# Mesh and cdps will be set manually
proxy.meshes = None
proxy.cdps = None
# Compute box moi
moi = [0,0,0]
height = math.fabs(tipPos-basePos)
for i in range(3):
if i == axis :
moi[i] = proxy.mass*radius*radius / 2.0
else :
moi[i] = proxy.mass*(3*radius*radius + height*height) / 12.0
### HACK!
moi[i] = max(moi[i], 0.01)
proxy.moi = PyUtils.toVector3d(moi) * moiScale
cylinder = proxy.createAndFillObject()
basePoint = [0,0,0]
tipPoint = [0,0,0]
basePoint[axis] = basePos
tipPoint[axis] = tipPos
basePoint3d = PyUtils.toPoint3d(basePoint)
tipPoint3d = PyUtils.toPoint3d(tipPoint)
baseToTipVector3d = Vector3d(basePoint3d, tipPoint3d)
if baseToTipVector3d.isZeroVector() :
raise ValueError( 'Invalid points for cylinder: base and tip are equal!' )
baseToTipUnitVector3d = baseToTipVector3d.unit()
if height <= radius*2.0 :
cdp = Physics.SphereCDP()
cdp.setCenter( basePoint3d + baseToTipVector3d*0.5 )
cdp.setRadius( height/2.0 )
else:
cdp = Physics.CapsuleCDP()
cdp.setPoint1( basePoint3d + baseToTipUnitVector3d * radius )
cdp.setPoint2( tipPoint3d + baseToTipUnitVector3d * -radius )
cdp.setRadius( radius )
cylinder.addCollisionDetectionPrimitive( cdp )
if withMesh:
mesh = Mesh.createCylinder( basePoint, tipPoint, radius, colour )
cylinder.addMesh(mesh)
return cylinder
def _createCone( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh ):
"""
Private function.
Use createCone() or createCone() instead.
"""
if axis != 0 and axis != 1 and axis != 2 :
raise ValueError( 'Axis must be 0 for x, 1 for y or 2 for z.' )
# Mesh and cdps will be set manually
proxy.meshes = None
proxy.cdps = None
# Compute box moi
moi = [0,0,0]
height = math.fabs(tipPos-basePos)
for i in range(3):
if i == axis :
moi[i] = proxy.mass*radius*radius * 3.0 / 10.0
else :
moi[i] = proxy.mass*(radius*radius/4.0 + height*height) * 3.0 / 5.0
proxy.moi = PyUtils.toVector3d(moi) * moiScale
cone = proxy.createAndFillObject()
basePoint = [0,0,0]
tipPoint = [0,0,0]
basePoint[axis] = basePos
tipPoint[axis] = tipPos
basePoint3d = PyUtils.toPoint3d(basePoint)
tipPoint3d = PyUtils.toPoint3d(tipPoint)
baseToTipVector3d = Vector3d(basePoint3d, tipPoint3d)
if baseToTipVector3d.isZeroVector() :
raise ValueError( 'Invalid points for cone: base and tip are equal!' )
baseToTipUnitVector3d = baseToTipVector3d.unit()
if height <= radius*2.0 :
cdp = Physics.SphereCDP()
cdp.setCenter( basePoint3d + baseToTipVector3d*0.5 )
cdp.setRadius( height/2.0 )
else:
cdp = Physics.CapsuleCDP()
cdp.setPoint1( basePoint3d + baseToTipUnitVector3d * radius )
cdp.setPoint2( tipPoint3d + baseToTipUnitVector3d * -radius )
cdp.setRadius( radius )
cone.addCollisionDetectionPrimitive( cdp )
if withMesh:
mesh = Mesh.createCone( basePoint, tipPoint, radius, colour )
cone.addMesh(mesh)
return cone
| [
[
8,
0,
0.0108,
0.0189,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0243,
0.0027,
0,
0.66,
0.0556,
347,
0,
5,
0,
0,
347,
0,
0
],
[
1,
0,
0.027,
0.0027,
0,
0.66,... | [
"'''\nCreated on 2009-10-06\n\n@author: beaudoin\n\nA collection of useful functions for creating stock rigid bodies\n'''",
"import Physics, MathLib, Mesh, PyUtils, math",
"from MathLib import Point3d, Vector3d",
"def createBox( size=(1,1,1), colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):\n ... |
'''
Created on 2009-09-16
@author: beaudoin
A Python version of the C++ Observable class found in Utils
'''
class Observable(object):
def __init__(self):
self._observers = []
self._hasChanged = False
self._batchChangeDepth = 0
def setChanged(self):
"""Protected. Indicate that the object has changed."""
self._hasChanged = True
def clearChanged(self):
"""Protected. Indicate that the object changes have been sent to every observer."""
self._hasChanged = False
def notifyObservers(self, data = None):
"""Protected. Notify observers that a change has occurred.
Doesn't notify if a batch change is going on."""
self.setChanged()
self.notifyObserversIfChanged( data )
def notifyObserversIfChanged(self, data = None ):
"""Protected. Notify observers only if the object has been modified.
Doesn't notify if a batch change is going on."""
if not self.isDoingBatchChanges() and self.hasChanged():
for observer in self._observers:
observer.update( data )
self.clearChanged()
def hasChanged(self):
"""Return true if this object has changed since last notification."""
return self._hasChanged
def isDoingBatchChanges(self):
"""Returns true if this object is currently going through a batch of changes."""
return self._batchChangeDepth > 0
def beginBatchChanges(self):
"""Indicates that we want to begin performing batch changes on this object.
Every call to beginBatchChanges() should be matched by a call to endBatchChanges(),
observers will only be notified when the first begin is closed by the last end.
The call to endBatchChanges() should usually be in a finally clause."""
self._batchChangeDepth += 1
def endBatchChanges(self):
"""Indicates that we want to end performing batch changes on this object.
Every call to beginBatchChanges() should be matched by a call to endBatchChanges(),
observers will only be notified when the first begin is closed by the last end.
The call to endBatchChanges() should usually be in a finally clause."""
self._batchChangeDepth -= 1
self.notifyObserversIfChanged()
def addObserver(self, observer):
"""Adds an observer to this object. Observers need to have a method:
update( observable, data = None )
Where observable is an observable object and data is an arbitrary data object."""
self._observers.append( observer )
def deleteObserver(self, observer):
"""Removes the specified observer from the list of observers."""
self._observers.remove(observer)
def countObservers(self):
"""Returns the number of observers of this object."""
return len( self._observers )
@classmethod
def typeName(cls):
"""Returns the name of the class."""
return cls.__name__
| [
[
8,
0,
0.0513,
0.0897,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
3,
0,
0.5577,
0.8974,
0,
0.66,
1,
546,
0,
13,
0,
0,
186,
0,
10
],
[
2,
1,
0.1603,
0.0513,
1,
0.19,
... | [
"'''\nCreated on 2009-09-16\n\n@author: beaudoin\n\nA Python version of the C++ Observable class found in Utils \n'''",
"class Observable(object):\n \n def __init__(self):\n self._observers = []\n self._hasChanged = False\n self._batchChangeDepth = 0\n \n def setChanged(self):... |
'''
Created on 2009-09-02
@author: beaudoin
'''
def callOnObjectOrList( objectOrList, function ):
"""Apply the specified function on :
- The single element passed as first parameter
- The list of elements passed as first parameter, if this is a list or tuple
- The list of values passed as first parameter if this is a dict
The passed function should receive a single parameter.
Does not return anything, so whatever is returned by function is lost."""
if hasattr( objectOrList, 'values' ):
for object in objectOrList.values(): function(object)
elif hasattr( objectOrList, '__iter__' ):
for object in objectOrList: function(object)
else:
function( objectOrList )
def callOnObjectOrListAndEnumerate( objectOrList, function ):
"""Apply the specified function on :
- The single element passed as first parameter
- The list of elements passed as first parameter, if this is a list or tuple
- The list of values passed as first parameter if this is a dict
The passed function should receive two parameters: an index or the object.
Does not return anything, so whatever is returned by function is lost."""
if hasattr( objectOrList, 'values' ):
for i, object in enumerate(objectOrList.values()): function(i,object)
elif hasattr( objectOrList, '__iter__' ):
for i, object in enumerate(objectOrList): function(i,object)
else:
function( 0, objectOrList )
def _moduleExist( moduleNames ):
"""Checks that the specified module can be loaded in the current python path.
moduleNames is a list containing every element of the module name. For example,
module 'Data.Character.Robot' would be [ 'Data', 'Character', 'Robot' ] """
import sys, os
for path in sys.path :
fileName = os.path.join( path, *moduleNames )
if os.path.exists( fileName + '.py' ) : return True
return False
def _getData( dataModule ):
"""Private function. Access the data contained in the specified dataModule"""
# First check if file exist.
# This is better than using the python exception handling, since we don't want to
# inadvertently catch exceptions generated during module importation.
modules = dataModule.split('.')
if modules[0] != "Data" : modules.insert(0, "Data")
if not _moduleExist( modules ) :
modules.append( modules[-1] )
if not _moduleExist( modules ) :
raise ImportError( "Can't find data module '" + dataModule + "'." )
moduleName = '.'.join(modules)
module = __import__( moduleName, globals(), locals(), ["data"] )
reload( module )
try:
return module.data
except( AttributeError ):
raise ImportError( "Data module '" + dataModule + "' doesn't contain a variable named 'data'." )
def load( dataModule, *args ):
"""Loads the object contained in the specified data module.
A data module is a python-style name for a module located under the
'Data' package. For example to load the data contained
into 'Data/Character/Robot/Controllers/Walk.py', call
load( "Character.Robot.Controllers.Walk" ).
As a shortcut, if the specified dataModule is a package, the
function will look for a module having the exact name of the package.
For example, load( "Character.Robot" ) is the same as load( "Character.Robot.Robot" ).
Any extra parameter passed to the function are passed to the load method
of the loaded object. Returns the loaded object. """
data = _getData( dataModule )
return data.load(*args)
def loadRename( dataModule, objectName, *args ):
"""Loads the object contained in the specified data module.
A data module is a python-style name for a module located under the
'Data' package. For example to load the data contained
into 'Data/Character/Robot/Controllers/Walk.py', call
load( "Character.Robot.Controllers.Walk" ).
As a shortcut, if the specified dataModule is a package, the
function will look for a module having the exact name of the package.
For example, load( "Character.Robot" ) is the same as load( "Character.Robot.Robot" ).
Any extra parameter passed to the function are passed to the load method
of the loaded object. Returns the loaded object. """
data = _getData( dataModule )
data.name = objectName
return data.load(*args)
def loadMany( dataModule, count, *args ):
"""Loads 'count' instances of the object contained in the specified data module.
See 'load' for more details on what is a dataModule.
If they have a 'name' attribute, an underscore and a number starting at '_0' will be appended to each instance.
If they have a 'pos' attribute, then the positions will be moved around.
Returns a list of all the loaded object. """
from MathLib import Vector3d
data = _getData( dataModule )
result = []
for i in range(0,count):
dataCopy = data
try: dataCopy.name = data.name + "_" + str(i)
except AttributeError: pass
try: dataCopy.pos += Vector3d(10,10,10) * i
except AttributeError: pass
result.append( dataCopy.load(*args) )
return result
def getClassName( object ):
"""
Returns the name of the class of the specified object.
The object must have a method typeName() that returns the name of the class (i.e. "class ClassName" or "ClassName").
"""
return object.typeName().split(' ')[-1]
def getProxyClass( object ):
"""
This function returns the proxy class for specified object. This class will
have the following methods:
wrap(object) : returns the proxy class for the specified object
getIcon() : returns the filename of a png icon that represents the object
getName(object) : returns a string that can be used to identify the object
Moreover, the proxy class can be constructed using all the accessible members
of the wrapped object.
"""
from App import Proxys
className = getClassName(object)
try:
# Create an instance of the equivalent python wrapper class
return Proxys.__dict__[className]
except NameError:
raise NameError( "No proxy class known for object of type '%s'." % className )
def wrap( object, recursive = True ):
"""
This function creates an instance of the correct proxy class to wrap the specified object.
The proxy class will have the exact same name, but the class will come from the App.Proxys package.
As a container, specify the object (not proxy object) to which this object will be attached with an HAS_A or HAS_MANY relationship.
As an index, specify the position at which this object appear in the list of his container. Only useful with an HAS_MANY relationship.
Pass recursive = False to only wrap non-object members. The members containing object references or list of objects will not be wrapped and will be None.
"""
if object is None : return None
return getProxyClass(object).wrap( object, recursive )
def serialize(object):
"""Tries to create a serialized version of the object. Wrap it if needed."""
try: proxyClass = getProxyClass(object)
except AttributeError:
result = repr( object )
if result[0]=='<' :
raise TypeError( "Cannot wrap object " + result + ". Missing typeName() or proxy class." )
return result
return repr( getProxyClass(object).wrap( object, True ) )
def copy(object, *args):
"""Copy the object."""
copiedWrapper = wrapCopy( object )
try: copiedWrapper.name = copiedWrapper.name + "_Copy"
except AttributeError: pass
return copiedWrapper.createAndFillObject(None, *args)
def wrapCopy(object):
"""Wrap a copy of the object."""
from App import Proxys
return eval( serialize(object), Proxys.__dict__ )
def toVector3d( tuple ):
"""Converts a tuple to a Vector3d. If it is already a ThreeTuple, return it as a vector."""
from MathLib import Vector3d, ThreeTuple
if tuple is None: return None
if isinstance( tuple, ThreeTuple ) : return Vector3d(tuple)
if len(tuple) != 3:
raise TypeError( "A Vector3D should be a 3-tuple" )
return Vector3d( tuple[0], tuple[1], tuple[2] )
def fromVector3d( vec ):
"""Converts a Vector3D to a tuple"""
if vec is None: return None
return (vec.x, vec.y, vec.z)
def toPoint3d( tuple ):
"""Converts a tuple to a Point3D. If it is already a Point3D, return it."""
from MathLib import Point3d, ThreeTuple
if tuple is None: return None
if isinstance( tuple, ThreeTuple ) : return Point3d(tuple)
if len(tuple) != 3:
raise TypeError( "A Point3D should be a 3-tuple" )
return Point3d( tuple[0], tuple[1], tuple[2] )
def fromPoint3d( pt ):
"""Converts a Point3d to a tuple"""
if pt is None: return None
return (pt.x, pt.y, pt.z)
def angleAxisToQuaternion( tuple ):
"""Converts a 2-tuple (angle, (axis_x, axis_y, axis_z)) to a Quaternion. If it is already a Quaternion, return it."""
from MathLib import Quaternion
if tuple is None: return None
if isinstance( tuple, Quaternion ) : return tuple
if len(tuple) != 2:
raise TypeError( "An angle-axis quaternion should be a 2-tuple" )
q = Quaternion()
q.setToRotationQuaternion( tuple[0], toVector3d( tuple[1] ) )
return q
def angleAxisFromQuaternion( quat ):
"""Converts Quaterion to a 2-tuple (angle, (axis_x, axis_y, axis_z))"""
if quat is None: return None
return ( quat.getAngle(), fromVector3d( quat.getAxis() ) )
def toTrajectory1d( tupleList ):
"""Converts a list of 2-tuple to a Core.Trajectory1d"""
from MathLib import Trajectory1d
if tupleList is None: return None
traj = Trajectory1d()
for tuple in tupleList:
if len(tuple) != 2 : raise TypeError( "A Trajectory1d should be a list of 2-tuples" )
traj.addKnot( tuple[0], tuple[1] )
return traj
def fromTrajectory1d( traj ):
"""Converts Core.Trajectory1d to a list of 2-tuple"""
if traj is None: return None
return [ (traj.getKnotPosition(i), traj.getKnotValue(i)) for i in range(traj.getKnotCount()) ]
def fancify( expr ):
"""Add new line, spaces and intentation to the passed expression"""
import ast
import Fancify
tree = ast.parse( expr )
return Fancify.Fancify().visit(tree)
def sameObject( obj1, obj2 ):
"""True if the two objects are the same. Very similar to the "is" python keyword, but returns
true if both objects are different SWIG wrapper of the same object."""
try:
return obj1.this == obj2.this
except AttributeError:
return obj1 is obj2
def sameObjectInList( object, objectList ):
"""True if the object is in the list. See sameObject for an explanation on how the comparison is made."""
for other in objectList:
if sameObject(object, other):
return True
return False
def safeEqual( obj1, obj2 ):
"""True if both objects are None or both are equals."""
try: return obj1 == obj2
except (ValueError, TypeError): return False
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
import warnings
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function %s." % func.__name__,
category=DeprecationWarning, stacklevel = 2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def unCamelCase(inString):
"""Takes a string in camel case and remove camel case, inserting spaces and capitalize."""
import string
result = []
prev = 0
for i, char in enumerate(inString):
if i == 0: continue
if char in string.uppercase:
result.append( inString[prev:i] )
prev = i
result.append( inString[prev:] )
return ' '.join(result).capitalize()
def convertController(controllerFileName, character = None ):
"""
Takes the filename to an old-style controller file and converts it to the new format.
If a character is provided it is used for loading, otherwise the 1st character of the application is used.
"""
import wx, Core
character = wx.GetApp().getCharacter( character )
if character is None:
character = wx.GetApp().getCharacter(0)
if character is None:
raise AttributeError( "No character provided, and none found in the application" )
controller = Core.SimBiController(character)
controller.loadFromFile( controllerFileName )
print fancify( repr( wrap( controller ) ) )
def _buildGetterOrSetter( prefix, varName ):
"""Utility function used by getterName and setterName."""
if varName[0] == '_' :
varName = varName[1:]
return prefix + varName[0].upper() + varName[1:]
def getterName( varName ):
"""
Given that the string varName holds a variable (prefixed with _ or not), this method returns the standard
name of the getter for that variable. i.e. 'getVarName'
"""
return _buildGetterOrSetter( 'get', varName )
def setterName( varName ):
"""
Given that the string varName holds a variable (prefixed with _ or not), this method returns the standard
name of the setter for that variable. i.e. 'setVarName'
"""
return _buildGetterOrSetter( 'set', varName )
| [
[
8,
0,
0.0091,
0.0152,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
0,
0.0409,
0.0424,
0,
0.66,
0.0323,
564,
0,
2,
0,
0,
0,
0,
6
],
[
8,
1,
0.0318,
0.0182,
1,
0.78,
... | [
"'''\nCreated on 2009-09-02\n\n@author: beaudoin\n'''",
"def callOnObjectOrList( objectOrList, function ):\n \"\"\"Apply the specified function on :\n - The single element passed as first parameter\n - The list of elements passed as first parameter, if this is a list or tuple\n - The list ... |
from Utils import *
from Enum import enum
from Observable import Observable
import Mesh
import RigidBody | [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
842,
0,
1,
0,
0,
842,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.25,
575,
0,
1,
0,
0,
575,
0,
0
],
[
1,
0,
0.6,
0.2,
0,
0.66,
0.5,
5... | [
"from Utils import *",
"from Enum import enum",
"from Observable import Observable",
"import Mesh",
"import RigidBody"
] |
'''
Created on 2009-10-06
@author: beaudoin
A collection of useful functions for creating stock meshes
'''
import GLUtils, PyUtils, MathLib, math
from MathLib import Point3d, Vector3d
def create( vertices, faces, colour=(0.6,0.6,0.6) ):
"""
Creates a mesh having the specified vertices and faces.
Vertices should be a list of 3-tuples of float or Point3d (positions).
Faces should be a list of tuples of indices.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
mesh = GLUtils.GLMesh()
for vertex in vertices:
mesh.addVertex( PyUtils.toPoint3d(vertex) )
for face in faces:
poly = GLUtils.GLIndexedPoly()
for index in face:
poly.addVertexIndex( index )
mesh.addPoly(poly)
try:
mesh.setColour( *colour )
except TypeError:
mesh.setColour( *(colour + (1,)) )
mesh.computeNormals()
return mesh
def createBox( size=(1,1,1), position=(0,0,0), colour=(0.6,0.6,0.6) ):
"""
Creates the mesh for a box having the specified size and a specified position.
The size should be a 3-tuple (xSize, ySize, zSize).
The position should be a 3-tuple.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
size = PyUtils.toVector3d(size)
position = PyUtils.toPoint3d(position)
vertices = []
delta = MathLib.Vector3d()
for repeat in range(3):
for x in (-0.5,0.5) :
delta.x = size.x * x
for y in (-0.5,0.5) :
delta.y = size.y * y
for z in (-0.5,0.5) :
delta.z = size.z * z
vertices.append( position + delta )
faces = [(0,1,3,2),(5,4,6,7), # YZ Faces
(9,13,15,11),(12,8,10,14), # XY Faces
(18,19,23,22),(17,16,20,21)] # XZ Faces
return create( vertices, faces, colour )
def createTaperedBox( position=(0,0,0), size=(1,1,1), colour=(0.6,0.6,0.6), samplesY = 20, samplesXZ = 20, exponentBottom = 4, exponentTop = 4, exponentSide = 4 ):
"""
Creates the mesh for a box having the specified size and a specified position.
The size should be a 3-tuple (xSize, ySize, zSize).
The position should be a 3-tuple.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
return createEllipsoid( position, (size[0]/2.0,size[1]/2.0,size[2]/2.0), colour, samplesY, samplesXZ, exponentBottom, exponentTop, exponentSide )
def createSphere( position=(0,0,0), radius=1, colour=(0.6,0.6,0.6), samplesY = 20, samplesXZ = 20 ):
"""
Creates the mesh for an sphere having the specified position and radius
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
return createEllipsoid( position, (radius,radius,radius), colour, samplesY, samplesXZ )
def createEllipsoid( position=(0,0,0), radius=(1,1,1), colour=(0.6,0.6,0.6), samplesY = 20, samplesXZ = 20, exponentBottom = 2, exponentTop = 2, exponentSide = 2 ):
"""
Creates the mesh for an ellipsoid having the specified position and radius
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
if exponentBottom < 2.0 or exponentTop < 2.0 or exponentSide < 2.0 :
raise ValueError( 'Exponents for ellipsoid must all be under 2.0!' )
position = PyUtils.toPoint3d(position)
vertices = []
for i in range(1,samplesY):
thetaI = i*math.pi/float(samplesY)
if i < samplesY / 2 :
n = exponentTop
else:
n = exponentBottom
cos = math.cos(thetaI)
y = cos * radius[1]
scaleXZ = math.pow( 1-math.pow(math.fabs(cos),n), 1.0/float(n) )
for j in range(0,samplesXZ):
thetaJ = j*2.0*math.pi/float(samplesXZ)
n = exponentSide
cos = math.cos(thetaJ)
x = cos * scaleXZ * radius[0]
z = math.pow( 1-math.pow(math.fabs(cos),n), 1.0/float(n) ) * math.copysign(1, math.sin(thetaJ)) * scaleXZ * radius[2]
vertices.append( position + Vector3d(x,y,z) )
vertices.append( position + Vector3d(0,radius[1],0) )
vertices.append( position + Vector3d(0,-radius[1],0) )
faces = []
for i in range(0,(samplesY-2)*samplesXZ,samplesXZ) :
for j in range(0,samplesXZ) :
faces.append( (i+j, i+(j+1)%samplesXZ, i+samplesXZ+(j+1)%samplesXZ, i+samplesXZ+j) )
for i in range(0,samplesXZ) :
base = (samplesY-2)*samplesXZ
faces.append( ((i+1)%samplesXZ, i, (samplesY-1)*samplesXZ) )
faces.append( (base+i, base+(i+1)%samplesXZ, (samplesY-1)*samplesXZ+1) )
return create( vertices, faces, colour )
def createCylinder( basePoint=(0,-1,0), tipPoint=(0,1,0), radius = 1.0, colour=(0.6,0.6,0.6), samples = 20 ):
"""
Creates the mesh for a cylinder between the two specified points.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
basePoint = PyUtils.toPoint3d(basePoint)
tipPoint = PyUtils.toPoint3d(tipPoint)
baseToTipVector = Vector3d(basePoint,tipPoint)
if baseToTipVector.isZeroVector() :
raise ValueError( 'Invalid points for cylinder: base and tip are equal!' )
baseToTipUnitVector = baseToTipVector.unit()
xUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,0,1) )
if xUnitVector.length() < 0.5 :
xUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,-1,0) )
xUnitVector.toUnit()
yUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(-1,0,0) )
if yUnitVector.length() < 0.5 :
yUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,1,0) )
yUnitVector.toUnit()
vertices = []
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( basePoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( tipPoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( basePoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
vertices.append( tipPoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
faces = [ range(0,samples), range(samples,2*samples) ]
for i in range(0,2*samples,2) :
base = 2*samples
size = 2*samples
faces.append( (base+i, base+i+1, base+(i+3)%size, base+(i+2)%size ) )
return create( vertices, faces, colour )
def createCone( basePoint=(0,-1,0), tipPoint=(0,1,0), radius = 1.0, colour=(0.6,0.6,0.6), samples = 20 ):
"""
Creates the mesh for a cone between the two specified points.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
basePoint = PyUtils.toPoint3d(basePoint)
tipPoint = PyUtils.toPoint3d(tipPoint)
baseToTipVector = Vector3d(basePoint,tipPoint)
if baseToTipVector.isZeroVector() :
raise ValueError( 'Invalid points for cylinder: base and tip are equal!' )
baseToTipUnitVector = baseToTipVector.unit()
xUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,0,1) )
if xUnitVector.length() < 0.5 :
xUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,-1,0) )
xUnitVector.toUnit()
yUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(-1,0,0) )
if yUnitVector.length() < 0.5 :
yUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,1,0) )
yUnitVector.toUnit()
vertices = []
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( basePoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( basePoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
vertices.append( tipPoint )
faces = [ range(0,samples) ]
for i in range(0,samples) :
base = samples
size = samples
faces.append( (base+i, base+(i+1)%size, 2*samples ) )
return create( vertices, faces, colour )
| [
[
8,
0,
0.0191,
0.0335,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0431,
0.0048,
0,
0.66,
0.1111,
810,
0,
4,
0,
0,
810,
0,
0
],
[
1,
0,
0.0478,
0.0048,
0,
0.66... | [
"'''\nCreated on 2009-10-06\n\n@author: beaudoin\n\nA collection of useful functions for creating stock meshes\n'''",
"import GLUtils, PyUtils, MathLib, math",
"from MathLib import Point3d, Vector3d",
"def create( vertices, faces, colour=(0.6,0.6,0.6) ):\n \"\"\"\n Creates a mesh having the specified ve... |
'''
Created on 2009-09-28
@author: beaudoin
'''
def enum( *args ):
"""
Creates an enum class.
Pass a dictionnary { choice : value, ... }
Here, choice needs to be a string and value is an integer
Can also pass a list or a tuple, then the values will be given automatically, starting at 0
Instances of this class can have any of the values available in choices
Examples:
Colors = enum( {"red" : 10, "green" : 20, "yellow" : 30} )
Colors.int( "red" ) ==> 10
Colors.str( 20 ) ==> green
x = Colors("red")
x ==> "red"
str(x) ==> red
int(x) ==> 10
x.set( "green" )
x.set( 30 )
"""
@classmethod
def toInt(cls,choice):
"""Return the value associated with the choice (an integer)."""
if choice is None : return None
return cls.choicesDict[choice]
@classmethod
def toStr(cls,value):
"""Return the choice associated with the value (a string)."""
if value is None : return None
return cls.valuesDict[value]
@classmethod
def values(cls):
"""Return the choice associated with the value (a string)."""
return valuesDict.keys()
@classmethod
def choices(cls):
"""Return the choice associated with the value (a string)."""
return choicesDict.keys()
def __init__(self, value=None):
"""Initialize a new instance of this enum class"""
self.set(value)
def __repr__(self):
"""A representation of this object"""
if self.value is None : return repr(None)
return repr( str(self) )
def __int__(self):
"""Return the value currently associated with this variable"""
return int( self.value )
def __str__(self):
"""Return the value currently associated with this variable"""
if self.value is None : return str(None)
return self.toStr( self.value )
def __eq__(self,other):
"""Checks that this enum is equal to the other, which can be an enum of the same type, a value, or a string."""
if isinstance(other, basestring) : return other == str(self)
return self.value == int(other)
def __ne__(self,other):
"""Checks that this enum is equal to the other, which can be an enum of the same type, a value, or a string."""
return not self == other
def set(self, value):
"""Changes the value of self"""
if value is None : self.value = None
try: self.value = value.value
except AttributeError:
if isinstance(value, int) : self.value = value
elif isinstance(value, basestring) : self.value = self.toInt(value)
else: raise ValueError( "Trying to set an enum with an invalid type. Only int and str can be used." )
return self
# Reverse the dictionary
if len(args) == 1 and isinstance(args[0], dict) :
choicesDict = args[0]
else:
choicesDict = {}
for i, choice in enumerate( args ) : choicesDict[choice] = i
try: del i
except UnboundLocalError: pass
valuesDict = {}
for choice, value in choicesDict.iteritems(): valuesDict[value] = choice
try: del choice
except UnboundLocalError: pass
try: del value
except UnboundLocalError: pass
try: del args
except UnboundLocalError: pass
return type('Enum',(object,),locals())
| [
[
8,
0,
0.0283,
0.0472,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
0,
0.533,
0.9245,
0,
0.66,
1,
820,
0,
1,
1,
0,
0,
0,
22
],
[
8,
1,
0.1651,
0.1698,
1,
0.51,
0... | [
"'''\nCreated on 2009-09-28\n\n@author: beaudoin\n'''",
"def enum( *args ):\n \"\"\"\n Creates an enum class. \n Pass a dictionnary { choice : value, ... }\n Here, choice needs to be a string and value is an integer\n Can also pass a list or a tuple, then the values will be given automatically, st... |
'''
Created on 2009-11-27
@author: beaudoin
'''
import Core
import random, math
from MathLib import Point3d, Vector3d
class WalkController(Core.IKVMCController):
def __init__(self, character):
super(WalkController,self).__init__(character)
def typeName(self):
return self.__class__.__name__
def initialSetup(self):
"""Call this method for the first setup of the dance controller"""
self.desiredCoronalStepLength = 0.04
self.defaultStepSize = 0.275
self.legLength = 1
self.setupParameters()
def setupParameters(self):
"""Called whenever parameters are setup"""
self.getState(0).setDuration( Core.cvar.SimGlobals_stepTime )
#now prepare the step information for the following step:
footStart = self.getStanceFootPos().z
sagittalPlaneFutureFootPos = footStart + self.defaultStepSize
self.swingFootTrajectory.clear()
self.setSagittalBalanceFootPlacement( 1 )
self.swingFootTrajectory.addKnot(0, Point3d(0, 0.04, self.getSwingFootPos().z - footStart));
self.swingFootTrajectory.addKnot(0.5, Point3d(0, 0.05 + 0.1 + Core.cvar.SimGlobals_stepHeight, 0.5 * self.getSwingFootPos().z + sagittalPlaneFutureFootPos * 0.5 - footStart));
self.swingFootTrajectory.addKnot(1, Point3d(0, 0.05 + 0, sagittalPlaneFutureFootPos - footStart));
def performPreTasks(self, contactForces):
"""Performs all the tasks that need to be done before the physics simulation step."""
v = self.getV()
d = self.getD()
self.velDSagittal = Core.cvar.SimGlobals_VDelSagittal
curState = self.getCurrentState()
fLean = Core.cvar.SimGlobals_rootSagittal
traj = curState.getTrajectory("root")
component = traj.getTrajectoryComponent(2)
component.offset = fLean;
traj = curState.getTrajectory("pelvis_lowerback")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*1.5;
traj = curState.getTrajectory("lowerback_torso")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*2.5;
traj = curState.getTrajectory("torso_head")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*3.0;
traj = curState.getTrajectory("STANCE_Knee")
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_stanceKnee
self.legOrientation = Core.cvar.SimGlobals_duckWalk
super(WalkController,self).performPreTasks(contactForces)
def performPostTasks(self, dt, contactForces):
"""Performs all the tasks that need to be done after the physics simulation step."""
step = Vector3d(self.getStanceFootPos(), self.getSwingFootPos())
step = self.getCharacterFrame().inverseRotate(step)
phi = self.getPhase()
if step.z > 0.7 :
self.setPhase( 1.0 )
if super(WalkController,self).performPostTasks(dt, contactForces):
v = self.getV()
print "step: %3.5f %3.5f %3.5f. Vel: %3.5f %3.5f %3.5f. phi = %f\n" % (step.x, step.y, step.z, v.x, v.y, v.z, phi);
self.setupParameters()
| [
[
8,
0,
0.0337,
0.0562,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0787,
0.0112,
0,
0.66,
0.25,
463,
0,
1,
0,
0,
463,
0,
0
],
[
1,
0,
0.0899,
0.0112,
0,
0.66,
... | [
"'''\nCreated on 2009-11-27\n\n@author: beaudoin\n'''",
"import Core",
"import random, math",
"from MathLib import Point3d, Vector3d",
"class WalkController(Core.IKVMCController):\n \n def __init__(self, character):\n super(WalkController,self).__init__(character)\n \n def typeName(se... |
'''
Created on 2009-11-27
@author: beaudoin
'''
import Core
import random, math
from MathLib import Point3d, Vector3d
class DanceController(Core.IKVMCController):
def __init__(self, character):
super(DanceController,self).__init__(character)
def typeName(self):
return self.__class__.__name__
def initialSetup(self):
"""Call this method for the first setup of the dance controller"""
self.desiredCoronalStepLength = -0.02
self.silly = 0;
self.cnt = 0.0001;
self.sillySign = 1;
self.silly2 = 0;
self.cnt2 = 0.0003;
self.sillySign2 = 1;
self.defaultStepSize = 0.275
self.legLength = 1
self.setupParameters()
def setupParameters(self):
"""Called whenever parameters are setup"""
self.getState(0).setDuration( Core.cvar.SimGlobals_stepTime )
#now prepare the step information for the following step:
footStart = self.getStanceFootPos().z
sagittalPlaneFutureFootPos = footStart + self.defaultStepSize
self.swingFootTrajectory.clear()
self.setSagittalBalanceFootPlacement( 1 )
# self.swingFootTrajectory.addKnot(0, Point3d(0, 0.04, self.getSwingFootPos().z - footStart));
# self.swingFootTrajectory.addKnot(0.5, Point3d(0, 0.05 + 0.1 + Core.cvar.SimGlobals_stepHeight, 0.5 * self.getSwingFootPos().z + sagittalPlaneFutureFootPos * 0.5 - footStart));
# self.swingFootTrajectory.addKnot(1, Point3d(0, 0.05 + 0, sagittalPlaneFutureFootPos - footStart));
self.swingFootTrajectory.addKnot(0, Point3d(0, 0.06 + 0.1, 0))
self.swingFootTrajectory.addKnot(0.75, Point3d(0, 0.08 + 0.1 + Core.cvar.SimGlobals_stepHeight, 0.15))
self.swingFootTrajectory.addKnot(1.0, Point3d(0, 0.08 + Core.cvar.SimGlobals_stepHeight/2, 0.15))
# controller->swingFootTrajectory.addKnot(1, Point3d(0, 0.05, 0.27));
takeAStep = False
idleMotion = False
if self.doubleStanceMode and idleMotion:
if random.random() < 0.2:
Core.cvar.SimGlobals_upperBodyTwist = (random.random() - 0.5)
elif random.random() < 0.2:
self.doubleStanceMode = False
Core.cvar.SimGlobals_desiredHeading += Core.cvar.SimGlobals_upperBodyTwist + (random.random() - 0.5)
Core.cvar.SimGlobals_upperBodyTwist = 0;
takeAStep = True;
v = self.getV()
print "v.x: %f, v.z: %f" % (v.x, v.z)
if math.fabs(v.x) < 0.1 and \
math.fabs(v.z) < 0.05 and \
math.fabs(Core.cvar.SimGlobals_VDelSagittal) <= 0.1 and \
shouldComeToStop :
if not self.doubleStanceMode :
# check out the distance between the feet...
fMidPoint = Vector3d(self.stanceFoot.getCMPosition(), self.swingFoot.getCMPosition())
errV = self.characterFrame.inverseRotate(self.doubleStanceCOMError)
if errV.length() < 0.05 and fMidPoint.length() < 0.2 and fMidPoint.length() > 0.05 :
self.doubleStanceMode = True;
def checkStanceState(self):
"""Checks the stance state"""
if self.getDoubleStanceCOMError().length() > 0.06 :
if self.doubleStanceMode :
print "Should take a step...\n"
self.doubleStanceMode = False
def performPreTasks(self, contactForces):
"""Performs all the tasks that need to be done before the physics simulation step."""
v = self.getV()
d = self.getD()
self.checkStanceState()
self.velDSagittal = Core.cvar.SimGlobals_VDelSagittal
curState = self.getCurrentState()
# fLean = 0
# errM = v.z - self.velDSagittal
# sign = math.copysign( 1, errM )
# errM = math.fabs(errM)
# if errM > 0.3 :
# fLean += -(errM*sign - 0.3*sign) / 5.0
# if fLean > 0.15 :
# fLean = 0.15
# if fLean < -0.15 :
# fLean = -0.15
fLean = Core.cvar.SimGlobals_rootSagittal
sign = 1
if self.getStance() == Core.LEFT_STANCE :
sign = -1
self.silly += self.sillySign * self.cnt
if self.silly > 0.15 : self.sillySign = -1
if self.silly < -0.15 : self.sillySign = 1
traj = curState.getTrajectory("root")
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_upperBodyTwist/2.0 * sign
traj = curState.getTrajectory("pelvis_lowerback")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*1.5
component = traj.getTrajectoryComponent(1)
component.offset = self.silly *1.5* sign
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_upperBodyTwist * sign
traj = curState.getTrajectory("lowerback_torso")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*2.5
component = traj.getTrajectoryComponent(1)
component.offset = self.silly *2.5* sign
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_upperBodyTwist*2.0 * sign
traj = curState.getTrajectory("torso_head")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*3.0
component = traj.getTrajectoryComponent(1)
component.offset = self.silly * 1 * sign
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_upperBodyTwist*3.0 * sign
self.silly2 += self.sillySign2 * self.cnt2
if self.silly2 > 0.15 : self.sillySign2 = -1
if self.silly2 < -0.2 : self.sillySign2 = 1
traj = curState.getTrajectory("lShoulder")
component = traj.getTrajectoryComponent(2)
component.offset = self.silly2*10.0
component = traj.getTrajectoryComponent(0)
component.offset = self.silly2*-2.0
component = traj.getTrajectoryComponent(1)
component.offset = self.silly2*self.silly2*25
traj = curState.getTrajectory("rShoulder")
component = traj.getTrajectoryComponent(2)
component.offset = self.silly2*10.0
component = traj.getTrajectoryComponent(0)
component.offset = self.silly2*-2.0
component = traj.getTrajectoryComponent(1)
component.offset = self.silly2*self.silly2*-25
self.velDLateral = 0.0
self.coronalPlaneOffset = 0
# tmp = (0.8 - self.getPhase()) / 0.6
# if tmp < 0 : tmp = 0
# if tmp > 1 : tmp = 1
# if math.fabs(v.x) > 0.1 or math.fabs(d.x) > 0.05 :
# tmp = 0
# tmp = 0
# controller.coronalBalanceFootPlacement = 1-tmp
self.setCoronalBalanceFootPlacement( 1 )
if self.doubleStanceMode :
self.setPhase( 0.3 )
traj = curState.getTrajectory("STANCE_Knee")
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_stanceKnee
traj = curState.getTrajectory("SWING_Knee")
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_stanceKnee
self.legOrientation = Core.cvar.SimGlobals_duckWalk
super(DanceController,self).performPreTasks(contactForces)
def performPostTasks(self, dt, contactForces):
"""Performs all the tasks that need to be done after the physics simulation step."""
step = Vector3d(self.getStanceFootPos(), self.getSwingFootPos())
step = self.getCharacterFrame().inverseRotate(step)
phi = self.getPhase()
if step.z > 0.7 or (math.fabs(step.x) > 0.45 and phi > 0.5) :
self.setPhase( 1.0 )
if super(DanceController,self).performPostTasks(dt, contactForces):
v = self.getV()
print "step: %3.5f %3.5f %3.5f. Vel: %3.5f %3.5f %3.5f. phi = %f\n" % (step.x, step.y, step.z, v.x, v.y, v.z, phi);
self.setupParameters()
| [
[
8,
0,
0.0143,
0.0238,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0333,
0.0048,
0,
0.66,
0.25,
463,
0,
1,
0,
0,
463,
0,
0
],
[
1,
0,
0.0381,
0.0048,
0,
0.66,
... | [
"'''\nCreated on 2009-11-27\n\n@author: beaudoin\n'''",
"import Core",
"import random, math",
"from MathLib import Point3d, Vector3d",
"class DanceController(Core.IKVMCController):\n \n def __init__(self, character):\n super(DanceController,self).__init__(character)\n \n def typeName(... |
from DanceController import DanceController
from WalkController import WalkController | [
[
1,
0,
0.5,
0.5,
0,
0.66,
0,
456,
0,
1,
0,
0,
456,
0,
0
],
[
1,
0,
1,
0.5,
0,
0.66,
1,
293,
0,
1,
0,
0,
293,
0,
0
]
] | [
"from DanceController import DanceController",
"from WalkController import WalkController"
] |
import Utils
Utils.test() | [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
842,
0,
1,
0,
0,
842,
0,
0
],
[
8,
0,
1,
0.3333,
0,
0.66,
1,
224,
3,
0,
0,
0,
0,
0,
1
]
] | [
"import Utils",
"Utils.test()"
] |
'''
Created on 2009-09-26
@author: beaudoin
'''
import wx, UI
class Animation(object):
# Available speeds on the buttons
_buttonSpeeds = ( '1/16', '1/8', '1/4', '1/2', '1', '2', '4' )
def __init__(self, toolPanel):
"""Adds a tool set for animation information to a toolpanel."""
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Animation" )
app = wx.GetApp()
speedButtonPanel = self._toolSet.addTool( wx.Panel )
animButtonPanel = self._toolSet.addTool( wx.Panel )
self._speedButtons = [ SpeedButton( speedButtonPanel, label = speed, size=(28,28) ) for speed in Animation._buttonSpeeds ]
self._restartButton = wx.BitmapButton( animButtonPanel, bitmap = wx.Bitmap('../data/ui/restart.png', wx.BITMAP_TYPE_PNG) )
self._playButton = wx.BitmapButton( animButtonPanel, bitmap = wx.Bitmap('../data/ui/play.png', wx.BITMAP_TYPE_PNG) )
self._pauseButton = wx.BitmapButton( animButtonPanel, bitmap = wx.Bitmap('../data/ui/pause.png', wx.BITMAP_TYPE_PNG) )
self._stepButton = wx.BitmapButton( animButtonPanel, bitmap = wx.Bitmap('../data/ui/step.png', wx.BITMAP_TYPE_PNG) )
self._stepButton.SetBitmapDisabled( wx.Bitmap('../data/ui/stepDisabled.png', wx.BITMAP_TYPE_PNG) )
for speedButton in self._speedButtons:
speedButton.Bind( wx.EVT_BUTTON, lambda event: app.setSimulationSecondsPerSecond( event.GetEventObject()._labelValue ) )
self._restartButton.Bind( wx.EVT_BUTTON, lambda e: app.restoreActiveSnapshot(False) )
self._playButton.Bind( wx.EVT_BUTTON, lambda e: app.setAnimationRunning(True) )
self._pauseButton.Bind( wx.EVT_BUTTON, lambda e: app.setAnimationRunning(False) )
self._stepButton.Bind( wx.EVT_BUTTON, lambda e: app.simulationFrame() )
hBoxSpeedButton = wx.BoxSizer( wx.HORIZONTAL )
hBoxSpeedButton.AddStretchSpacer()
for speedButton in self._speedButtons:
hBoxSpeedButton.Add( speedButton,0, wx.EXPAND )
hBoxSpeedButton.AddStretchSpacer()
speedButtonPanel.SetSizerAndFit(hBoxSpeedButton)
self._hBoxAnimButtons = wx.BoxSizer( wx.HORIZONTAL )
self._hBoxAnimButtons.AddStretchSpacer()
self._hBoxAnimButtons.Add(self._restartButton)
self._hBoxAnimButtons.Add(self._playButton)
self._hBoxAnimButtons.Add(self._pauseButton)
self._hBoxAnimButtons.Add(self._stepButton)
self._hBoxAnimButtons.AddStretchSpacer()
animButtonPanel.SetSizerAndFit(self._hBoxAnimButtons)
# Add this as an observer
app.addAnimationObserver(self)
# Initial update
self.update()
def update(self, data = None):
"""Called whenever the animation is updated in the application."""
app = wx.GetApp()
simulationSecondsPerSeconds = app.getSimulationSecondsPerSecond()
for speedButton in self._speedButtons:
speedButton.Enable( simulationSecondsPerSeconds != speedButton._labelValue )
self._hBoxAnimButtons.Show( self._playButton, not app.isAnimationRunning() )
self._hBoxAnimButtons.Show( self._pauseButton, app.isAnimationRunning() )
self._stepButton.Enable( not app.isAnimationRunning() )
self._hBoxAnimButtons.Layout()
class SpeedButton(wx.Button):
"""A private internal class that keeps a button together with its numeric speed"""
def __init__(self, parent, id = wx.ID_ANY, label = '', pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0,
validator = wx.DefaultValidator, name='' ):
super(SpeedButton, self).__init__(parent, id, label, pos, size, style, validator, name)
self._labelValue = eval(label+".0") | [
[
8,
0,
0.0366,
0.061,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0854,
0.0122,
0,
0.66,
0.3333,
666,
0,
2,
0,
0,
666,
0,
0
],
[
3,
0,
0.4817,
0.7561,
0,
0.66,... | [
"'''\nCreated on 2009-09-26\n\n@author: beaudoin\n'''",
"import wx, UI",
"class Animation(object):\n \n # Available speeds on the buttons\n _buttonSpeeds = ( '1/16', '1/8', '1/4', '1/2', '1', '2', '4' )\n\n def __init__(self, toolPanel):\n \"\"\"Adds a tool set for animation information to a ... |
'''
Created on 2009-10-02
@author: beaudoin
'''
import wx, UI, PyUtils
class SnapshotTree(object):
def __init__(self, toolPanel):
"""Adds a tool set for animation information to a toolpanel."""
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Snapshots", resizable = True )
app = wx.GetApp()
buttonPanel = self._toolSet.addTool( wx.Panel )
self._takeSnapshotButton = wx.BitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/takeSnapshotButton.png', wx.BITMAP_TYPE_PNG) )
self._takeSnapshotButton.SetBitmapDisabled( wx.Bitmap('../data/ui/takeSnapshotButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._dontRestoreControllerParamsButton = UI.Ext.ToggleBitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/restoreControllerParams.png', wx.BITMAP_TYPE_PNG) )
self._dontRestoreControllerParamsButton.SetBitmapSelected( wx.Bitmap('../data/ui/dontRestoreControllerParams.png', wx.BITMAP_TYPE_PNG) )
self._previousButton = wx.BitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/previousSnapshotButton.png', wx.BITMAP_TYPE_PNG) )
self._previousButton.SetBitmapDisabled( wx.Bitmap('../data/ui/previousSnapshotButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._restoreButton = wx.BitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/restoreSnapshotButton.png', wx.BITMAP_TYPE_PNG) )
self._restoreButton.SetBitmapDisabled( wx.Bitmap('../data/ui/restoreSnapshotButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._nextButton = wx.BitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/nextSnapshotButton.png', wx.BITMAP_TYPE_PNG) )
self._nextButton.SetBitmapDisabled( wx.Bitmap('../data/ui/nextSnapshotButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._takeSnapshotButton.Bind( wx.EVT_BUTTON, lambda e: app.takeSnapshot() )
self._previousButton.Bind( wx.EVT_BUTTON, lambda e: app.previousSnapshot(self.restoreControllerParams()) )
self._restoreButton.Bind( wx.EVT_BUTTON, lambda e: app.restoreActiveSnapshot(self.restoreControllerParams()) )
self._nextButton.Bind( wx.EVT_BUTTON, lambda e: app.nextSnapshot(self.restoreControllerParams()) )
self._hBoxButtons = wx.BoxSizer( wx.HORIZONTAL )
self._hBoxButtons.Add(self._takeSnapshotButton)
self._hBoxButtons.AddStretchSpacer(1)
self._hBoxButtons.Add(self._dontRestoreControllerParamsButton)
self._hBoxButtons.Add(self._previousButton)
self._hBoxButtons.Add(self._restoreButton)
self._hBoxButtons.Add(self._nextButton)
buttonPanel.SetSizerAndFit(self._hBoxButtons)
self._infoTree = self._toolSet.addTool( UI.InfoTreeBasic, 1, object = app.getSnapshotTree(), desiredHeight = 200, autoVisible = True, onUpdate = self.update )
self._infoTree.Bind( wx.EVT_TREE_ITEM_ACTIVATED , self.selectSnapshot )
self._activeTreeItemId = None
#
# Public methods
#
def restoreControllerParams(self):
"""Return true if we should restore the controller parameters when moving around, false if not."""
return not self._dontRestoreControllerParamsButton.IsSelected()
#
# Callbacks
#
def selectSnapshot(self, event):
"""Select the snapshot double-clicked at."""
item = event.GetItem()
try:
nodeData = self._infoTree.GetItemPyData(item)
snapshot = nodeData.getObject()
snapshot.restore(self.restoreControllerParams())
except AttributeError:
event.Skip()
def update(self, data = None):
"""Called whenever the tree is updated."""
try:
tree = self._infoTree
rootItem = tree.GetRootItem()
nodeData = tree.GetItemPyData( rootItem )
snapshot = nodeData.getObject().getCurrentSnapshot()
except AttributeError: return
if self._activeTreeItemId != None :
currentSnapshot = tree.GetItemPyData( self._activeTreeItemId )
if PyUtils.sameObject(currentSnapshot, snapshot) : return
tree.SetItemBold( self._activeTreeItemId, False )
# Look for the new item
activeList = [tree.GetFirstChild(rootItem)[0]]
while len(activeList) > 0 :
treeItemId = activeList.pop()
if not treeItemId.IsOk(): continue
object = tree.GetItemPyData( treeItemId ).getObject()
if PyUtils.sameObject(snapshot, object) :
self._activeTreeItemId = treeItemId
tree.SetItemBold( treeItemId, True )
return
activeList.append( tree.GetFirstChild(treeItemId)[0] )
activeList.append( tree.GetNextSibling(treeItemId) )
| [
[
8,
0,
0.0309,
0.0515,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0722,
0.0103,
0,
0.66,
0.5,
666,
0,
3,
0,
0,
666,
0,
0
],
[
3,
0,
0.5412,
0.9072,
0,
0.66,
... | [
"'''\nCreated on 2009-10-02\n\n@author: beaudoin\n'''",
"import wx, UI, PyUtils",
"class SnapshotTree(object):\n \n def __init__(self, toolPanel):\n \"\"\"Adds a tool set for animation information to a toolpanel.\"\"\"\n self._toolPanel = toolPanel\n self._toolSet = toolPanel.createTo... |
'''
Created on 2009-09-26
@author: beaudoin
'''
import UI, wx, math
class _OptionData(object):
def __init__(self, checkBox, getter, setter):
self.checkBox = checkBox
self.getter = getter
self.setter = setter
self.update()
def update(self):
self.checkBox.SetValue( self.getter() )
def set(self):
self.setter(self.checkBox.IsChecked())
class _SliderData(object):
def __init__(self, slider, valueWidget, getter, setter, min, max):
self.slider = slider
self.valueWidget = valueWidget
self.getter = getter
self.setter = setter
self.min = min
self.max = max
self.update()
def update(self):
value = self.getter()
if value < self.min : value = self.min
if value > self.max : value = self.max
convertedValue = int((value-self.min)/float(self.max-self.min) * (self.slider.GetMax()-self.slider.GetMin()) + self.slider.GetMin())
self.slider.SetValue(convertedValue)
self.valueWidget.SetLabel( "%.2f" % value )
def set(self):
value = self.getSliderValue()
self.setter(value)
self.valueWidget.SetLabel( "%.2f" % value )
def getSliderValue(self):
convertedValue = self.slider.GetValue()
return float((convertedValue-self.slider.GetMin())/float(self.slider.GetMax()-self.slider.GetMin()) * (self.max-self.min) + self.min)
class ToolsetBase(object):
def __init__(self):
"""Abstract base class for toolsets that can contain options.
The subclass must contain a self._toolSet member."""
self._dataList = []
def update(self, data = None):
"""Called whenever the animation is updated in the application."""
for data in self._dataList:
data.update()
def addOption(self, label, getter, setter):
"""Adds a new option to the panel, with its getter and setter."""
checkBox = self._toolSet.addTool( wx.CheckBox, label = label, size=(-1,22) )
data = _OptionData(checkBox, getter, setter)
checkBox.Bind( wx.EVT_CHECKBOX, lambda e: data.set() )
self._dataList.append( data )
return checkBox, data
def addSlider(self, label, min, max, step, getter, setter, labelWidth = 75, valueWidth = 40):
"""Adds a new horizontal slider to the panel, with its getter and setter."""
toolPanel = self._toolSet.addTool( wx.Panel )
sizer = wx.BoxSizer( wx.HORIZONTAL )
labelWidget = wx.StaticText( toolPanel, label = label, size=(labelWidth,-1) )
slider = wx.Slider( toolPanel, size=(-1,22), style = wx.SL_HORIZONTAL, minValue = 0, maxValue = math.ceil(float(max-min)/float(step)) )
slider.SetLineSize( step )
valueWidget = wx.StaticText( toolPanel, label = "0", size=(valueWidth,-1) )
sizer.Add(labelWidget, 0, wx.ALIGN_CENTER)
sizer.Add(slider, 1, wx.EXPAND)
sizer.Add(valueWidget, 0, wx.ALIGN_CENTER)
toolPanel.SetSizerAndFit( sizer )
data = _SliderData(slider, valueWidget, getter, setter, min, max)
slider.Bind( wx.EVT_SCROLL, lambda e: data.set() )
self._dataList.append( data )
return slider, data
def addButton(self, label, action):
"""Adds a new option button the panel, with its action (a parameter-less function)."""
button = self._toolSet.addTool( wx.Button, label = label, flag=0 )
button.Bind(wx.EVT_BUTTON, lambda event: action() )
return button
| [
[
8,
0,
0.0291,
0.0485,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.068,
0.0097,
0,
0.66,
0.25,
587,
0,
3,
0,
0,
587,
0,
0
],
[
3,
0,
0.1456,
0.1262,
0,
0.66,
... | [
"'''\nCreated on 2009-09-26\n\n@author: beaudoin\n'''",
"import UI, wx, math",
"class _OptionData(object):\n \n def __init__(self, checkBox, getter, setter):\n self.checkBox = checkBox\n self.getter = getter\n self.setter = setter\n self.update()",
" def __init__(self, che... |
'''
Created on 2009-09-26
@author: beaudoin
'''
import UI, wx
from ToolsetBase import ToolsetBase
class Options(ToolsetBase):
def __init__(self, toolPanel):
"""Adds a tool set for various options information to a toolpanel."""
super(Options, self).__init__()
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Options" )
app = wx.GetApp()
self.addOption( "Show collision volumes", app.getDrawCollisionVolumes, app.drawCollisionVolumes )
self.addOption( "Capture screenshots", app.getCaptureScreenShots, app.captureScreenShots )
self.addOption( "Kinematic motion", app.getKinematicMotion, app.setKinematicMotion)
# Add this as an observer
app.addOptionsObserver(self)
# Initial update
self.update() | [
[
8,
0,
0.1,
0.1667,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2333,
0.0333,
0,
0.66,
0.3333,
587,
0,
2,
0,
0,
587,
0,
0
],
[
1,
0,
0.2667,
0.0333,
0,
0.66,
... | [
"'''\nCreated on 2009-09-26\n\n@author: beaudoin\n'''",
"import UI, wx",
"from ToolsetBase import ToolsetBase",
"class Options(ToolsetBase):\n \n def __init__(self, toolPanel):\n \"\"\"Adds a tool set for various options information to a toolpanel.\"\"\"\n \n super(Options, self).__... |
'''
Created on 2009-09-26
@author: beaudoin
'''
import UI, wx
from ToolsetBase import ToolsetBase
class Camera(ToolsetBase):
def __init__(self, toolPanel):
"""Adds a tool set for camera information to a toolpanel."""
super(Camera, self).__init__()
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Camera" )
app = wx.GetApp()
self.addOption( "Follow character", app.doesCameraFollowCharacter, app.setCameraFollowCharacter )
self.addOption( "Auto orbit", app.doesCameraAutoOrbit, app.setCameraAutoOrbit )
# Add this as an observer
app.addCameraObserver(self)
# Initial update
self.update()
| [
[
8,
0,
0.1034,
0.1724,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2414,
0.0345,
0,
0.66,
0.3333,
587,
0,
2,
0,
0,
587,
0,
0
],
[
1,
0,
0.2759,
0.0345,
0,
0.66... | [
"'''\nCreated on 2009-09-26\n\n@author: beaudoin\n'''",
"import UI, wx",
"from ToolsetBase import ToolsetBase",
"class Camera(ToolsetBase):\n \n def __init__(self, toolPanel):\n \"\"\"Adds a tool set for camera information to a toolpanel.\"\"\"\n \n super(Camera, self).__init__()\n ... |
'''
Created on 2009-09-26
@author: beaudoin
'''
import UI, wx, PyUtils, os, Core
class ControllerTree(object):
"""A toolset that can be used to display an editable tree of the loaded controllers."""
def __init__(self, toolPanel):
"""Adds a tool set that display a tree of controllers to a toolpanel."""
self._toolPanel = toolPanel
toolSet = toolPanel.createToolSet( "Controller Tree", resizable = True )
self._toolSet = toolSet
self._buttonToolbar = toolSet.addTool( ButtonToolbar, 0 )
self._infoTree = toolSet.addTool( UI.InfoTree, 1, object = wx.GetApp().getControllerList(), desiredHeight = 450 )
self._infoTree.Bind( wx.EVT_TREE_SEL_CHANGED, self._buttonToolbar.updateButtons )
self._buttonToolbar.setTree( self._infoTree.getTree() )
#
# Callbacks
#
def updateButtons(self, event):
_updateButtonState
class ButtonToolbar(wx.Panel):
"""Private class that provide a toolbar for actions available on a controller tree."""
def __init__(self,*args, **kwargs):
super(ButtonToolbar,self).__init__(*args,**kwargs)
self._replaceCurvesButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/replaceCurvesButton.png', wx.BITMAP_TYPE_PNG) )
self._replaceCurvesButton.SetBitmapDisabled( wx.Bitmap('../data/ui/replaceCurvesButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._addCurvesButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/addCurvesButton.png', wx.BITMAP_TYPE_PNG) )
self._addCurvesButton.SetBitmapDisabled( wx.Bitmap('../data/ui/addCurvesButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._recenterButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/recenter.png', wx.BITMAP_TYPE_PNG) )
self._recenterButton.SetBitmapDisabled( wx.Bitmap('../data/ui/recenterDisabled.png', wx.BITMAP_TYPE_PNG) )
self._stepUntilBreakButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/stepUntilBreak.png', wx.BITMAP_TYPE_PNG) )
self._stepUntilBreakButton.SetBitmapDisabled( wx.Bitmap('../data/ui/stepUntilBreakDisabled.png', wx.BITMAP_TYPE_PNG) )
self._saveButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/save.png', wx.BITMAP_TYPE_PNG) )
self._saveButton.SetBitmapDisabled( wx.Bitmap('../data/ui/saveDisabled.png', wx.BITMAP_TYPE_PNG) )
self._saveCharacterStateButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/saveCharacterState.png', wx.BITMAP_TYPE_PNG) )
self._saveCharacterStateButton.SetBitmapDisabled( wx.Bitmap('../data/ui/saveCharacterStateDisabled.png', wx.BITMAP_TYPE_PNG) )
# self._addButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/plusButton.png', wx.BITMAP_TYPE_PNG) )
# self._addButton.SetBitmapDisabled( wx.Bitmap('../data/ui/plusButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
# self._removeButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/minusButton.png', wx.BITMAP_TYPE_PNG) )
# self._removeButton.SetBitmapDisabled( wx.Bitmap('../data/ui/minusButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
# self._upButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/upButton.png', wx.BITMAP_TYPE_PNG) )
# self._upButton.SetBitmapDisabled( wx.Bitmap('../data/ui/upButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
# self._downButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/downButton.png', wx.BITMAP_TYPE_PNG) )
# self._downButton.SetBitmapDisabled( wx.Bitmap('../data/ui/downButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._hBoxButtonBar = wx.BoxSizer(wx.HORIZONTAL)
self._hBoxButtonBar.Add( self._replaceCurvesButton, 0, wx.EXPAND )
self._hBoxButtonBar.Add( self._addCurvesButton, 0, wx.EXPAND )
self._hBoxButtonBar.Add( self._recenterButton, 0, wx.EXPAND )
self._hBoxButtonBar.Add( self._stepUntilBreakButton, 0, wx.EXPAND )
self._hBoxButtonBar.AddStretchSpacer()
self._hBoxButtonBar.Add( self._saveButton, 0, wx.EXPAND )
self._hBoxButtonBar.Add( self._saveCharacterStateButton, 0, wx.EXPAND )
# self._hBoxButtonBar.Add( self._addButton, 0, wx.EXPAND )
# self._hBoxButtonBar.Add( self._removeButton, 0, wx.EXPAND )
# self._hBoxButtonBar.Add( self._upButton, 0, wx.EXPAND )
# self._hBoxButtonBar.Add( self._downButton, 0, wx.EXPAND )
self.SetSizer( self._hBoxButtonBar )
self._replaceCurvesButton.Bind( wx.EVT_BUTTON, self.replaceCurves )
self._addCurvesButton.Bind( wx.EVT_BUTTON, self.addCurves )
self._recenterButton.Bind( wx.EVT_BUTTON, self.recenter )
self._stepUntilBreakButton.Bind( wx.EVT_BUTTON, self.stepUntilBreak )
self._saveButton.Bind( wx.EVT_BUTTON, self.saveController )
self._saveCharacterStateButton.Bind( wx.EVT_BUTTON, self.saveCharacterState )
self._tree = None
self._saveNumber = 0
self._dirName = os.path.join( 'Data', 'Temp' )
self._lastSave = (None,None,None) # a triplet: controller, saveNumberForController, saveNumberForCharacterState
#
# Public methods
#
def setTree(self, tree):
"""Sets the tree attached to this button toolbar."""
self._tree = tree
self.updateButtons()
#
# Callbacks
#
def updateButtons(self, event = None):
"""Adjust button states based on the current selection"""
treeItemId = self._tree.GetSelection()
operations = save = plus = minus = up = down = False
if treeItemId.IsOk():
element = self._tree.GetItemPyData( treeItemId )
operations = save = True
self._replaceCurvesButton.Enable(operations)
self._addCurvesButton.Enable(operations)
self._recenterButton.Enable(operations)
self._stepUntilBreakButton.Enable(operations)
self._saveButton.Enable(save)
self._saveCharacterStateButton.Enable(save)
# self._addButton.Enable(plus)
# self._removeButton.Enable(minus)
# self._upButton.Enable(up)
# self._downButton.Enable(down)
def replaceCurves(self, event = None):
"""Replace all the curves with the selected ones."""
app = wx.GetApp()
app.clearCurves()
self.addCurves( event )
def addCurves(self, event = None):
"""Add all the curves under a node to the application."""
app = wx.GetApp()
treeItemId = self._tree.GetSelection()
if not treeItemId.IsOk(): return
# Name that node by going back to the top of the tree
nameStack = []
currTreeItemId = treeItemId
rootTreeItemId = self._tree.GetRootItem()
while currTreeItemId.IsOk() and currTreeItemId != rootTreeItemId:
nameStack.insert(0, self._tree.GetItemText(currTreeItemId))
currTreeItemId = self._tree.GetItemParent(currTreeItemId)
# Now, recursively go down the tree from the current node
curveList = app.getCurveList()
curveList.beginBatchChanges()
try: self._addCurves( treeItemId, nameStack )
finally: curveList.endBatchChanges()
def saveController(self, event = None):
"""Save the currently selected controller"""
controller = self._getSelectedController()
if controller is None : return
saveNumber = self._saveNumber
if PyUtils.sameObject( self._lastSave[0], controller ) :
if self._lastSave[2] is not None :
saveNumber = self._lastSave[2]
controllerName = controller.getName()
dialogTitle = "Save %s Controller" % controllerName
fileName = "%s_%d.py" % (controllerName, saveNumber)
dialog = wx.FileDialog(self, dialogTitle, self._dirName, fileName, "*.py", wx.SAVE | wx.OVERWRITE_PROMPT )
dialog.CenterOnScreen()
if dialog.ShowModal() == wx.ID_OK:
if saveNumber != self._saveNumber:
self._lastSave = (None, None, None)
else:
self._lastSave = (controller, self._saveNumber, None)
self._saveNumber += 1
fileName=dialog.GetFilename()
self._dirName=dialog.GetDirectory()
pathName = os.path.join(self._dirName,fileName)
file = open(pathName,'w')
file.write( "from App.Proxys import *\n\ndata = %s" % PyUtils.fancify( PyUtils.serialize(controller)) )
file.close()
dialog.Destroy()
def recenter(self, event = None):
"""Recenter the character attached to the currently selected controller"""
controller = self._getSelectedController()
if controller is None : return
app = wx.GetApp()
app.recenterCharacter( controller.getCharacter() )
def stepUntilBreak(self, event = None):
"""Steps the selected controller until its phase resets to zero"""
controller = self._getSelectedController()
if controller is None : return
app = wx.GetApp()
app.advanceAnimationUntilControllerEnds( controller )
def saveCharacterState(self, event = None):
"""Saves the selected character state"""
controller = self._getSelectedController()
if controller is None : return
app = wx.GetApp()
character = controller.getCharacter()
saveNumber = self._saveNumber
if PyUtils.sameObject( self._lastSave[0], controller ) :
if self._lastSave[1] is not None :
saveNumber = self._lastSave[1]
controllerName = controller.getName()
dialogTitle = "Save Character State for %s" % controllerName
fileName = "%sState_%d.rs" % (controllerName, saveNumber)
dialog = wx.FileDialog(self, dialogTitle, self._dirName, fileName, "*.rs", wx.SAVE | wx.OVERWRITE_PROMPT )
dialog.CenterOnScreen()
if dialog.ShowModal() == wx.ID_OK:
if saveNumber != self._saveNumber:
self._lastSave = (None, None, None)
else:
self._lastSave = (controller, None, self._saveNumber)
self._saveNumber += 1
fileName=dialog.GetFilename()
self._dirName=dialog.GetDirectory()
pathName = os.path.join(self._dirName,fileName)
stateArray = Core.ReducedCharacterStateArray()
if controller.getStance() == Core.RIGHT_STANCE:
character.getReverseStanceState(stateArray)
else:
character.getState(stateArray)
character.saveReducedStateToFile( str(pathName), stateArray )
dialog.Destroy()
#
# Private methods
#
def _getSelectedController(self):
"""Go up to the root to find the selected controller. None if no controller was selected."""
treeItemId = self._tree.GetSelection()
rootTreeItemId = self._tree.GetRootItem()
controller = None
while treeItemId.IsOk() and treeItemId != rootTreeItemId:
try: controller = self._tree.GetItemPyData(treeItemId).getObject()
except AttributeError: controller = None
treeItemId = self._tree.GetItemParent(treeItemId)
if controller is None or not isinstance(controller,Core.SimBiController):
return None
return controller
def _addCurves(self, treeItemId, nameStack):
"""PRIVATE. Recursively add curves under this treeItemId."""
from App.Proxys import Member
app = wx.GetApp()
controller = self._getSelectedController()
phiPtr = controller.getPhiPtr()
nodeData = self._tree.GetItemPyData( treeItemId )
if nodeData is None : return
try:
# Assume the tree node contains an object
object = nodeData.getObject()
except AttributeError:
object = None
if object is not None:
proxyObject = PyUtils.wrap(object, recursive = False)
for i in range( proxyObject.getMemberCount() ):
value, member = proxyObject.getValueAndInfo(i)
if value is None: continue
if isinstance( member, Member.Trajectory1d ):
name = " : ".join(nameStack[1:])
if member.name != "baseTrajectory" :
name += " : " + member.fancyName
app.addCurve( name, value, phiPtr )
# Recurse on the child nodes
currTreeItemId, cookie = self._tree.GetFirstChild( treeItemId )
while currTreeItemId.IsOk():
newNameStack = nameStack[:]
newNameStack.append( self._tree.GetItemText(currTreeItemId) )
self._addCurves( currTreeItemId, newNameStack )
currTreeItemId, cookie = self._tree.GetNextChild( treeItemId, cookie )
| [
[
8,
0,
0.0106,
0.0177,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0247,
0.0035,
0,
0.66,
0.3333,
587,
0,
5,
0,
0,
587,
0,
0
],
[
3,
0,
0.0671,
0.0742,
0,
0.66... | [
"'''\nCreated on 2009-09-26\n\n@author: beaudoin\n'''",
"import UI, wx, PyUtils, os, Core",
"class ControllerTree(object):\n \"\"\"A toolset that can be used to display an editable tree of the loaded controllers.\"\"\"\n \n def __init__(self, toolPanel):\n \"\"\"Adds a tool set that display a tr... |
from ToolsetBase import ToolsetBase
from ControllerTree import ControllerTree
from Animation import Animation
from Options import Options
from Camera import Camera
from SnapshotTree import SnapshotTree | [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
177,
0,
1,
0,
0,
177,
0,
0
],
[
1,
0,
0.3333,
0.1667,
0,
0.66,
0.2,
389,
0,
1,
0,
0,
389,
0,
0
],
[
1,
0,
0.5,
0.1667,
0,
0.66,
... | [
"from ToolsetBase import ToolsetBase",
"from ControllerTree import ControllerTree",
"from Animation import Animation",
"from Options import Options",
"from Camera import Camera",
"from SnapshotTree import SnapshotTree"
] |
'''
Created on 2009-08-30
@author: beaudoin
Allows creation of a vertical collection of collapsible tool sets
'''
import wx
class ToolSet(wx.Panel):
"""A simple class that maintain tools and that can be hidden or showed."""
_triUp = None
_triDown = None
def __init__(self, parent, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.TAB_TRAVERSAL,
name='', resizable = False ):
super(ToolSet, self).__init__(parent, id, pos, size, style, name)
# Load the bitmaps if needed
if ToolSet._triUp is None :
ToolSet._triRight = wx.Bitmap('../data/ui/triRight.png', wx.BITMAP_TYPE_PNG)
ToolSet._triDown = wx.Bitmap('../data/ui/triDown.png', wx.BITMAP_TYPE_PNG)
# Setup a link to the parent, to refresh it when tool sets open or close
self._parentVBox = parent._vBox
# Setup the tool set title
self._title = wx.Panel(self)
self._title.SetBackgroundColour( (180,180,180) )
titleLabel = wx.StaticText(self._title,label=name)
self._titleBitmap = wx.StaticBitmap(self._title, bitmap = ToolSet._triDown )
titleHBox = wx.BoxSizer(wx.HORIZONTAL)
titleHBox.Add( self._titleBitmap, 0, wx.CENTER | wx.ALL, 3 )
titleHBox.Add( titleLabel, 1, wx.ALL, 3 )
self._title.SetSizer( titleHBox )
# A 1 px panel for spacing
spacing = wx.Panel(self, size=(-1,1) )
spacing.SetBackgroundColour( (150,150,150) )
self._vBox = wx.BoxSizer(wx.VERTICAL)
self._vBox.Add( self._title, 0, wx.EXPAND )
self._vBox.Add( spacing, 0, wx.EXPAND )
# Create the panel
# If the tool set is resizable, create the panel in a sash window
if resizable:
# Setup the main tool set panel
self._sashWindow = wx.SashWindow(self)
self._sashWindow.SetSashVisible( wx.SASH_BOTTOM, True )
self._vBox.Add( self._sashWindow, 0, wx.EXPAND )
self._panel = wx.Panel(self._sashWindow)
self._vBoxSashWindow = wx.BoxSizer(wx.VERTICAL)
self._vBoxSashWindow.Add( self._panel, 0, wx.EXPAND )
self._sashWindow.SetSizer( self._vBoxSashWindow )
self._sashWindow.Bind( wx.EVT_SASH_DRAGGED, self.toolSetResize )
else:
# Setup the main tool set panel
self._panel = wx.Panel(self)
self._vBox.Add( self._panel, 0, wx.EXPAND )
# Create the sizer for the panel
self._panelVBox = wx.BoxSizer(wx.VERTICAL)
self._panel.SetSizer( self._panelVBox )
self.SetSizer( self._vBox )
# Setup initial state
self._opened = True
# Bind events
self._title.Bind( wx.EVT_LEFT_DCLICK, self.processOpenClose )
titleLabel.Bind( wx.EVT_LEFT_DCLICK, self.processOpenClose )
self._titleBitmap.Bind( wx.EVT_LEFT_DOWN, self.processOpenClose )
self._titleBitmap.Bind( wx.EVT_LEFT_DCLICK, self.processOpenClose )
#
# Event handlers
def processOpenClose( self, event ):
"""Change the state from open to close and vice-versa"""
self.setOpen( not self._opened )
def toolSetResize( self, event ):
"""Change the size of the tool set"""
if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE :
return
self._panelVBox.SetMinSize( (-1, event.GetDragRect().height) )
self.refreshAll()
#
# public methods
def setOpen( self, opened ):
"""Indicates whether this tool set should be open or not"""
if self._opened == opened :
return
self._opened = opened;
try:
self._sashWindow.Show( opened )
except AttributeError:
self._panel.Show( opened )
if opened :
self._titleBitmap.SetBitmap( ToolSet._triDown )
else :
self._titleBitmap.SetBitmap( ToolSet._triRight )
self._parentVBox.Layout()
self.GetParent().FitInside()
self.GetParent().Refresh()
def addTool(self, widgetClass, proportion=0, flag=wx.EXPAND, border=0, desiredHeight = 0, **argkw ):
"""Adds the specified widget as a tool in the tool set
widgetCreator is a standard wxWidget class, such as wx.panel,
you can pass any wxWidget creation argument you want in argkw.
The method returns the newly created widget."""
widget = widgetClass( self._panel, **argkw )
self._panelVBox.Add( widget, proportion, flag, border )
minSize = self._panelVBox.GetMinSizeTuple()
self._panelVBox.SetMinSize((minSize[0],desiredHeight))
self.refreshAll()
return widget
def refreshAll(self):
"""Refresh the content of the tool set"""
self._panel.Fit()
try:
self._sashWindow.Fit()
except AttributeError: pass
self.Fit()
self.GetParent().Layout()
class ToolPanel(wx.ScrolledWindow):
"""A simple class that maintain tool sets and that can be scrolled."""
def __init__(self, parent, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style= wx.HSCROLL | wx.VSCROLL,
name='toolPanel' ):
super(ToolPanel, self).__init__(parent, id, pos, size, style, name)
self._vBox = wx.BoxSizer(wx.VERTICAL)
self.SetSizer( self._vBox )
# Enable vertical scrolling by 10 pixel increments
self.SetScrollRate(0,10)
def createToolSet(self, toolSetName, resizable = False):
"""Creates a new tool set and adds it to the ToolPanel.
The user should then add tools to the tool set in any way he wishes
"""
toolSet = ToolSet(self, name=toolSetName, resizable = resizable )
self._vBox.Add( toolSet, 0, wx.EXPAND )
self.Layout()
return toolSet
| [
[
8,
0,
0.0241,
0.0422,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0542,
0.006,
0,
0.66,
0.3333,
666,
0,
1,
0,
0,
666,
0,
0
],
[
3,
0,
0.4518,
0.7771,
0,
0.66,... | [
"'''\nCreated on 2009-08-30\n\n@author: beaudoin\n\nAllows creation of a vertical collection of collapsible tool sets\n'''",
"import wx",
"class ToolSet(wx.Panel):\n \"\"\"A simple class that maintain tools and that can be hidden or showed.\"\"\"\n _triUp = None\n _triDown = None \n \n d... |
'''
Created on 2009-09-30
@author: beaudoin
'''
import wx, GLUtils, PyUtils
class CurveEditorCollection(GLUtils.GLUIContainer):
"""A collection of curve editor that observes the curve editors of the application."""
def __init__( self, parent, x=0, y=0, width=0, height=0, minWidth=-1, minHeight=-1 ):
super(CurveEditorCollection,self).__init__(parent,x,y,width,height,minWidth,minHeight)
sizer = GLUtils.GLUIBoxSizer( GLUtils.GLUI_HORIZONTAL )
self.setSizer(sizer)
app = wx.GetApp()
self._appCurveList = app.getCurveList()
self._appCurveList.addObserver(self)
self._curveEditorList = []
def _removeCurveEditors(self, start=None, end=None):
"""Private. This method removes curve editors from the curve editor list.
Objects removed are in the range [start,end).
Runs from object 0 when start==None and until the end when end==None."""
if start is None : start = 0
if end is None : end = len( self._curveEditorList )
for curveEditor in self._curveEditorList[start:end]:
self.detachChild( curveEditor )
del self._curveEditorList[start:end]
def _insertCurveEditor(self, index, curve):
"""Private. This method inserts at the specified index a curve editor that wraps the specified App.Curve."""
curveEditor = GLUtils.GLUICurveEditor( self )
curveEditor.setTrajectory( curve.getTrajectory1d() )
curveEditor.setCurrTime( curve.getPhiPtr() )
curveEditor.setTitle( curve.getName() )
curveEditor.setMinSize(200,200)
self.getSizer().add( curveEditor )
self._curveEditorList.insert(index, curveEditor)
def getTrajectory(self, index):
"""Return the trajectory attached to the curve editor number 'index'."""
return self._curveEditorList[index].getTrajectory()
def update(self, data = None):
"""Called whenever the curve list is updated. Make sure the curve editor list match the application curve list."""
count = self._appCurveList.getCount()
for i in range(count):
inCurve = self._appCurveList.get(i)
inTrajectory1d = inCurve.getTrajectory1d()
try:
outTrajectory1d = self.getTrajectory(i)
areSameObject = PyUtils.sameObject(inTrajectory1d, outTrajectory1d)
except IndexError:
outTrajectory1d = None
areSameObject = False
if not areSameObject:
# Need to delete or insert
# First, check how many curves we should delete
delete = 1
try:
while not PyUtils.sameObject( inTrajectory1d, self.getTrajectory(i+delete) ) :
delete += 1
except IndexError:
delete = 0
if delete > 0 :
# Delete the specified controllers
self._removeCurveEditors(i,i+delete)
else :
# Insert the specified controller
self._insertCurveEditor(i, inCurve)
# Delete any remaining controllers
self._removeCurveEditors(count)
self.getParent().layout()
| [
[
8,
0,
0.0361,
0.0602,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0964,
0.012,
0,
0.66,
0.5,
666,
0,
3,
0,
0,
666,
0,
0
],
[
3,
0,
0.5602,
0.8916,
0,
0.66,
... | [
"'''\nCreated on 2009-09-30\n\n@author: beaudoin\n'''",
"import wx, GLUtils, PyUtils",
"class CurveEditorCollection(GLUtils.GLUIContainer):\n \"\"\"A collection of curve editor that observes the curve editors of the application.\"\"\"\n \n def __init__( self, parent, x=0, y=0, width=0, height=0, minWid... |
'''
Created on 2009-12-02
@author: beaudoin
'''
import GLUtils
from OpenGL.GL import *
class ControlPoint(object):
"""Base class for any type of control point.
Derived classes must implement:
getPos() returns the x, y position of the control point."""
def __init__( self ):
super(ControlPoint,self).__init__()
self._previousMousePos = None
def draw(self):
xPos, yPos = self.getPos()
glVertex2d( xPos, yPos )
def setPreviousMousePos(self, pos ):
self._previousMousePos = pos
def unsetPreviousMousePos(self):
self._previousMousePos = None
def moveToPos(self, pos):
if self._previousMousePos is None :
self._previousMousePos = pos
self.setPos(pos)
self._previousMousePos = pos
class WindowWithControlPoints(GLUtils.GLUIWindow):
"""
Base class for a simple GL window that can contain various control points.
Derived class should not perform their drawing in draw() but instead in
drawContent()
The control points will be drawn on top of that.
At that point, the drawing area will be configured to the specified values (minPosY, maxPosY
"""
def __init__( self, parent, x=0, y=0, width=0, height=0, minWidth=-1, minHeight=-1, boundsX = (-1,1), boundsY = (-1,1), forceAspectRatio = None ):
"""
Initializes a window that can have control points.
boundsX indicate the (min, max) X values to display
boundsY indicate the (min, max) Y values to display
forceAspectRatio can be 'x', 'y' or None.
If 'x', the boundsX will be modified to enforce conservation of aspect ratio
If 'y', the boundsY will be modified to enforce conservation of aspect ratio
If None, aspect ratio is not adjusted by the window
See GLUIWindow for other parameters.
"""
super(WindowWithControlPoints,self).__init__(parent,x,y,width,height, minWidth, minHeight)
self._controlPoints = []
self._controlPointHeld = None
self._holdPos = (-1,-1)
self._boundsX = boundsX
self._boundsY = boundsY
self._width = float(boundsX[1] - boundsX[0])
self._height = float(boundsY[1] - boundsY[0])
if forceAspectRatio is not None:
if forceAspectRatio == 'x' :
self._width = self._height * float(minWidth) / float(minHeight)
midX = (boundsX[0] + boundsX[1])/2.0
self._boundsX = (midX - self._width/2.0, midX + self._width/2.0)
elif forceAspectRatio == 'y' :
self._height = width * float(minHeight) / float(minWidth)
midY = (boundsY[0] + boundsY[1])/2.0
self._boundsY = (midY - self._height/2.0, midY + self._height/2.0)
else :
raise ValueError( "forceAspectRation must be 'x', 'y' or None" )
def draw(self):
"""Draws the content of the window by calling self.drawContent(), then the control points."""
# Save projection matrix and sets it to a simple orthogonal projection
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
glOrtho(self._boundsX[0], self._boundsX[1], self._boundsY[0], self._boundsY[1],-1,1)
self.drawContent()
# Draw control points
try:
glPointSize( 8.0 )
glColor3d(1,1,0)
glBegin( GL_POINTS );
for controlPoint in self._controlPoints:
controlPoint.draw()
glEnd()
except Exception as e:
glEnd()
print "Exception while drawing WindowWithControlPoints interface: " + str(e)
traceback.print_exc(file=sys.stdout)
# Restore projection to pixel mode
glMatrixMode(GL_PROJECTION)
glPopMatrix()
def deleteAllControlPoints(self):
"""Delete all the control points."""
self._controlPoints = []
def addControlPoint(self, controlPoint):
"""Adds a control point to the window."""
self._controlPoints.append( controlPoint )
def onLeftDown(self, mouseEvent):
"""Left mouse button pressed."""
x, y = mouseEvent.x, mouseEvent.y
self._captureControlPoint( self._findClosestControlPoint(x,y), x, y )
return True
def onLeftUp( self, mouseEvent ):
self._checkReleaseCapture(mouseEvent)
return True;
def _posToPixel(self, x, y):
size = self.getSize()
return int((x-self._boundsX[0])*size.width/self._width), \
size.height-int((y-self._boundsY[0])*size.height/self._height)
def _pixelToPos(self, x, y):
size = self.getSize()
return self._boundsX[0] + x*self._width/float(size.width), \
self._boundsY[0] - (y - size.height)*self._height/float(size.height)
def _findClosestControlPoint(self, x,y):
for controlPoint in self._controlPoints:
distX, distY = self._posToPixel( *controlPoint.getPos() )
distX -= x
distY -= y
if distX*distX + distY*distY < 25 :
return controlPoint;
return None;
def _captureControlPoint( self, controlPoint, x, y ):
if self.hasCapture(): return
self._controlPointHeld = controlPoint
if controlPoint is None : return
posX, posY = self._pixelToPos( x, y )
controlPoint.setPreviousMousePos( (posX, posY) )
self._holdPos = (x,y)
self.captureMouse()
def _checkReleaseCapture( self, mouseEvent ):
if not self.hasCapture(): return
if mouseEvent.leftDown or mouseEvent.rightDown : return
self.releaseMouse()
if self._controlPointHeld is not None :
self._controlPointHeld.unsetPreviousMousePos()
self._controlPointHeld = None
self._holdPos = (-1,-1)
def onMotion( self, mouseEvent ):
if not mouseEvent.leftDown and not mouseEvent.rightDown: return True
if not self.hasCapture(): return True
if self._controlPointHeld is None : return True
posX, posY = self._pixelToPos( mouseEvent.x, mouseEvent.y )
self._controlPointHeld.moveToPos( (posX, posY) )
return True
| [
[
8,
0,
0.0168,
0.0279,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0391,
0.0056,
0,
0.66,
0.25,
810,
0,
1,
0,
0,
810,
0,
0
],
[
1,
0,
0.0447,
0.0056,
0,
0.66,
... | [
"'''\nCreated on 2009-12-02\n\n@author: beaudoin\n'''",
"import GLUtils",
"from OpenGL.GL import *",
"class ControlPoint(object):\n \"\"\"Base class for any type of control point. \n Derived classes must implement:\n getPos() returns the x, y position of the control point.\"\"\"\n \n de... |
from CurveEditorCollection import CurveEditorCollection
from WindowWithControlPoints import WindowWithControlPoints, ControlPoint | [
[
1,
0,
0.5,
0.5,
0,
0.66,
0,
795,
0,
1,
0,
0,
795,
0,
0
],
[
1,
0,
1,
0.5,
0,
0.66,
1,
647,
0,
2,
0,
0,
647,
0,
0
]
] | [
"from CurveEditorCollection import CurveEditorCollection",
"from WindowWithControlPoints import WindowWithControlPoints, ControlPoint"
] |
'''
Created on 2009-08-24
This module contains the main OpenGL application window that is used by all SNM applications
@author: beaudoin
'''
import wx
import UI
class MainWindow(wx.Frame):
"""The class for the main window."""
MIN_TOOLPANEL_WIDTH = 200
MIN_CONSOLE_HEIGHT = 100
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE,
name='frame', fps=30, glCanvasSize=wx.DefaultSize,
showConsole=True,
consoleEnvironment={} ):
# Check if a fixed glWindow was asked
fixedGlWindow = glCanvasSize != wx.DefaultSize
self._glCanvasSize = glCanvasSize
#
# Forcing a specific style on the window.
# Should this include styles passed?
style |= wx.NO_FULL_REPAINT_ON_RESIZE
# Not resizable if GL canvas is fixed size
if fixedGlWindow :
style &= ~wx.RESIZE_BORDER & ~wx.MAXIMIZE_BOX
super(MainWindow, self).__init__(parent, id, title, pos, size, style, name)
#
# Create the menu
self._menuBar = wx.MenuBar()
self._fileMenu = wx.Menu()
self._fileMenu.Append( wx.ID_OPEN, "&Open" )
self._fileMenu.Append( wx.ID_SAVE, "&Save" )
self._fileMenu.AppendSeparator()
self._fileMenu.Append( wx.ID_EXIT, "&Quit" )
self._menuBar.Append(self._fileMenu, "&File" )
self._helpMenu = wx.Menu()
self._helpMenu.Append( wx.ID_ABOUT, "&About" )
self._menuBar.Append(self._helpMenu, "&Help" )
self.SetMenuBar( self._menuBar )
#
# Create the GL canvas
attribList = (wx.glcanvas.WX_GL_RGBA, # RGBA
wx.glcanvas.WX_GL_DOUBLEBUFFER, # Double Buffered
wx.glcanvas.WX_GL_DEPTH_SIZE, 24, # 24 bit depth
wx.glcanvas.WX_GL_STENCIL_SIZE, 8 ) # 8 bit stencil
self._glCanvas = UI.GLPanel(self, fps = fps, size = glCanvasSize, attribList = attribList)
# Create the right window (sashed) where the tool panel will be
self._rightWindow = wx.SashLayoutWindow(self)
self._rightWindow.SetDefaultSize((MainWindow.MIN_TOOLPANEL_WIDTH * 1.3,-1))
self._rightWindow.SetMinimumSizeX(MainWindow.MIN_TOOLPANEL_WIDTH)
self._rightWindow.SetOrientation( wx.LAYOUT_VERTICAL )
self._rightWindow.SetAlignment( wx.LAYOUT_RIGHT )
if not fixedGlWindow:
self._rightWindow.SetSashVisible( wx.SASH_LEFT, True )
self._rightWindow.Bind( wx.EVT_SASH_DRAGGED, self.onSashDragRightWindow )
#
# Create the tool panel
self._toolPanel = UI.ToolPanel(self._rightWindow)
# Create the bottom window (sashed) where the console will be
self._bottomWindow = wx.SashLayoutWindow(self)
self._bottomWindow.SetDefaultSize((-1,MainWindow.MIN_CONSOLE_HEIGHT*2))
self._bottomWindow.SetMinimumSizeY(MainWindow.MIN_CONSOLE_HEIGHT)
self._bottomWindow.SetOrientation( wx.LAYOUT_HORIZONTAL )
self._bottomWindow.SetAlignment( wx.LAYOUT_BOTTOM )
if not fixedGlWindow:
self._bottomWindow.SetSashVisible( wx.SASH_TOP, True )
self._bottomWindow.Bind( wx.EVT_SASH_DRAGGED, self.onSashDragBottomWindow )
#
# Create the console window
self._console = UI.PythonConsole(self._bottomWindow, size=(-1,220), consoleEnvironment = consoleEnvironment )
if not showConsole:
self._bottomWindow.Hide()
self.Bind( wx.EVT_SIZE, self.onSize )
#
# Private methods
def _layoutFrame(self):
"""Private. Perform frame layout"""
wx.LayoutAlgorithm().LayoutFrame(self, self._glCanvas)
#
# Event handlers
def onSize(self, event):
self._layoutFrame()
if self._glCanvasSize != wx.DefaultSize :
currGlCanvasSize = self._glCanvas.GetSize()
diff = ( currGlCanvasSize[0] - self._glCanvasSize[0], currGlCanvasSize[1] - self._glCanvasSize[1] )
if diff == (0,0) :
return
currentSize = event.GetSize()
newSize= ( currentSize[0] - diff[0], currentSize[1] - diff[1] )
if newSize == currentSize :
return
self.SetSize( newSize )
self.SendSizeEvent()
def onSashDragRightWindow(self, event):
if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
return
self._rightWindow.SetDefaultSize((event.GetDragRect().width,-1))
self._layoutFrame()
def onSashDragBottomWindow(self, event):
if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
return
self._bottomWindow.SetDefaultSize((-1,event.GetDragRect().height))
self._layoutFrame()
#
# Accessors
def getGLCanvas(self):
"""Return the associated GL canvas."""
return self._glCanvas
def getToolPanel(self):
"""Return the associated tool panel."""
return self._toolPanel
def getFps(self):
"""Return the desired frame per second for this window."""
return self._glCanvas.getFps()
| [
[
8,
0,
0.0265,
0.0464,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0596,
0.0066,
0,
0.66,
0.3333,
666,
0,
1,
0,
0,
666,
0,
0
],
[
1,
0,
0.0662,
0.0066,
0,
0.66... | [
"'''\nCreated on 2009-08-24\n\nThis module contains the main OpenGL application window that is used by all SNM applications\n\n@author: beaudoin\n'''",
"import wx",
"import UI",
"class MainWindow(wx.Frame):\n \"\"\"The class for the main window.\"\"\"\n MIN_TOOLPANEL_WIDTH = 200\n MIN_CONSOLE_HEIGHT ... |
'''
Created on 2009-09-24
@author: beaudoin
'''
import Utils, wx
import PyUtils
class MemberDisplay(Utils.Observer):
"""
This class wraps an element and displays its content in a table with a grid sizer
"""
def __init__(self, table, sizer):
super(MemberDisplay,self).__init__()
self._table = table
self._sizer = sizer
self._contentControls = None
self._object = None
def __del__(self):
try: self.deleteObserver()
except AttributeError: pass
def deleteObserver(self):
try: self._object.deleteObserver(self)
except AttributeError: pass
def attachObject(self, object):
self.deleteObserver()
self._object = object
try:
self._proxy = PyUtils.wrap( object, recursive = False )
except AttributeError:
self._proxy = None
try: object.addObserver(self)
except AttributeError: pass
self.createControls()
def createControls(self):
"""Creates all the controls to display the attached object's content"""
self._table.Freeze()
self._table.DestroyChildren()
self._contentControls = []
if self._proxy is None :
self._table.SetVirtualSize((0,0))
self._table.Thaw()
return
for i in range( self._proxy.getMemberCount() ) :
( value, info ) = self._proxy.getValueAndInfo(i)
if info.isObject : continue
value = info.format(value)
labelControl = wx.StaticText(self._table, label=info.fancyName)
if info.editable :
contentControl = self.createControlForMember( self._table, info, value)
else :
contentControl = wx.StaticText(self._table, label=str(value))
self._sizer.Add( labelControl, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.TOP , 2)
self._sizer.Add( contentControl, 0, wx.EXPAND | wx.TOP | wx.RIGHT, 2)
self._contentControls.append( contentControl )
self._table.FitInside()
self._table.Thaw()
def createControlForMember( self, parent, info, value ):
"""Creates a control for the member specified in info."""
from App.Proxys import Member
if isinstance(info, Member.Enum) :
result = wx.ComboBox( parent, value=value, style = wx.CB_READONLY, choices = info.enum.choices() )
result.Bind( wx.EVT_COMBOBOX, lambda event: self.changeValue(info.name, result.GetValue()) )
elif info.type == bool :
result = wx.CheckBox( parent )
result.SetValue(value)
result.Bind( wx.EVT_CHECKBOX, lambda event: self.changeValue(info.name, result.GetValue()) )
else:
result = wx.TextCtrl(parent, value=str(value))
result.Bind( wx.EVT_KILL_FOCUS, lambda event: self.changeValue(info.name, result.GetValue()) )
return result
def changeValue(self, memberName, value):
"""The value of the control specified in info has changed."""
try: self._proxy.setValueAndUpdateObject( memberName, value, self._object )
except: self.update()
def update(self, data = None):
"""Called whenever the observer is updated."""
self._proxy.extractFromObject( self._object, recursive = False )
j = 0
for i in range( self._proxy.getMemberCount() ) :
( value, info ) = self._proxy.getValueAndInfo(i)
if info.isObject : continue
value = info.format(value)
if not info.type is bool : value = str(value)
control = self._contentControls[j]
try: self._contentControls[j].SetValue(value) # Try to set the value
except AttributeError: self._contentControls[j].SetLabel(value) # Otherwise SetLabel will do
j += 1
| [
[
8,
0,
0.03,
0.05,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.07,
0.01,
0,
0.66,
0.3333,
842,
0,
2,
0,
0,
842,
0,
0
],
[
1,
0,
0.08,
0.01,
0,
0.66,
0.6667... | [
"'''\nCreated on 2009-09-24\n\n@author: beaudoin\n'''",
"import Utils, wx",
"import PyUtils",
"class MemberDisplay(Utils.Observer):\n \"\"\"\n This class wraps an element and displays its content in a table with a grid sizer\n \"\"\"\n \n def __init__(self, table, sizer):\n super(MemberD... |
'''
Created on 2009-10-08
@author: beaudoin
'''
import wx
class ToggleBitmapButton(wx.BitmapButton):
def __init__(self, parent, id=wx.ID_ANY, bitmap=wx.NullBitmap, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BU_AUTODRAW, validator=wx.DefaultValidator, name=wx.ButtonNameStr, selected=False):
"""Creates a bitmap button that can be toggled on and off."""
super(ToggleBitmapButton,self).__init__( parent, id, bitmap, pos, size, style, validator, name)
self._selected = selected
self._lookIsSelected = False
self.Bind( wx.EVT_BUTTON, self.OnClick )
#
# Callbacks
#
def OnClick(self, event):
"""Flips the state if possible."""
self._selected = not self._selected
self._updateLook()
event.Skip()
#
# Public methods
#
def SetBitmapSelected(self, bitmap):
"""Sets the bitmap for the selected (depressed) button appearance."""
super(ToggleBitmapButton,self).SetBitmapSelected(bitmap)
self._updateLook()
def SetSelected(self, selected = True):
"""Indicates whether this toggle button should be selected or not."""
self._selected = selected
self._updateLook()
def IsSelected(self):
"""Returns true if the toggle button is currently in its selected state, false otherwise."""
return self._selected
#
# Private methods
#
def _updateLook(self):
"""Make sure the look matches the selected state."""
if self._selected == self._lookIsSelected : return
# Toggle looks
other = self.GetBitmapSelected()
if not other.IsOk(): return
current = self.GetBitmapLabel()
self.SetBitmapLabel( other )
super(ToggleBitmapButton,self).SetBitmapSelected( current )
self._lookIsSelected = self._selected
| [
[
8,
0,
0.0448,
0.0746,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1045,
0.0149,
0,
0.66,
0.5,
666,
0,
1,
0,
0,
666,
0,
0
],
[
3,
0,
0.5373,
0.8209,
0,
0.66,
... | [
"'''\nCreated on 2009-10-08\n\n@author: beaudoin\n'''",
"import wx",
"class ToggleBitmapButton(wx.BitmapButton):\n \n def __init__(self, parent, id=wx.ID_ANY, bitmap=wx.NullBitmap, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BU_AUTODRAW, validator=wx.DefaultValidator, name=wx.ButtonNameStr, sele... |
from ToggleBitmapButton import ToggleBitmapButton | [
[
1,
0,
1,
1,
0,
0.66,
0,
45,
0,
1,
0,
0,
45,
0,
0
]
] | [
"from ToggleBitmapButton import ToggleBitmapButton"
] |
import ToolSets
import GLUITools
import Ext
from InfoTree import InfoTreeBasic, InfoTree
from GLPanel import GLPanel
from PythonConsole import PythonConsole
from ToolPanel import ToolPanel
from MainWindow import MainWindow
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
262,
0,
1,
0,
0,
262,
0,
0
],
[
1,
0,
0.2222,
0.1111,
0,
0.66,
0.1429,
486,
0,
1,
0,
0,
486,
0,
0
],
[
1,
0,
0.3333,
0.1111,
0,
... | [
"import ToolSets",
"import GLUITools",
"import Ext",
"from InfoTree import InfoTreeBasic, InfoTree",
"from GLPanel import GLPanel",
"from PythonConsole import PythonConsole",
"from ToolPanel import ToolPanel",
"from MainWindow import MainWindow"
] |
'''
Created on 2009-09-14
@author: beaudoin
'''
import wx
import Utils
from MemberDisplay import MemberDisplay
# Unique list for all the images
_iconList = None
_iconDict = {}
_unknownIcon = '../data/ui/unknownIcon.png'
def _getIconList():
global _iconList
if _iconList is None :
_iconList = wx.ImageList(16,16, False)
return _iconList
def _addIcon( pngFilename ):
"""Private, adds an icon to the list of icon and the dictionnary."""
global _iconDict, _unknownIcon
iconList = _getIconList()
if pngFilename == None: pngFilename = _unknownIcon
bitmap = wx.Bitmap(pngFilename, wx.BITMAP_TYPE_PNG)
if not bitmap.Ok() :
if pngFilename == _unknownIcon :
raise IOError("Icon file '%s' not found" % _unknownIcon)
return _addIcon(None)
index = iconList.Add(bitmap)
_iconDict[pngFilename] = index
return index
def getIconIndex( pngFilename ):
"""Returns the index of the icon for the pngFilename.
Use this to set node images in the info tree."""
global _iconDict
try: return _iconDict[pngFilename]
except KeyError: return _addIcon( pngFilename )
class InfoTreeBasic(wx.TreeCtrl):
"""A class that display a tree structure containing all the information of a given wrappable and observable object."""
def __init__(self, parent, object = None, rootName = "Root", autoVisible = False, onUpdate = None, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style= wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT | wx.TR_LINES_AT_ROOT,
validator = wx.DefaultValidator, name='InfoTreeBasic'):
"""Initializes a tree that listens to the object."""
super(InfoTreeBasic, self).__init__(parent, id, pos, size, style, validator, name)
# Configure empty tree
self.SetImageList( _getIconList() )
self.AddRoot( "" )
# Set a reasonable minimum width
self.SetMinSize( (-1,80) )
self._rootName = rootName
self._autoVisible = autoVisible
self._onUpdate = onUpdate
self._updateLocks = 0
# Create an observer that need to be alive for as long as the tree is alive
# so store it in a member
self.attachToObject( object )
def isAutoVisible(self):
"""True if the tree should make new nodes visible when they are added."""
return self._autoVisible
def attachToObject(self, object):
"""Attach this tree to a specific object."""
from App.Proxys.NodeData import NodeData
if object is not None:
self._root = NodeData( self._rootName, object, self, self.GetRootItem() )
#
# Callbacks
#
def updateLock(self):
"""Called whenever something in the tree is updated. Call that to set a lock. The update
will take place once all the locks are released."""
self._updateLocks += 1
def updateUnlock(self):
"""Called whenever something in the tree is updated. Call that to release a lock. The update
will take place once all the locks are released."""
assert self._updateLocks > 0, "Update unlocked, but no lock set!"
self._updateLocks -= 1
if self._updateLocks == 0 :
self.update()
def update(self, data = None):
"""Called whenever something in the tree is updated."""
try: self._onUpdate(data)
except TypeError: pass
class InfoTree(wx.Panel):
"""A complete tree attached to an info box."""
def __init__(self, parent, object = None, rootName = "Root", autoVisible = False, onUpdate = None, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style= wx.TAB_TRAVERSAL, name='InfoTree'):
super(InfoTree, self).__init__(parent, id, pos, size, style, name)
self._infoTreeBasic = InfoTreeBasic( self, object, rootName, autoVisible, onUpdate )
self._sashWindow = wx.SashWindow( self )
self._sashWindow.SetSashVisible( wx.SASH_TOP, True )
self._infoTable = wx.ScrolledWindow(self._sashWindow, style = wx.VSCROLL )
self._infoTable.SetBackgroundColour( (255,255,255) )
self._infoTable.SetScrollRate(0,10)
self._infoTable.SetMinSize( (-1,70) )
self._infoTableSizer = wx.FlexGridSizer(0,2,0,8)
self._infoTableSizer.AddGrowableCol(1)
self._infoTable.SetSizer( self._infoTableSizer )
self._vBoxSashWindow = wx.BoxSizer(wx.VERTICAL)
self._vBoxSashWindow.Add( self._infoTable, 1, wx.EXPAND )
self._vBoxSashWindow.SetMinSize( (-1,100) )
self._sashWindow.SetSizer( self._vBoxSashWindow )
self._sashWindow.Bind( wx.EVT_SASH_DRAGGED, self.sashWindowResize )
self._vBox = wx.BoxSizer(wx.VERTICAL)
self._vBox.Add( self._infoTreeBasic, 1, wx.EXPAND )
self._vBox.Add( self._sashWindow, 0, wx.EXPAND )
self.SetSizerAndFit( self._vBox )
self._memberDisplay = MemberDisplay(self._infoTable, self._infoTableSizer)
self._infoTreeBasic.Bind( wx.EVT_TREE_SEL_CHANGED, self.selectionChanged )
self.Bind( wx.EVT_PAINT, self.onPaint )
#
# Private methods
#
def _adjustSashSize(self):
"""Private. Make sure sash size is not too large."""
height = self._vBoxSashWindow.GetMinSize()[1]
maxHeight = self.GetSize()[1] - 80
if height > maxHeight :
if maxHeight <= 0 : maxHeight = -1
currMaxHeight = self._vBoxSashWindow.GetMinSize().height
if currMaxHeight == maxHeight : return
self._vBoxSashWindow.SetMinSize( (-1,maxHeight) )
self._refreshAll()
def _refreshAll(self):
"""Private. Make sure everything is laid-out correctly."""
self.Fit()
self.GetParent().Layout()
def _displayInfo(self, object):
"""Display info on the passed object."""
self._memberDisplay.attachObject(object)
#
# Public methods
#
def attachToObject(self, object):
self._infoTreeBasic.attachToObject(object)
def getTree(self):
return self._infoTreeBasic
#
# Callbacks
#
def onPaint(self, event):
self._adjustSashSize()
event.Skip()
def sashWindowResize(self, event):
"""Called whenever the sash window is resized"""
if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE :
return
self._vBoxSashWindow.SetMinSize( (-1,event.GetDragRect().height) )
self._adjustSashSize()
self._refreshAll()
def selectionChanged(self, event):
nodeData = self._infoTreeBasic.GetItemPyData(event.GetItem())
try: object = nodeData.getObject()
except (AttributeError, TypeError): object = nodeData
self._displayInfo( object )
event.Skip()
| [
[
8,
0,
0.0147,
0.0245,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0343,
0.0049,
0,
0.66,
0.0909,
666,
0,
1,
0,
0,
666,
0,
0
],
[
1,
0,
0.0392,
0.0049,
0,
0.66... | [
"'''\nCreated on 2009-09-14\n\n@author: beaudoin\n'''",
"import wx",
"import Utils",
"from MemberDisplay import MemberDisplay",
"_iconList = None",
"_iconDict = {}",
"_unknownIcon = '../data/ui/unknownIcon.png'",
"def _getIconList():\n global _iconList\n if _iconList is None :\n _iconList... |
'''
Created on 2009-08-30
@author: beaudoin
This file contains a class that can be used as a python interpreter console
'''
import wx
import sys
class PythonConsole(wx.Panel):
"""A console to output python and a command line interprete.
You should only have one of this as it seize the standard output.
"""
def __init__(self, parent, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.TAB_TRAVERSAL,
name='', consoleEnvironment={} ):
"""Initialize a console. You can pass other dictionnaries as globals and locals."""
super(PythonConsole, self).__init__(parent, id, pos, size, style, name)
#
# Create the console components
self._console = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH2 | wx.TE_CHARWRAP )
self._console.SetDefaultStyle( wx.TextAttr(wx.BLACK, wx.WHITE, wx.Font(8, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) ) )
self._commandLine = wx.TextCtrl(self, size=(-1,20), style = wx.TE_PROCESS_ENTER | wx.TE_RICH2 )
self._commandLine.SetDefaultStyle( wx.TextAttr(wx.BLUE, wx.WHITE, wx.Font(8, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) ) )
#
# Create the sizer
self._vBox = wx.BoxSizer(wx.VERTICAL)
self._vBox.Add( self._console, 1, wx.EXPAND )
self._vBox.Add( self._commandLine, 0, wx.EXPAND )
self.SetSizer( self._vBox )
#
# Do bindings
self._commandLine.Bind( wx.EVT_KEY_DOWN, self.processKeyDown )
self._commandLine.Bind( wx.EVT_TEXT_ENTER, self.processUserCommand )
#
# Initialize
self._history = []
self._historyIndex = 0
self._currentCommand = u""
self._commandDepth = 0
self._runningCommand = u""
self._globals = consoleEnvironment
self._locals = consoleEnvironment
sys.stdout = self
#
# write function for stdout and stderr
def write(self, text, color = None):
# Freeze the window then scroll it as many lines as needed
self._console.Freeze()
before = self._console.GetLastPosition()
self._console.AppendText( text )
after = self._console.GetLastPosition()
if color is not None :
self._console.SetStyle (before, after, wx.TextAttr(color))
self._console.ScrollLines( text.count('\n') + 1 )
self._console.ShowPosition( self._console.GetLastPosition() )
self._console.Thaw()
#
# wxPython Window Handlers
def processKeyDown(self, event):
"""Called whenever the user presses a key in the command line.
Used to catch the UP arrow and DOWN arrow and navigate through history.
"""
keyCode = event.GetKeyCode()
if keyCode == wx.WXK_UP:
if self._historyIndex != 0:
if self._historyIndex == len( self._history ):
self._currentCommand = self._commandLine.GetValue()
self._historyIndex -= 1
self._commandLine.SetValue( self._history[self._historyIndex] )
self._commandLine.SetInsertionPointEnd()
elif keyCode == wx.WXK_DOWN:
if self._historyIndex != len( self._history ):
self._historyIndex += 1
if self._historyIndex == len( self._history ):
self._commandLine.SetValue( self._currentCommand )
else:
self._commandLine.SetValue( self._history[self._historyIndex] )
self._commandLine.SetInsertionPointEnd()
else:
# Assume text was entered
self._historyIndex = len( self._history )
event.Skip()
def processUserCommand(self, event):
"""Called when the user press enter to validate a new command line."""
commandLine = self._commandLine.GetValue().strip()
if len(commandLine) > 0:
self._history.append( commandLine )
self._historyIndex = len(self._history)
self._currentCommand = u""
if len(commandLine) == 0 and self._commandDepth > 0:
self._commandDepth -= 1
if self._commandDepth > 0:
self.write( "... " + " " * self._commandDepth + "<<<<\n", wx.BLUE )
else:
self.write( "<<<\n", wx.BLUE )
else:
if self._commandDepth == 0:
self.write( ">>> ", wx.BLUE )
else:
self.write( "... ", wx.BLUE )
commandLine = " " * self._commandDepth + commandLine
self._runningCommand += commandLine + "\n"
self.write( commandLine + "\n", wx.BLUE )
if commandLine.endswith(':'):
self._commandDepth += 1
if self._commandDepth == 0:
# First assume it is an expression
try:
x = eval( self._runningCommand, self._globals, self._locals )
if x is not None:
self._globals["_"] = x
print x
# If it fails, execute it as a statement
except:
try:
exec self._runningCommand in self._globals, self._locals
except NameError as exception:
self.write( "Symbol not found: " + str(exception) + "\n", wx.RED );
except SyntaxError as exception:
if exception.text is not None:
self.write( "Syntax error: " + "\n", wx.RED );
self.write( " " + exception.text + "\n", wx.RED );
self.write( " " + " " * exception.offset + "^" + "\n", wx.RED );
else:
self.write( "Syntax error: " + str(exception) + "\n", wx.RED );
except EnvironmentError as exception:
self.write( "IO error (" + str(exception.errno) + "): " + exception.strerror + "\n", wx.RED );
except ArithmeticError as exception:
self.write( "Arithmetic error: " + str(exception) + "\n", wx.RED );
except ImportError as exception:
self.write( "Import error: " + str(exception) + "\n", wx.RED );
except AssertionError as exception:
self.write( "Assertion failed: " + str(exception) + "\n", wx.RED );
except AttributeError as exception:
self.write( "Attribute not found: " + str(exception) + "\n", wx.RED );
except TypeError as exception:
self.write( "Invalid type: " + str(exception) + "\n", wx.RED );
except ValueError as exception:
self.write( "Invalid value: " + str(exception) + "\n", wx.RED );
except IndexError as exception:
self.write( "Index out of range: " + str(exception) + "\n", wx.RED );
except KeyError as exception:
self.write( "Key does not exist: " + str(exception) + "\n", wx.RED );
except SystemError as exception:
self.write( "Internal error: " + str(exception) + "\n", wx.RED );
except MemoryError as exception:
self.write( "Out of memory error: " + str(exception) + "\n", wx.RED );
except SystemExit:
wx.GetApp().GetTopWindow().Close()
except:
self.write( "Unknown error, exception raised: ", sys.exc_info()[0] + "\n", wx.RED );
finally:
self._runningCommand = u""
self._commandLine.SetValue(u"")
| [
[
8,
0,
0.0222,
0.0389,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.05,
0.0056,
0,
0.66,
0.3333,
666,
0,
1,
0,
0,
666,
0,
0
],
[
1,
0,
0.0556,
0.0056,
0,
0.66,
... | [
"'''\nCreated on 2009-08-30\n\n@author: beaudoin\n\nThis file contains a class that can be used as a python interpreter console\n'''",
"import wx",
"import sys",
"class PythonConsole(wx.Panel):\n \"\"\"A console to output python and a command line interprete.\n You should only have one of this as it sei... |
'''
Created on 2009-08-25
Basic controller editor
@author: beaudoin
'''
import sys
sys.path += ['.']
import wx, App, math
movieResolution = (1280,720)
movieSetup = False # True if we want a movie
glMovie = False # True if we're only interested in recording the GL canvas
# False if we want a "screen cast"
glCanvasSize = wx.DefaultSize
size = wx.DefaultSize
showConsole = True
if movieSetup:
if glMovie:
glCanvasSize = movieResolution
else:
size = movieResolution
showConsole = False
app = App.SNMApp("Style Editor", size = size, glCanvasSize=glCanvasSize, showConsole = showConsole)
import UI, Utils, GLUtils, Physics, Core, MathLib, PyUtils
from App import InstantChar, KeyframeEditor
# Create the desired tool sets
toolPanel = app.getToolPanel()
animationToolSet = UI.ToolSets.Animation(toolPanel)
if not movieSetup:
optionsToolSet = UI.ToolSets.Options(toolPanel)
optionsToolSet._toolSet.setOpen(False)
cameraToolSet = UI.ToolSets.Camera(toolPanel)
cameraToolSet._toolSet.setOpen(False)
instantChar = InstantChar.Model()
if not movieSetup:
controllerSnapshotToolSet = UI.ToolSets.SnapshotTree(toolPanel)
controllerSnapshotToolSet._toolSet.setOpen(False)
controllerTreeToolSet = UI.ToolSets.ControllerTree(toolPanel)
controllerTreeToolSet._toolSet.setOpen(False)
glCanvas = app.getGLCanvas()
glCanvas.addGLUITool( UI.GLUITools.CurveEditorCollection )
#from Data.Frameworks import DefaultFramework
#from Data.Frameworks import DanceFramework
#from Data.Frameworks import WalkFramework
#####################
## BEGIN Custom for Instant Character
character = instantChar.create()
#controller = PyUtils.load( "Characters.BipV3.Controllers.CartoonySneak", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.ZeroWalk", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.VeryFastWalk_5-43_0-4", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.jog_8-76_0-33", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.run_21-57_0-38_0-10", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.FastWalk_3-7_0-53", character )
controller = PyUtils.load( "Characters.BipV3.Controllers.EditableWalking", character )
#controller = PyUtils.load( "Temp.Cartoony", character )
#controller = PyUtils.load( "Temp.TipToe", character )
controller.setStance( Core.LEFT_STANCE );
instantChar.connectController(False)
#character.loadReducedStateFromFile( "Data/Characters/BipV3/Controllers/runState.rs" )
keyframeEditor = KeyframeEditor.Model()
## END
#####################
######################
## BEGIN DUMMY STUFF
#staircase = App.Scenario.Staircase( position=(0,0,5), rightRampHeight = 1, stepCount = 22, leftRampHeight = 1, angle = math.pi/4.0 )
#staircase.load()
#PyUtils.convertController("../../scoros5/data/controllers/bipV3/fWalk_3.sbc")
#ctrl2 = PyUtils.copy( app.getController(0), char )
## END DUMMY STUFF
######################
# Initial snapshot
app.takeSnapshot()
app.MainLoop()
app.Destroy()
| [
[
8,
0,
0.0408,
0.0714,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0816,
0.0102,
0,
0.66,
0.0345,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1122,
0.0102,
0,
0.66... | [
"'''\nCreated on 2009-08-25\n\nBasic controller editor\n\n@author: beaudoin\n'''",
"import sys",
"import wx, App, math",
"movieResolution = (1280,720)",
"movieSetup = False # True if we want a movie",
"glMovie = False # True if we're only interested in recording the GL canvas",
"glCanvasSize = wx.Def... |
'''
Created on 2009-08-28
@author: beaudoin
'''
from App.Proxys import *
data = RigidBody(
name = "ground",
locked = True,
cdps = [ BoxCDP( (-50,-1,-50), (50,0,50) ),
PlaneCDP( (0,1,0), (0,-1,0) ) ],
frictionCoeff = 2.5,
restitutionCoeff = 0.35 ) | [
[
8,
0,
0.2,
0.3333,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4667,
0.0667,
0,
0.66,
0.5,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.8,
0.4667,
0,
0.66,
1,... | [
"'''\nCreated on 2009-08-28\n\n@author: beaudoin\n'''",
"from App.Proxys import *",
"data = RigidBody(\n name = \"ground\",\n locked = True,\n cdps = [ BoxCDP( (-50,-1,-50), (50,0,50) ),\n PlaneCDP( (0,1,0), (0,-1,0) ) ],\n frictionCoeff = 2.5,\n restitutionCoeff = 0.35 )"
] |
'''
Created on 2009-08-28
@author: beaudoin
'''
from App.Proxys import *
data = RigidBody(
name = "ground",
locked = True,
cdps = [ PlaneCDP( (0,1,0), (0,0,0) ) ],
frictionCoeff = 2.5,
restitutionCoeff = 0.35 )
| [
[
8,
0,
0.2143,
0.3571,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0714,
0,
0.66,
0.5,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.8214,
0.4286,
0,
0.66,
... | [
"'''\nCreated on 2009-08-28\n\n@author: beaudoin\n'''",
"from App.Proxys import *",
"data = RigidBody(\n name = \"ground\",\n locked = True,\n cdps = [ PlaneCDP( (0,1,0), (0,0,0) ) ],\n frictionCoeff = 2.5,\n restitutionCoeff = 0.35 )"
] |
'''
Created on 2009-08-28
@author: beaudoin
'''
from App.Proxys import *
data = RigidBody(
name = "dodgeBall",
meshes = [ ("../data/models/sphere.obj",(0.8,0,0,1)) ],
mass = 2.0,
moi = ( 0.2,0.2,0.2 ),
cdps = [ SphereCDP( (0,0,0), 0.1 ) ],
pos = (1000, 1000, 0.2),
frictionCoeff = 1.8,
restitutionCoeff = 0.35 ) | [
[
8,
0,
0.1765,
0.2941,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4118,
0.0588,
0,
0.66,
0.5,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.7647,
0.5294,
0,
0.66,
... | [
"'''\nCreated on 2009-08-28\n\n@author: beaudoin\n'''",
"from App.Proxys import *",
"data = RigidBody(\n name = \"dodgeBall\",\n meshes = [ (\"../data/models/sphere.obj\",(0.8,0,0,1)) ],\n mass = 2.0,\n moi = ( 0.2,0.2,0.2 ),\n cdps = [ SphereCDP( (0,0,0), 0.1 ) ],\n pos = (1000, 1000, 0.2),\n... |
'''
Created on 2009-08-28
@author: beaudoin
'''
from os import path
meshDir = path.join( path.dirname(__file__), "Meshes" )
colourDark = ( 0.5, 0.5, 0.5, 1 )
colourLight = ( 0.8, 0.8, 0.8, 1 )
from App.Proxys import *
data = Character(
name = "Bip",
root = ArticulatedRigidBody(
name = "pelvis",
meshes = [ (path.join(meshDir, "pelvis_2_b.obj"), colourDark),
(path.join(meshDir, "pelvis_2_s.obj"), colourLight) ],
mass = 12.9,
moi = (0.0705, 0.11, 0.13),
cdps = [ SphereCDP((0,-0.075,0), 0.12) ],
pos = (0, 1.035, 0.2),
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
arbs = [
ArticulatedRigidBody(
name = "torso",
meshes = [ (path.join(meshDir, "torso_2_b.obj"), colourDark),
(path.join(meshDir, "torso_2_s_v2.obj"), colourLight) ],
mass = 22.5,
moi = (0.34, 0.21, 0.46),
cdps = [ SphereCDP((0,0,0.01), 0.11) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "head",
meshes = [ (path.join(meshDir, "head_b.obj"), colourDark),
(path.join(meshDir, "head_s.obj"), colourLight) ],
mass = 5.2,
moi = (0.04, 0.02, 0.042),
cdps = [ SphereCDP((0,0.04,0), 0.11) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperArm",
meshes = [ (path.join(meshDir, "lUpperArm.obj"), colourDark) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerArm",
meshes = [ (path.join(meshDir, "lLowerArm.obj"), colourDark) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperArm",
meshes = [ (path.join(meshDir, "rUpperArm.obj"), colourDark) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerArm",
meshes = [ (path.join(meshDir, "rLowerArm.obj"), colourDark) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperLeg",
meshes = [ (path.join(meshDir, "lUpperLeg.obj"), colourDark) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.26, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerLeg",
meshes = [ (path.join(meshDir, "lLowerLeg.obj"), colourDark) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.2, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperLeg",
meshes = [ (path.join(meshDir, "rUpperLeg.obj"), colourDark) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.26, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerLeg",
meshes = [ (path.join(meshDir, "rLowerLeg.obj"), colourDark) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.2, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lFoot",
meshes = [ (path.join(meshDir, "lFoot.obj"), colourDark) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.025, -0.033, -0.09), (0.025, 0.005, 0.055)) ],
# CDP_Sphere 0.025 -0.025 -0.08 0.01
# CDP_Sphere -0.025 -0.025 -0.08 0.01
# CDP_Sphere 0.02 -0.025 0.045 0.01
# CDP_Sphere -0.02 -0.025 0.045 0.01
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "rFoot",
meshes = [ (path.join(meshDir, "rFoot.obj"), colourDark) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.025, -0.033, -0.09), (0.025, 0.005, 0.055)) ],
# CDP_Sphere 0.025 -0.025 -0.08 0.01
# CDP_Sphere -0.025 -0.025 -0.08 0.01
# CDP_Sphere 0.02 -0.025 0.045 0.01
# CDP_Sphere -0.02 -0.025 0.045 0.01
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "lToes",
meshes = [ (path.join(meshDir, "lToes.obj"), colourDark) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ SphereCDP((0.0, -0.005, 0.025), 0.01) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "rToes",
meshes = [ (path.join(meshDir, "rToes.obj"), colourDark) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ SphereCDP((0.0, -0.005, 0.025), 0.01) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) )
],
joints = [
BallInSocketJoint(
name = "pelvis_torso",
parent = "pelvis",
child = "torso",
posInParent = (0, 0.17, -0.035),
posInChild = (0, -0.23, -0.01),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "torso_head",
parent = "torso",
child = "head",
posInParent = (0, 0.1, -0.00),
posInChild = (0, -0.16, -0.025),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "lShoulder",
parent = "torso",
child = "lUpperArm",
posInParent = (0.20, 0.07, 0.02),
posInChild = (-0.17, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-1.7, 1.7, -1.5, 1.5, -1.5, 1.5) ),
BallInSocketJoint(
name = "rShoulder",
parent = "torso",
child = "rUpperArm",
posInParent = (-0.20, 0.07, 0.02),
posInChild = (0.17, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-1.7, 1.7, -1.5, 1.5, -1.5, 1.5) ),
HingeJoint(
name = "lElbow",
parent = "lUpperArm",
child = "lLowerArm",
posInParent = (0.175, 0, 0.006),
posInChild = (-0.215, 0, 0),
axis = ( 0, 1, 0 ),
limits = (-2.7, 0) ),
HingeJoint(
name = "rElbow",
parent = "rUpperArm",
child = "rLowerArm",
posInParent = (-0.175, 0, 0.006),
posInChild = (0.215, 0, 0),
axis = ( 0, -1, 0 ),
limits = (-2.7, 0) ),
BallInSocketJoint(
name = "lHip",
parent = "pelvis",
child = "lUpperLeg",
posInParent = (0.1, -0.05, 0.0),
posInChild = (0, 0.21, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-1.3, 1.9, -1, 1, -0.25, 1) ),
BallInSocketJoint(
name = "rHip",
parent = "pelvis",
child = "rUpperLeg",
posInParent = (-0.1, -0.05, 0.0),
posInChild = (0, 0.21, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-1.3, 1.9, -1, 1, -1, 0.25) ),
HingeJoint(
name = "lKnee",
parent = "lUpperLeg",
child = "lLowerLeg",
posInParent = (0, -0.26, 0),
posInChild = (0, 0.21, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
HingeJoint(
name = "rKnee",
parent = "rUpperLeg",
child = "rLowerLeg",
posInParent = (0, -0.26, 0),
posInChild = (0, 0.21, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
UniversalJoint(
name = "lAnkle",
parent = "lLowerLeg",
child = "lFoot",
posInParent = (0, -0.25, 0.01),
posInChild = (0.0, 0.02, -0.04),
parentAxis = (1, 0, 0),
childAxis = (0, 0, 1),
limits = (-0.75, 0.75, -0.75, 0.75) ),
UniversalJoint(
name = "rAnkle",
parent = "rLowerLeg",
child = "rFoot",
posInParent = (0, -0.25, 0.01),
posInChild = (0.0, 0.02, -0.04),
parentAxis = (1, 0, 0),
childAxis = (0, 0, -1),
limits = (-0.75, 0.75, -0.75, 0.75) ),
HingeJoint(
name = "lToeJoint",
parent = "lFoot",
child = "lToes",
posInParent = (0, -0.02, 0.05),
posInChild = (0, 0, -0.025),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.02) ),
HingeJoint(
name = "rToeJoint",
parent = "rFoot",
child = "rToes",
posInParent = (0, -0.02, 0.05),
posInChild = (0, 0, -0.025),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.02) )
]
)
| [
[
8,
0,
0.0096,
0.0161,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0225,
0.0032,
0,
0.66,
0.1667,
688,
0,
1,
0,
0,
688,
0,
0
],
[
14,
0,
0.0289,
0.0032,
0,
0.6... | [
"'''\nCreated on 2009-08-28\n\n@author: beaudoin\n'''",
"from os import path",
"meshDir = path.join( path.dirname(__file__), \"Meshes\" )",
"colourDark = ( 0.5, 0.5, 0.5, 1 )",
"colourLight = ( 0.8, 0.8, 0.8, 1 )",
"from App.Proxys import *",
"data = Character(\n \n name = \"... |
from App.Proxys import *
data = SimBiController(
name = 'Turning',
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 200.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 20.0, kd = 5.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 20.0, kd = 5.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 75.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 75.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 10.0, kd = 0.5, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 10.0, kd = 0.5, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 1,
duration = 0.7,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.319408095177, 59.9547123615 ) ],
forceY = [ ( 0.0, 0.0 ) ],
forceZ = [ ( 0.693332994276, -5.26775796183 ), ( 0.693342994276, 54.4334989389 ) ],
torqueX = [ ],
torqueY = [
( 0.0236475679619, 14.3936675448 ),
( 0.38629006461, 50.9613634694 ),
( 0.841129806169, -34.6226057158 ) ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.0, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.5804 ), ( 0.22408, 0.862791 ), ( 0.431438, -0.048689 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1.0, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1.0, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0170029671656, 0.546257090497 ), ( 0.640214956672, 0.168866831761 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.280602, 0.015874 ), ( 0.99, 0.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.0 ), ( 0.508361, 0.05 ), ( 0.986622, 0.0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] )
]
),
SimBiConState(
name = 'State 1',
nextStateIndex = 1,
duration = 0.7,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.0, 0.0 ) ],
forceY = [ ( 0.0, 0.0 ) ],
forceZ = [ ( 0.0, 0.0 ) ],
torqueX = [ ],
torqueY = [ ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.0, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.5804 ),
( 0.22408, 0.862791 ),
( 0.431438, -0.048689 ),
( 0.688963, -0.71086 ),
( 0.986622, -0.782532 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1.0, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1.0, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.00034 ), ( 0.505017, -0.100323 ), ( 0.986622, -0.001158 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.280602, 0.015874 ), ( 0.99, 0.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.0 ), ( 0.508361, 0.05 ), ( 0.986622, 0.0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] )
]
)
]
) | [
[
1,
0,
0.0026,
0.0026,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5039,
0.9948,
0,
0.66,
1,
929,
3,
3,
0,
0,
597,
10,
90
]
] | [
"from App.Proxys import *",
"data = SimBiController( \n\n name = 'Turning',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),\n ControlParams( joint = 'pelvis_torso', kp = 200.0, kd = 30.0, tauMax = 10000.0, scal... |
from App.Proxys import *
data = SimBiController(
name = 'Jumping',
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 1000.0, kd = 100.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State0',
nextStateIndex = 1,
transitionOn = 'TIME_UP',
duration = 2.0,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.0, 0.0 ) ],
forceY = [
( 0.220257139643, -0.297893823029 ),
( 0.269866998824, 4009.37843155 ),
( 0.323865606442, -0.297893823029 ) ],
forceZ = [
( 0.22457639404, 0.230547728033 ),
( 0.312787202786, 1969.12899193 ),
( 0.340594719742, 0.281229318864 ) ],
torqueX = [
( 0.336683417085, 0.026145829397 ),
( 0.388500473607, -54.4526060901 ),
( 0.448698407471, -3.77495360492 ),
( 0.677040782713, -1.51348004883 ),
( 0.878199541855, -0.759655530132 ),
( 1.03586451524, -30.912636278 ) ],
torqueY = [
( 0.361809045226, -0.0251256281407 ),
( 0.429548422996, -8.20440959163 ),
( 0.474930850007, -0.0223053848099 ) ],
torqueZ = [
( 0.336683417085, 0.0753768844221 ),
( 0.416682339801, -13.6502244593 ),
( 0.462311557789, 0.0251256281407 ) ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.488294, 0.113631 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.197367186158, -0.311997836151 ),
( 0.29648241206, -2.0351758794 ),
( 0.557788944724, -1.03015075377 ),
( 0.663316582915, -0.929648241206 ),
( 1.06507609055, 0.082112161635 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.06 ), ( 0.5, -0.06 ), ( 1.0, -0.06 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.195969899497, -1.08040201005 ),
( 0.195979899497, 0.0251256281407 ),
( 0.43216080402, 0.0753768844221 ),
( 0.984924623116, -1.08040201005 ) ] ),
TrajectoryComponent( rotationAxis = ( 0.0, 0.0, 1.0 ), reverseOnStance = 'LEFT', baseTrajectory = [ ( 0.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.336683417085, 1.4824120603 ), ( 0.552763819095, 0.175879396985 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.16105827842, 0.873209081588 ),
( 0.224457449363, 0.0138604616125 ),
( 0.43216080402, 0.0753768844221 ),
( 0.723618090452, 1.93467336683 ),
( 0.989949748744, 0.879396984925 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.020067, 0.809573 ),
( 0.197324, -0.510418 ),
( 0.27135678392, -0.326633165829 ),
( 0.658291457286, 0.376884422111 ),
( 0.994974874372, 0.527638190955 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.211055276382, -0.326633165829 ), ( 0.261306532663, 0.577889447236 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.327759, 1.733668 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0301, -0.005792 ), ( 0.41806, -0.277104 ), ( 0.973244, -0.017375 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.006689, -0.025126 ), ( 0.505017, -0.138526 ), ( 0.996656, -0.025126 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.110368, 1.884422 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.023411, 0.003989 ), ( 0.471572, 0.243329 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.013378, 0.005066 ), ( 0.448161, 0.321392 ), ( 0.993311, 0.025126 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ( 0.307692, 2.135678 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.307692, 2.573897 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ( 0.364548, 2.98995 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.013378, -2.665055 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.598662, 0.138959 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.685619, 0.026046 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.692308, 0.025126 ), ( 0.856187, -1.532663 ) ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.38796, 0.014868 ), ( 0.826087, -0.431185 ) ] ) ] )
]
),
SimBiConState(
name = 'State1',
nextStateIndex = 1,
transitionOn = 'TIME_UP',
duration = 0.4,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.0, 0.0 ) ],
forceY = [ ( 0.0, 0.0 ) ],
forceZ = [ ( 0.0, 0.0 ) ],
torqueX = [ ],
torqueY = [ ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.488294, 0.113631 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.55, cv = -0.3 ),
baseTrajectory = [ ( 0.541806, -0.438308 ), ( 0.692308, -0.362199 ), ( 0.859532, -0.160317 ), ( 0.996656, 0.200194 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.0, -0.06 ), ( 0.5, -0.06 ), ( 1.0, -0.06 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.528428, 1.658482 ), ( 0.80602, 1.006429 ), ( 0.983278, 0.354748 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.147157, 0.130628 ),
( 0.394649, 0.318731 ),
( 0.61204, 0.29114 ),
( 0.832776, 0.236208 ),
( 0.989967, 0.576787 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.020067, 0.809573 ),
( 0.197324, -0.510418 ),
( 0.488294, -0.518456 ),
( 0.75, -0.5 ),
( 0.751, -0.15 ),
( 1.0, -0.15 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.354515, -0.354772 ), ( 0.625418, 0.764028 ), ( 0.749164, 1.163781 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.327759, 1.733668 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0301, -0.005792 ), ( 0.41806, -0.277104 ), ( 0.973244, -0.017375 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.006689, -0.025126 ), ( 0.505017, -0.138526 ), ( 0.996656, -0.025126 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.110368, 1.884422 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.023411, 0.003989 ), ( 0.471572, 0.243329 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.013378, 0.005066 ), ( 0.448161, 0.321392 ), ( 0.993311, 0.025126 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ( 0.307692, 2.135678 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.307692, 2.573897 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ( 0.364548, 2.98995 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.013378, -2.665055 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.598662, 0.138959 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.685619, 0.026046 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.692308, 0.025126 ), ( 0.856187, -1.532663 ) ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.38796, 0.014868 ), ( 0.826087, -0.431185 ) ] ) ] )
]
)
]
) | [
[
1,
0,
0.0024,
0.0024,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5036,
0.9952,
0,
0.66,
1,
929,
3,
3,
0,
0,
597,
10,
99
]
] | [
"from App.Proxys import *",
"data = SimBiController( \n\n name = 'Jumping',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),\n ControlParams( joint = 'pelvis_torso', kp = 1000.0, kd = 100.0, tauMax = 10000.0, sc... |
'''
Created on 2009-09-09
@author: beaudoin
'''
from App.Proxys import *
data = SimBiController(
name = 'Walking',
startingState = 0,
controlParamsList = [
ControlParams( joint = 'root', kp = 3000, kd = 300, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'pelvis_torso', kp = 200, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lHip', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.66, 1 ) ),
ControlParams( joint = 'rHip', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.66, 1 ) ),
ControlParams( joint = 'torso_head', kp = 200, kd = 20, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lShoulder', kp = 20, kd = 5, tauMax = 10000, scale = ( 0.5, 1, 1 ) ),
ControlParams( joint = 'rShoulder', kp = 20, kd = 5, tauMax = 10000, scale = ( 0.3, 1, 1 ) ),
ControlParams( joint = 'lKnee', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'rKnee', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lElbow', kp = 5, kd = 1, tauMax = 10000, scale = ( 0.2, 1, 1 ) ),
ControlParams( joint = 'rElbow', kp = 5, kd = 1, tauMax = 10000, scale = ( 0.2, 1, 1 ) ),
ControlParams( joint = 'lAnkle', kp = 75, kd = 10, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 75, kd = 10, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 10, kd = 0.5, tauMax = 10000, scale = ( 1, 1, 1 ) ),
ControlParams( joint = 'rToeJoint', kp = 10, kd = 0.5, tauMax = 10000, scale = ( 1, 1, 1 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
transitionOn = 'FOOT_CONTACT',
stance = 'REVERSE',
duration = 0.7,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [(0,0)],
forceY = [(0,0)],
forceZ = [(0,0)] )
],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0, 1 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0, 1 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
feedback = LinearBalanceFeedback( axis = ( 0, 0, 1 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1, 0, 0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1, 0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0, 1 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0, 1.5804 ),
( 0.22408, 0.862791 ),
( 0.431438, -0.048689 ),
( 0.688963, -0.71086 ),
( 0.986622, -0.782532 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
feedback = LinearBalanceFeedback( axis = ( 0, 0, 1 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0, 1.57 ), ( 1, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0, 1.57 ), ( 1, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.00034 ), ( 0.505017, -0.100323 ), ( 0.986622, -0.001158 ) ] ),
TrajectoryComponent( rotationAxis = ( 1, 0, 0 ), baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0, 0 ), ( 0.280602, 0.015874 ), ( 0.99, 0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0 ), ( 0.508361, 0.05 ), ( 0.986622, 0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1, 0, 0 ) ) ] )
]
)
]
)
| [
[
8,
0,
0.0146,
0.0244,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0341,
0.0049,
0,
0.66,
0.5,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.522,
0.961,
0,
0.66,
... | [
"'''\nCreated on 2009-09-09\n\n@author: beaudoin\n'''",
"from App.Proxys import *",
"data = SimBiController( \n\n name = 'Walking',\n\n startingState = 0,\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 3000, kd = 300, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.