예제 #1
0
 def __init__(self):
     # a dynamic world, moving objects or objects which react to other objects should be placed here
     self.dynamic_world = BulletWorld()
     CollisionGroup.set_collision_rule(self.dynamic_world)
     self.dynamic_world.setGravity(Vec3(0, 0, -9.81))  # set gravity
     # a static world which used to query position/overlap .etc. Don't implement doPhysics() in this world
     self.static_world = BulletWorld()
예제 #2
0
    def __init__(self, objpath, handpkg, gdb):
        self.objtrimesh = trimesh.load_mesh(objpath)
        self.objcom = self.objtrimesh.center_mass
        self.objtrimeshconv = self.objtrimesh.convex_hull
        # oc means object convex
        self.ocfacets, self.ocfacetnormals = self.objtrimeshconv.facets_over(
            .9999)

        # for dbaccess
        self.dbobjname = os.path.splitext(os.path.basename(objpath))[0]

        # use two bulletworld, one for the ray, the other for the tabletop
        self.bulletworldray = BulletWorld()
        self.bulletworldhp = BulletWorld()
        # plane to remove hand
        self.planebullnode = cd.genCollisionPlane(offset=0)
        self.bulletworldhp.attachRigidBody(self.planebullnode)

        self.handpkg = handpkg
        self.handname = handpkg.getHandName()
        self.hand = handpkg.newHandNM(hndcolor=[0, 1, 0, .1])
        # self.rtq85hnd = rtq85nm.Rtq85NM(hndcolor=[1, 0, 0, .1])

        # for dbsave
        # each tpsmat4 corresponds to a set of tpsgripcontacts/tpsgripnormals/tpsgripjawwidth list
        self.tpsmat4s = None
        self.tpsgripcontacts = None
        self.tpsgripnormals = None
        self.tpsgripjawwidth = None

        # for ocFacetShow
        self.counter = 0

        self.gdb = gdb
        self.loadFreeAirGrip()
예제 #3
0
    def __init__(self, objpath,objpathWorkcell, handpkg, dbidstablepos,readser):
        self.dbobjname = os.path.splitext(os.path.basename(objpath))[0]

        self.objtrimesh=None

        self.dbidstablepos = dbidstablepos

        [objrotmat, objposmat]=self.loadDropStablePos()
        self.loadObjModel(objpath,objrotmat,objposmat)

        self.objcom = self.objtrimesh.center_mass
        self.objtrimeshconv=self.objtrimesh.convex_hull
        # oc means object convex
        self.ocfacets, self.ocfacetnormals = self.objtrimeshconv.facets_over(.9999)

        # for dbaccess

        # use two bulletworld, one for the ray, the other for the tabletop
        self.bulletworldray = BulletWorld()
        self.bulletworldhp = BulletWorld()
        # plane to remove hand
        self.planebullnode = cd.genCollisionPlane(offset=-55)
        self.bulletworldhp.attachRigidBody(self.planebullnode)


        #workcell to remove hand

        self.workcellmesh = trimesh.load_mesh(objpathWorkcell)
        self.objgeom = pandageom.packpandageom(self.workcellmesh.vertices, self.workcellmesh.face_normals,
                                               self.workcellmesh.faces)
        self.objmeshbullnode = cd.genCollisionMeshGeom(self.objgeom)
        self.bulletworldhp.attachRigidBody(self.objmeshbullnode)
        node = GeomNode('obj')
        node.addGeom(self.objgeom)
        self.worcell = NodePath('obj')
        self.worcell.attachNewNode(node)
        self.worcell.reparentTo(base.render)


        self.handpkg = handpkg
        self.handname = handpkg.getHandName()
        self.hand = handpkg.newHandNM(hndcolor=[0,1,0,.1])
        # self.rtq85hnd = rtq85nm.Rtq85NM(hndcolor=[1, 0, 0, .1])

        # for dbsave
        # each tpsmat4 corresponds to a set of tpsgripcontacts/tpsgripnormals/tpsgripjawwidth list
        self.tpsmat4s = None
        self.tpsgripcontacts = None
        self.tpsgripnormals = None
        self.tpsgripjawwidth = None

        # for ocFacetShow
        self.counter = 0

        self.gdb = gdb
        #get dropfreegrip

        self.loadDropfreeGrip()
예제 #4
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-3, 0, 4)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(0, 0, 0)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Slider
        frameA = TransformState.make_pos_hpr(LPoint3(2, 0, 0),
                                             LVector3(0, 0, 45))
        frameB = TransformState.make_pos_hpr(LPoint3(0, -3, 0),
                                             LVector3(0, 0, 0))

        slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True)
        slider.set_debug_draw_size(2.0)
        slider.set_lower_linear_limit(0)
        slider.set_upper_linear_limit(6)
        slider.set_lower_angular_limit(-60)
        slider.set_upper_angular_limit(60)
        self.world.attach(slider)
def test_sphere_into_heightfield():
    root = NodePath("root")
    world = BulletWorld()
    # Create PNMImage to construct Heightfield with
    img = PNMImage(10, 10, 1)
    img.fill_val(255)
    # Make our nodes
    heightfield = make_node("Heightfield", BulletHeightfieldShape, img, 1, ZUp)
    sphere = make_node("Sphere", BulletSphereShape, 1)
    # Attach to world
    np1 = root.attach_new_node(sphere)
    np1.set_pos(0, 0, 1)
    world.attach(sphere)

    np2 = root.attach_new_node(heightfield)
    np2.set_pos(0, 0, 0)
    world.attach(heightfield)

    assert world.get_num_rigid_bodies() == 2
    test = world.contact_test_pair(sphere, heightfield)
    assert test.get_num_contacts() > 0
    assert test.get_contact(0).get_node0() == sphere
    assert test.get_contact(0).get_node1() == heightfield

    # Increment sphere's Z coordinate, no longer colliding
    np1.set_pos(0, 0, 2)
    test = world.contact_test_pair(sphere, heightfield)
    assert test.get_num_contacts() == 0
예제 #6
0
 def __init__(self,
              camera,
              debug=False,
              audio3d=None,
              client=None,
              server=None):
     self.objects = {}
     self.incarnators = []
     self.collidables = set()
     self.updatables = set()
     self.updatables_to_add = set()
     self.garbage = set()
     self.render = NodePath('world')
     self.camera = camera
     self.audio3d = audio3d
     self.ambient = self._make_ambient()
     self.celestials = CompositeObject()
     self.sky = self.attach(Sky())
     # Set up the physics world. TODO: let maps set gravity.
     self.gravity = DEFAULT_GRAVITY
     self.physics = BulletWorld()
     self.physics.set_gravity(self.gravity)
     self.debug = debug
     self.client = client
     self.server = server
     if debug:
         debug_node = BulletDebugNode('Debug')
         debug_node.show_wireframe(True)
         debug_node.show_constraints(True)
         debug_node.show_bounding_boxes(False)
         debug_node.show_normals(False)
         np = self.render.attach_new_node(debug_node)
         np.show()
         self.physics.set_debug_node(debug_node)
예제 #7
0
    def SetupBulletTerrain(self):
        self.worldNP = self.render.attachNewNode('World')
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))

        img = PNMImage(Filename(self.PngDEM))
        if self.MeterScale < 1.1:
            shape = BulletHeightfieldShape(img, self.HeightRange, ZUp)
        else:
            shape = BulletHeightfieldShape(img, self.HeightRange, ZUp)

        shape.setUseDiamondSubdivision(True)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Heightfield'))
        np.node().addShape(shape)

        offset = self.MeterScale * self.PixelNr / 2.0
        np.setPos(+offset, +offset,
                  +(self.HeightRange / 2.0) + self.OffsetHeight)

        np.setSx(self.MeterScale)
        np.setSy(self.MeterScale)
        np.setCollideMask(BitMask32.allOn())

        self.world.attachRigidBody(np.node())
예제 #8
0
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Plane
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

        # collision
        visNP = loader.loadModel('../models/coryf2.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(render)
        pos = (7., 60.0, 3.8)
        visNP.setPos(pos[0], pos[1], pos[2])

        bodyNPs = BulletHelper.fromCollisionSolids(visNP, True)
        for bodyNP in bodyNPs:
            bodyNP.reparentTo(render)
            bodyNP.setPos(pos[0], pos[1], pos[2])

            if isinstance(bodyNP.node(), BulletRigidBodyNode):
                bodyNP.node().setMass(0.0)
                bodyNP.node().setKinematic(True)
                bodyNP.setCollideMask(BitMask32.allOn())
                self.world.attachRigidBody(bodyNP.node())
예제 #9
0
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), -1)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
    np.node().addShape(shape)
    np.setPos(0, 0, -1)
    np.setCollideMask(BitMask32.bit(0))

    self.world.attachRigidBody(np.node())

    # Boxes
    self.boxes = [None,]*6

    for i in range(6):
      shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-1'))
      np.node().setMass(1.0)
      np.node().addShape(shape)

      self.world.attachRigidBody(np.node())

      self.boxes[i] = np

      visualNP = loader.loadModel('models/box.egg')
      visualNP.reparentTo(np)

    self.boxes[0].setPos(-3, -3, 0)
    self.boxes[1].setPos( 0, -3, 0)
    self.boxes[2].setPos( 3, -3, 0)
    self.boxes[3].setPos(-3,  3, 0)
    self.boxes[4].setPos( 0,  3, 0)
    self.boxes[5].setPos( 3,  3, 0)

    self.boxes[0].setCollideMask(BitMask32.bit(1))
    self.boxes[1].setCollideMask(BitMask32.bit(2))
    self.boxes[2].setCollideMask(BitMask32.bit(3))
    self.boxes[3].setCollideMask(BitMask32.bit(1))
    self.boxes[4].setCollideMask(BitMask32.bit(2))
    self.boxes[5].setCollideMask(BitMask32.bit(3))

    self.boxNP = self.boxes[0]

    self.world.setGroupCollisionFlag(0, 1, True)
    self.world.setGroupCollisionFlag(0, 2, True)
    self.world.setGroupCollisionFlag(0, 3, True)

    self.world.setGroupCollisionFlag(1, 1, False)
    self.world.setGroupCollisionFlag(1, 2, True)
    def generate(self):
        DistributedObjectAI.generate(self)
        self.air.battleZones[self.zoneId] = self

        self.bspLoader = BSPLoader()
        self.bspLoader.setAi(True)
        self.bspLoader.setMaterialsFile("phase_14/etc/materials.txt")
        #self.bspLoader.setTextureContentsFile("phase_14/etc/texturecontents.txt")
        self.bspLoader.setServerEntityDispatcher(self)
        AvatarWatcher.zoneId = self.zoneId
        
        # Link up networked entities
        from src.coginvasion.szboss import (DistributedTriggerAI, DistributedFuncDoorAI,
                                            DistributedButtonAI, DistributedFuncRotatingAI, LogicCounter,
                                            HintsAI, InfoTimer, InfoBgmAI)
        from src.coginvasion.szboss.InfoPlayerStart import InfoPlayerStart
        self.bspLoader.linkServerEntityToClass("trigger_once",          DistributedTriggerAI.DistributedTriggerOnceAI)
        self.bspLoader.linkServerEntityToClass("trigger_multiple",      DistributedTriggerAI.DistributedTriggerMultipleAI)
        self.bspLoader.linkServerEntityToClass("func_door",             DistributedFuncDoorAI.DistributedFuncDoorAI)
        self.bspLoader.linkServerEntityToClass("func_button",           DistributedButtonAI.DistributedButtonAI)
        self.bspLoader.linkServerEntityToClass("func_rotating",         DistributedFuncRotatingAI.DistributedFuncRotatingAI)
        self.bspLoader.linkServerEntityToClass("logic_counter",         LogicCounter.LogicCounter)
        self.bspLoader.linkServerEntityToClass("info_hint_cover",       HintsAI.InfoHintCover)
        self.bspLoader.linkServerEntityToClass("info_timer",            InfoTimer.InfoTimer)
        self.bspLoader.linkServerEntityToClass("info_player_start",     InfoPlayerStart)
        self.bspLoader.linkServerEntityToClass("info_bgm",              InfoBgmAI.InfoBgmAI)
        
        self.physicsWorld = BulletWorld()
        self.physicsWorld.setGravity(Vec3(0, 0, -32.1740))
        self.bspLoader.setPhysicsWorld(self.physicsWorld)
예제 #11
0
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.show()

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Plane
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
        np.node().addShape(shape)
        np.setPos(0, 0, -1)
        np.setCollideMask(BitMask32.allOn())

        self.world.attachRigidBody(np.node())

        # initial vehicles
        self.vehicles = []
        #self.vehicles.append(basicVehicle(self,[13,2,0.5],18)) # [10,0.1,0.5] is vehicle start position
        self.vehicles.append(
            basicVehicle(self, [10, 0.1, 0.5],
                         18))  # [10,0.1,0.5] is vehicle start position
        sensor = basicSensor(self)  # initial sensor
        sensor.setVehicle(self.vehicles[0])
        self.vehicles[0].setSensor(sensor)
        self.vehicles[0].sensor.align()
        agent = basicAgent(50, 10.8, 15)  # initial agent
        agent.setVehicle(self.vehicles[0])
        self.vehicles[0].setAgent(agent)
예제 #12
0
    def __init__(self):
        ShowBase.__init__(self)
        # Bullet Physics Setup
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))

        shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        node = BulletRigidBodyNode('Ground')
        node.addShape(shape)
        ground_np = self.render.attachNewNode(node)
        ground_np.setPos(0, 0, -60)
        # noinspection PyArgumentList
        self.world.attach(node)

        # Mouse and Camera Setup
        self.disable_mouse()
        self.camera.set_pos(20, -150, 5)
        self.follow_np = self.render.attach_new_node('Follow')

        # Instructions
        self.add_instruction('(p) to generate a Plane', 0.06)
        self.add_instruction('(b) to generate a Cuboid/Box', 0.12)
        self.add_instruction('(s) to generate a Spheroid', 0.18)
        self.add_instruction('(c) to generate a Cylinder', 0.24)
        self.add_instruction('(f1) to toggle wireframe', 0.30)
        self.add_instruction('(esc) to exit', 0.36)
        # Input
        self.accept('escape', sys.exit, [0])
        self.accept('p', self.generate_plane)
        self.accept('b', self.generate_cuboid)
        self.accept('s', self.generate_spheroid)
        self.accept('c', self.generate_cylinder)
        self.accept('f1', self.toggle_wireframe)

        self.task_mgr.add(self.update, 'update')
예제 #13
0
    def __init__(self, scene, suncgDatasetRoot=None, debug=False, objectMode='box',
                 agentRadius=0.1, agentHeight=1.6, agentMass=60.0, agentMode='capsule'):

        super(Panda3dBulletPhysics, self).__init__()

        self.__dict__.update(scene=scene, suncgDatasetRoot=suncgDatasetRoot, debug=debug, objectMode=objectMode,
                             agentRadius=agentRadius, agentHeight=agentHeight, agentMass=agentMass, agentMode=agentMode)

        if suncgDatasetRoot is not None:
            self.modelCatMapping = ModelCategoryMapping(os.path.join(
                suncgDatasetRoot, "metadata", "ModelCategoryMapping.csv"))
        else:
            self.modelCatMapping = None

        self.bulletWorld = BulletWorld()
        self.bulletWorld.setGravity(Vec3(0, 0, -9.81))

        if debug:
            debugNode = BulletDebugNode('physic-debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(False)
            debugNode.showBoundingBoxes(True)
            debugNode.showNormals(False)
            self.debugNodePath = self.scene.scene.attachNewNode(debugNode)
            self.debugNodePath.show()
            self.bulletWorld.setDebugNode(debugNode)
        else:
            self.debugNodePath = None

        self._initLayoutModels()
        self._initAgents()
        self._initObjects()

        self.scene.worlds['physics'] = self
예제 #14
0
    def __init__(self, root_nodepath, world):
        self.world = BulletWorld()
        self.world.setGravity((0, 0, -9.81))

        self._timestep = 1 / world.tick_rate

        # # Seems that this does not function
        # on_contact_added = PythonCallbackObject(self._on_contact_added)
        # self.world.set_contact_added_callback(on_contact_added)
        # on_filter = PythonCallbackObject(self._filter_collision)
        # self.world.set_filter_callback(on_filter)

        self.listener = DirectObject()
        self.listener.accept('bullet-contact-added', self._on_contact_added)
        self.listener.accept('bullet-contact-destroyed', self._on_contact_removed)

        self.tracked_contacts = defaultdict(int)
        self.existing_collisions = set()

        # Debugging info
        debug_node = BulletDebugNode('Debug')
        debug_node.showWireframe(True)
        debug_node.showConstraints(True)
        debug_node.showBoundingBoxes(False)
        debug_node.showNormals(False)

        # Add to world
        self.debug_nodepath = root_nodepath.attachNewNode(debug_node)
        self.world.set_debug_node(debug_node)
        self.debug_nodepath.show()
예제 #15
0
파일: z1.py 프로젝트: t4nuj/3d-pathfinding
    def __init__(self):
        ShowBase.__init__(self)
        loadPrcFileData('', 'bullet-enable-contact-events true')

        world = BulletWorld()
        self.world = world
        world.setGravity(Vec3(0, 0, -9.81))
        base.cam.setPos(0,-50,1)

        # Cameras
        base.camNode.setActive(0)
        self.cam1 = base.makeCamera(base.win, displayRegion=(0,.5,0.5,1))
        self.cam2 = base.makeCamera(base.win, displayRegion=(.5,1,0.5,1))
        self.cam1.setPos(-10,-50,1)
        self.cam2.setPos(10,-50,1)
        # base.camList[0].setPos(0,-100, 1)

        # Plane
        shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        node = BulletRigidBodyNode('Ground')
        node.addShape(shape)
        np = render.attachNewNode(node)
        np.setPos(0, 0, 0)
        self.world.attachRigidBody(node)
        scene = loader.loadModel('Ground2/Ground2')
        scene.reparentTo(render)
        self.newGame()

        taskMgr.add(self.update, 'update')
예제 #16
0
    def __init__(self,
                 camera,
                 debug=False,
                 audio3d=None,
                 client=None,
                 server=None):
        self.objects = {}

        self.incarnators = []

        self.collidables = set()

        self.updatables = set()
        self.updatables_to_add = set()
        self.garbage = set()
        self.scene = NodePath('world')

        # Set up the physics world. TODO: let maps set gravity.
        self.gravity = DEFAULT_GRAVITY
        self.physics = BulletWorld()
        self.physics.set_gravity(self.gravity)

        self.debug = debug

        if debug:
            debug_node = BulletDebugNode('Debug')
            debug_node.show_wireframe(True)
            debug_node.show_constraints(True)
            debug_node.show_bounding_boxes(False)
            debug_node.show_normals(False)
            np = self.scene.attach_new_node(debug_node)
            np.show()
            self.physics.set_debug_node(debug_node)
예제 #17
0
    def setup(self):

        # World
        self.worldNP = render.attachNewNode("World")
        self.GUI = self.worldNP.attachNewNode("GUI")
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode("Debug"))
        self.debugNP.show()
        self.debugNP.node().showWireframe(True)
        self.debugNP.node().showConstraints(True)
        self.debugNP.node().showBoundingBoxes(False)
        self.debugNP.node().showNormals(True)

        self.setDefaults()
        self.addGUI()
        self.createCurve()

        self.world = BulletWorld()
        # self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setGravity(Vec3(0, 0, 0))
        self.world.setDebugNode(self.debugNP.node())

        # Plane (static)
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)
        nodePath = self.worldNP.attachNewNode(BulletRigidBodyNode("Ground"))
        nodePath.node().addShape(shape)
        nodePath.setPos(0, 0, 0)
        nodePath.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(nodePath.node())

        self.loadModel()
예제 #18
0
def bulletRayHit(pfrom, pto, geom):
    """
    NOTE: this function is quite slow
    find the nearest collision point between vec(pto-pfrom) and the mesh of nodepath

    :param pfrom: starting point of the ray, Point3
    :param pto: ending point of the ray, Point3
    :param geom: meshmodel, a panda3d datatype
    :return: None or Point3

    author: weiwei
    date: 20161201
    """

    bulletworld = BulletWorld()
    facetmesh = BulletTriangleMesh()
    facetmesh.addGeom(geom)
    facetmeshnode = BulletRigidBodyNode('facet')
    bullettmshape = BulletTriangleMeshShape(facetmesh, dynamic=True)
    bullettmshape.setMargin(1e-6)
    facetmeshnode.addShape(bullettmshape)
    bulletworld.attach(facetmeshnode)
    result = bulletworld.rayTestClosest(pfrom, pto)

    if result.hasHit():
        return result.getHitPos()
    else:
        return None
예제 #19
0
    def __init__(self):
        base.accept('f1', self.toggleDebug)

        self.debugNode = BulletDebugNode('Debug')
        self.debugNode.showWireframe(True)
        self.debugNode.showConstraints(True)
        self.debugNode.showBoundingBoxes(False)
        self.debugNode.showNormals(False)
        self.debugNP = base.render.attachNewNode(self.debugNode)
        # self.debugNP.show()

        # World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Terrain
        visNP = base.loader.loadModel('models/terrain.egg')

        mesh = BulletTriangleMesh()
        for x in visNP.findAllMatches('**/+GeomNode'):
            geom = x.node().getGeom(0)
            mesh.addGeom(geom)
        shape = BulletTriangleMeshShape(mesh, dynamic=True)

        body = BulletRigidBodyNode('Bowl')
        bodyNP = base.render.attachNewNode(body)
        bodyNP.node().addShape(shape)
        bodyNP.setPos(0, 0, 1)
        bodyNP.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(bodyNP.node())

        visNP.reparentTo(bodyNP)

        shapex = BulletBoxShape(5)
        bodyx = BulletRigidBodyNode('Egg')
        bodyNPx = base.render.attachNewNode(bodyx)
        bodyNPx.setPos(0, 0, 3)
        bodyNPx.node().setMass(100.0)
        bodyNPx.node().addShape(shapex)
        self.world.attachRigidBody(bodyNPx.node())
        # visNP.reparentTo(bodyNPx)

        # Player
        self.players = []
        self.myId = -1
        self.speed = Vec3(0, 0, 0)
        self.walk_speed = 2.5

        # Camera
        base.disableMouse()
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)

        # SkySphere
        Sky()

        self.initCam()
예제 #20
0
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

    #img = PNMImage(Filename('models/elevation2.png'))
    #shape = BulletHeightfieldShape(img, 1.0, ZUp)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
    np.node().addShape(shape)
    np.setPos(0, 0, -1)
    np.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(np.node())

    # Box
    shape = BulletBoxShape(Vec3(1.0, 3.0, 0.3))

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
    np.node().setMass(10.0)
    np.node().addShape(shape)
    np.setPos(3, 0, 4)
    np.setH(20.0)
    np.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(np.node())

    # Character
    self.crouching = False

    h = 1.75
    w = 0.4
    shape = BulletCapsuleShape(w, h - 2 * w, ZUp)

    self.character = BulletCharacterControllerNode(shape, 0.4, 'Player')
    # self.character.setMass(1.0)
    self.characterNP = self.worldNP.attachNewNode(self.character)
    self.characterNP.setPos(-2, 0, 14)
    self.characterNP.setH(45)
    self.characterNP.setCollideMask(BitMask32.allOn())
    self.world.attachCharacter(self.character)

    self.actorNP = Actor('models/ralph/ralph.egg', {
                         'run' : 'models/ralph/ralph-run.egg',
                         'walk' : 'models/ralph/ralph-walk.egg',
                         'jump' : 'models/ralph/ralph-jump.egg'})
    self.actorNP.reparentTo(self.characterNP)
    self.actorNP.setScale(0.3048) # 1ft = 0.3048m
    self.actorNP.setH(180)
    self.actorNP.setPos(0, 0, -1)
예제 #21
0
    def __init__(self, objpath, nxtrobot, handpkg, gdb):

        self.graphtpp0 = GraphTpp(objpath, nxtrobot, handpkg, gdb, 'rgt')
        self.armname = armname

        self.gdb = gdb
        self.robot = nxtrobot
        self.hand = handpkg.newHandNM(hndcolor=[1, 0, 0, .1])

        # plane to remove hand
        self.bulletworld = BulletWorld()
        self.planebullnode = cd.genCollisionPlane()
        self.bulletworld.attachRigidBody(self.planebullnode)

        # add tabletop plane model to bulletworld
        this_dir, this_filename = os.path.split(__file__)
        ttpath = Filename.fromOsSpecific(
            os.path.join(
                os.path.split(this_dir)[0] + os.sep, "grip", "supports",
                "tabletop.egg"))
        self.ttnodepath = NodePath("tabletop")
        ttl = loader.loadModel(ttpath)
        ttl.instanceTo(self.ttnodepath)

        # self.endnodeids is a dictionary where
        # self.endnodeids['rgt'] equals self.startnodeids
        # self.endnodeids['lft'] equals self.endnodeids # in right->left order
        self.endnodeids = {}

        # load retraction distances
        self.rethandx, self.retworldz, self.retworlda, self.worldz = self.gdb.loadIKRet(
        )
        # worlda is default for the general grasps on table top
        # for assembly at start and goal, worlda is computed by assembly planner
        self.worlda = Vec3(0, 0, 1)

        self.gnodesplotpos = {}

        self.freegripid = []
        self.freegripcontacts = []
        self.freegripnormals = []
        self.freegriprotmats = []
        self.freegripjawwidth = []

        # for start and goal grasps poses:
        radiusgrip = 1
        self.__xyzglobalgrippos_startgoal = {}
        for k, globalgripid in enumerate(self.graphtpp.globalgripids):
            xypos = [
                radiusgrip *
                math.cos(2 * math.pi / len(self.graphtpp.globalgripids) * k),
                radiusgrip *
                math.sin(2 * math.pi / len(self.graphtpp.globalgripids) * k)
            ]
            self.__xyzglobalgrippos_startgoal[globalgripid] = [
                xypos[0], xypos[1], 0
            ]

        self.__loadFreeAirGrip()
예제 #22
0
파일: physics.py 프로젝트: croxis/apollo
def getZone(zonex, zoney):
    if zonex not in worlds:
        worlds[zonex] = {}
    if zoney not in worlds[zonex]:
        worlds[zonex][zoney] = (BulletWorld(), NodePath('Zone ' + str(zonex) + str(zoney)))
        worlds[zonex][zoney][0].setGravity((0, 0, 0))
        log.debug("Zone added: " + str(zonex) + ", " + str(zoney))
    return worlds[zonex][zoney]
예제 #23
0
    def create_physics(self):
        """Create the physical world, and start a task to simulate physics"""

        self.world = BulletWorld()
        self.world.set_gravity((0, 0, -9.81))

        self.physics_on = False
        self.taskMgr.add(self.step_physics, "physics")
예제 #24
0
def task_1_Bullet_Hello_World():

    strOf_FuncName = "task_1_Bullet_Hello_World"

    '''###################
        step : 1
            opening, vars
    ###################'''
    print()
    
    print ("[%s:%d] starting : %s (time=%s)" % (
                os.path.basename(os.path.basename(libs.thisfile()))
                , libs.linenum()
                , strOf_FuncName
                , libs.get_TimeLabel_Now()
                )
    )
    
    '''###################
        step : 2
    ###################'''
    base.cam.setPos(0, -10, 0)
    base.cam.lookAt(0, 0, 0)
    
    # World
    world = BulletWorld()
    world.setGravity(Vec3(0, 0, -9.81))
    
    # Plane
    shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
    node = BulletRigidBodyNode('Ground')
    node.addShape(shape)
    np = render.attachNewNode(node)
    np.setPos(0, 0, -2)
    world.attachRigidBody(node)
    
    # Box
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))
    node = BulletRigidBodyNode('Box')
    node.setMass(1.0)
    node.addShape(shape)
    np = render.attachNewNode(node)
    np.setPos(0, 0, 2)
    world.attachRigidBody(node)
    model = loader.loadModel('models/box.egg')
    model.flattenLight()
    model.reparentTo(np)
    
    # Update
    def update(task):
        dt = globalClock.getDt()
        world.doPhysics(dt)
        return task.cont
    
    taskMgr.add(update, 'update')
    base.run()
    
    '''###################
예제 #25
0
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().showWireframe(True)
        self.debugNP.node().showConstraints(True)
        self.debugNP.node().showBoundingBoxes(False)
        self.debugNP.node().showNormals(False)

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attachNewNode(bodyA)
        bodyNP.node().addShape(shape)
        bodyNP.setCollideMask(BitMask32.allOn())
        bodyNP.setPos(-2, 0, 1)

        visNP = loader.loadModel('models/box.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(bodyNP)

        self.world.attachRigidBody(bodyA)

        # Box B
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attachNewNode(bodyB)
        bodyNP.node().addShape(shape)
        bodyNP.node().setMass(1.0)
        bodyNP.node().setDeactivationEnabled(False)
        bodyNP.setCollideMask(BitMask32.allOn())
        bodyNP.setPos(2, 0, 1)

        visNP = loader.loadModel('models/box.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(bodyNP)

        self.world.attachRigidBody(bodyB)

        # Hinge
        pivotA = Point3(2, 0, 0)
        pivotB = Point3(-4, 0, 0)
        axisA = Vec3(0, 0, 1)
        axisB = Vec3(0, 0, 1)

        hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA,
                                      axisB, True)
        hinge.setDebugDrawSize(2.0)
        hinge.setLimit(-90, 120, softness=0.9, bias=0.3, relaxation=1.0)
        self.world.attachConstraint(hinge)
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().showWireframe(True)
        self.debugNP.node().showConstraints(True)
        self.debugNP.node().showBoundingBoxes(False)
        self.debugNP.node().showNormals(False)

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attachNewNode(bodyA)
        bodyNP.node().addShape(shape)
        bodyNP.setCollideMask(BitMask32.allOn())
        bodyNP.setPos(-3, 0, 4)

        visNP = loader.loadModel('models/box.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(bodyNP)

        self.world.attachRigidBody(bodyA)

        # Box B
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attachNewNode(bodyB)
        bodyNP.node().addShape(shape)
        bodyNP.node().setMass(1.0)
        bodyNP.node().setDeactivationEnabled(False)
        bodyNP.setCollideMask(BitMask32.allOn())
        bodyNP.setPos(0, 0, 0)

        visNP = loader.loadModel('models/box.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(bodyNP)

        self.world.attachRigidBody(bodyB)

        # Slider
        frameA = TransformState.makePosHpr(Point3(2, 0, 0), Vec3(0, 0, 45))
        frameB = TransformState.makePosHpr(Point3(0, -3, 0), Vec3(0, 0, 0))

        slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True)
        slider.setDebugDrawSize(2.0)
        slider.setLowerLinearLimit(0)
        slider.setUpperLinearLimit(6)
        slider.setLowerAngularLimit(-60)
        slider.setUpperAngularLimit(60)
        self.world.attachConstraint(slider)
예제 #27
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Ground
        shape = BulletPlaneShape(LVector3(0, 0, 1), 0)

        #img = PNMImage(Filename('models/elevation.png'))
        #shape = BulletHeightfieldShape(img, 1.0, ZUp)

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Ground'))
        np.node().add_shape(shape)
        np.set_pos(0, 0, -1)
        np.set_collide_mask(BitMask32.all_on())

        self.world.attach(np.node())

        # Box
        shape = BulletBoxShape(LVector3(1.0, 3.0, 0.3))

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Box'))
        np.node().set_mass(10.0)
        np.node().add_shape(shape)
        np.set_pos(3, 0, 4)
        np.setH(20.0)
        np.set_collide_mask(BitMask32.all_on())

        self.world.attach(np.node())

        # Character
        self.crouching = False

        h = 1.75
        w = 0.4
        shape = BulletCapsuleShape(w, h - 2 * w, ZUp)
        self.character = BulletCharacterControllerNode(shape, 0.4, 'Player')
        self.characterNP = self.worldNP.attach_new_node(self.character)
        self.characterNP.set_pos(-2, 0, 14)
        self.characterNP.set_h(45)
        self.characterNP.set_collide_mask(BitMask32.all_on())
        self.world.attach(self.character)

        self.actorNP = Actor(
            'samples/roaming-ralph/models/ralph.egg.pz', {
                'run': 'samples/roaming-ralph/models/ralph-run.egg.pz',
                'walk': 'samples/roaming-ralph/models/ralph-walk.egg.pz'
            })
        self.actorNP.reparent_to(self.characterNP)
        self.actorNP.set_scale(0.3048)  # 1ft = 0.3048m
        self.actorNP.setH(180)
        self.actorNP.set_pos(0, 0, -1)
예제 #28
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-2, 0, 1)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(2, 0, 1)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Hinge
        pivotA = LPoint3(2, 0, 0)
        pivotB = LPoint3(-4, 0, 0)
        axisA = LVector3(0, 0, 1)
        axisB = LVector3(0, 0, 1)

        hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA,
                                      axisB, True)
        hinge.set_debug_draw_size(2.0)
        hinge.set_limit(-90, 120, softness=0.9, bias=0.3, relaxation=1.0)
        self.world.attach(hinge)
예제 #29
0
def genAvailableFAGsSgl(base, basepath, baseMat4, objpath, objMat4, gdb, handpkg):
    """
    find the collision freeairgrips of objpath without considering rotation

    :param base: panda base
    :param basepath: the path of base object
    :param objpath: the path of obj object, the object to be assembled
    :param baseMat4, objMat4: all in world coordinates, not relative
    :param gdb: grasp db
    :param handpkg: hand package
    :return: [assgripcontacts, assgripnormals, assgriprotmat4s, assgripjawwidth, assgripidfreeair]

    author: weiwei
    date: 20170307
    """

    bulletworld = BulletWorld()

    robothand = handpkg.newHandNM(hndcolor=[1, 0, 0, .1])

    basetrimesh = trimesh.load_mesh(basepath)
    basenp = pg.packpandanp(basetrimesh.vertices, basetrimesh.face_normals, basetrimesh.faces)
    basenp.setMat(baseMat4)
    basebullnode = cd.genCollisionMeshNp(basenp, base.render)

    bulletworld.attachRigidBody(basebullnode)

    dbobjname = os.path.splitext(os.path.basename(objpath))[0]
    objfag = F*g(gdb, dbobjname, handpkg)

    assgripcontacts = []
    assgripnormals = []
    assgriprotmat4s = []
    assgripjawwidth = []
    assgripidfreeair = []
    for i, rotmat in enumerate(objfag.freegriprotmats):
        assgrotmat = rotmat*objMat4
        robothand.setMat(assgrotmat)
        # detect the collisions when hand is open!
        robothand.setJawwidth(robothand.jawwidthopen)
        hndbullnode = cd.genCollisionMeshMultiNp(robothand.handnp)
        result0 = bulletworld.contactTest(hndbullnode)
        robothand.setJawwidth(objfag.freegripjawwidth[i])
        hndbullnode = cd.genCollisionMeshMultiNp(robothand.handnp)
        result1 = bulletworld.contactTest(hndbullnode)
        if (not result0.getNumContacts()) and (not result1.getNumContacts()):
            cct0 = objMat4.xformPoint(objfag.freegripcontacts[i][0])
            cct1 = objMat4.xformPoint(objfag.freegripcontacts[i][1])
            cctn0 = objMat4.xformPoint(objfag.freegripnormals[i][0])
            cctn1 = objMat4.xformPoint(objfag.freegripnormals[i][1])
            assgripcontacts.append([cct0, cct1])
            assgripnormals.append([cctn0, cctn1])
            assgriprotmat4s.append(assgrotmat)
            assgripjawwidth.append(objfag.freegripjawwidth[i])
            assgripidfreeair.append(objfag.freegripids[i])

    return [assgripcontacts, assgripnormals, assgriprotmat4s, assgripjawwidth, assgripidfreeair]
예제 #30
0
    def __init__(self):
        from panda3d.bullet import BulletWorld
        self._world = BulletWorld()
        self._world.set_gravity(0, 0, -9.807)

        self.tick_rate = None
        self.time = 0.0

        self._rigid_bodies = {}