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)
        body = BulletRigidBodyNode('Ground')
        bodyNP = self.worldNP.attachNewNode(body)
        bodyNP.node().addShape(shape)
        bodyNP.setPos(0, 0, -1)
        bodyNP.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(bodyNP.node())

        # Some boxes
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        for i in range(10):
            for j in range(10):
                x = i - 5.0
                y = 0.0
                z = j - 0.5

                body = BulletRigidBodyNode('Box-%i-%i' % (i, j))
                bodyNP = self.worldNP.attachNewNode(body)
                bodyNP.node().addShape(shape)
                bodyNP.node().setMass(1.0)
                bodyNP.node().setDeactivationEnabled(False)
                bodyNP.setPos(x, y, z)
                bodyNP.setCollideMask(BitMask32.allOn())

                self.world.attachRigidBody(bodyNP.node())

                visNP = loader.loadModel('models/box.egg')
                visNP.clearModelNodes()
                visNP.reparentTo(bodyNP)
Ejemplo n.º 2
0
    def __init__(self):
        ShowBase.__init__(self)
        self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
        self.plight = PointLight('plight')
        self.pnlp = self.camera.attachNewNode(self.plight)
        render.setLight(self.pnlp)

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

        self.world = BulletWorld()
        self.world.setDebugNode(self.debugNode)

        self.planet = Planet()
        self.planet.perlin_terrain(5, 0.5)
        self.planet.build_node_path(render, self.world)

        shape = BulletCapsuleShape(0.25, 0.5)
        node = BulletRigidBodyNode('Capsule')
        node.addShape(shape)
        np = render.attachNewNode(node)
        np.setPos(Vec3(0, 0.8, 0.8) * self.planet.get_radius())
        new_up_vector = Vec3(np.getPos() -
                             self.planet.get_node_path().getPos())
        old_up_vector = Vec3(0, 0, 1)
        q = self.__quatFromTo(old_up_vector, new_up_vector)
        np.setQuat(q)

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

        #node.applyCentralImpulse(Vec3(0.4, 0.6, 1.0))

        self.taskMgr.add(self.physicsUpdateTask, "PhysicsUpdateTask")

        self.accept('arrow_up', self.test01, ["shalala"])
Ejemplo n.º 3
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())

        # CHÃO
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)
        body = BulletRigidBodyNode('Ground')
        bodyNP = self.worldNP.attachNewNode(body)
        bodyNP.node().addShape(shape)
        bodyNP.setPos(0, 0, -1)
        bodyNP.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(bodyNP.node())

        self.criaPopulacao()
Ejemplo n.º 4
0
    def setupPhysics(self, **kwargs):
        self.debugNP = kwargs['world'].attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().showNormals(True)

        mesh = BulletTriangleMesh()

        geomlist = self.model.findAllMatches('**/+GeomNode')
        geom = geomlist[0].node().getGeom(0)
        mesh.addGeom(geom)

        shape = BulletPlaneShape(Vec3(0, 0, 0), 0)
        node = BulletRigidBodyNode('arena')
        node.addShape(shape)

        triangle = BulletTriangleMeshShape(mesh, dynamic=False)
        node1 = BulletRigidBodyNode('wall')
        node1.addShape(triangle)
        self.wallNp = kwargs['world'].attachNewNode(node1)
        self.mainNp = kwargs['world'].attachNewNode(node)

        self.mainNp.setCollideMask(kwargs['mask'])
Ejemplo n.º 5
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())

        self.vehicles = dict()
Ejemplo n.º 6
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())
        self.world.set_filter_callback(PythonCallbackObject(self.filter))

        # Ground
        shape = BulletPlaneShape(LVector3(0, 0, 1), -1)
        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Ground'))
        np.node().add_shape(shape)
        np.set_pos(0, 0, -1)
        np.set_python_tag('foo', 2)
        self.world.attach(np.node())

        # Box 1
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))
        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Box-1'))
        np.node().set_mass(1.0)
        np.node().add_shape(shape)
        np.set_pos(3, 0, 4)
        np.set_python_tag('foo', 0)
        self.world.attach(np.node())
        self.boxNP = np

        # Box 2
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))
        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Box-2'))
        np.node().set_mass(1.0)
        np.node().add_shape(shape)
        np.set_pos(-3, 0, 4)
        np.set_python_tag('foo', -1)
        self.world.attach(np.node())
Ejemplo n.º 7
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())
        self.world.setPythonFilterCallback(self.filter)

        # Ground
        shape = BulletPlaneShape(Vec3(0, 0, 1), -1)
        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
        np.node().addShape(shape)
        np.setPos(0, 0, -1)
        np.setPythonTag('foo', 2)
        self.world.attachRigidBody(np.node())

        # Box 1
        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)
        np.setPos(3, 0, 4)
        np.setPythonTag('foo', 0)
        self.world.attachRigidBody(np.node())
        self.boxNP = np

        # Box 2
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))
        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-2'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(-3, 0, 4)
        np.setPythonTag('foo', -1)
        self.world.attachRigidBody(np.node())
Ejemplo n.º 8
0
def invoke(scene, data, action):
    if action == 'LOAD':
        scene.phys_world = BulletWorld()
        scene.phys_world.setGravity(Vec3(0, 0, -data['phys_gravity']))

        if 'bullet_debug' in scene.flags and scene.flags['bullet_debug']:
            # --- debug ---
            debugNode = BulletDebugNode('PhysDebug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            debugNP = render.attachNewNode(debugNode)
            debugNP.show()
            scene.phys_world.setDebugNode(debugNode)
            # --- debug end ---

        #taskMgr.add(update, 'physics-update', extraArgs=[scene, data['phys_step_sub'], 1.0/data['phys_fps']])
        taskMgr.doMethodLater(
            2,
            update,
            'physics-update',
            extraArgs=[scene, data['phys_step_sub'], 1.0 / data['phys_fps']])
Ejemplo n.º 9
0
    def initBullet(self):
        """Initializes the Bullet physics engine, also adds the updatePhysicsTask to the task manager."""
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, 0))

        # add ground
        node = BulletRigidBodyNode("Ground")  # derived from PandaNode
        node.addShape(BulletPlaneShape(Vec3(0, 0, 1), 0))
        np = self.render.attachNewNode(node)
        np.setPos(0, 0, 0)
        self.world.attachRigidBody(node)

        # add debug node
        debugNode = BulletDebugNode("Debug")
        debugNode.showWireframe(False)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(True)
        debugNP = self.render.attachNewNode(debugNode)
        debugNP.show()
        self.world.setDebugNode(debugNP.node())

        self.taskMgr.add(self.updatePhysicsTask, "UpdatePhysics")
Ejemplo n.º 10
0
    def __init__(self, xml):
        globalClock.setMaxDt(0.1)
        #init pre and post callbacks
        self.prePhysics = {}
        self.postPhysics = {}

        #bullet debug node
        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(True)
        debugNP = render.attachNewNode(debugNode)
        debugNP.show()

        #create bullet world
        self.bulletworld = BulletWorld()
        self.bulletworld.setDebugNode(debugNP.node())
        self.bulletworld.setGravity(Vec3(0, 0, 0))

        #start doing physics
        self.physicsTask = taskMgr.add(self.simulationTask,
                                       'Physics Loop',
                                       sort=100)
    def setup(self):        
        # Bullet physics world
        self.worldNP = render.attach_new_node('World')
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Vehicle
        # Steering info
        self.steering = 0.0              # degrees
        self.steering_clamp = 45.0       # degrees
        self.steering_increment = 120.0  # degrees per second        
        # How fast steering relaxes to straight ahead
        self.steering_relax_factor = 2.0
        # How much steering intensity decreases with higher speeds
        self.steering_speed_reduction_factor = 0.003
        
        # Chassis collision box (note: Bullet uses half-measures)
        shape = BulletBoxShape(LVector3(0.6, 1.4, 0.5))
        ts = TransformState.make_pos(LPoint3(0, 0, 0.5))
        self.vehicleNP = self.worldNP.attach_new_node(
            BulletRigidBodyNode('Vehicle'))
        self.vehicleNP.node().add_shape(shape, ts)
        # Set initial position
        self.vehicleNP.set_pos(0, 70, -10)
        self.vehicleNP.node().set_mass(800.0)
        self.vehicleNP.node().set_deactivation_enabled(False)
        self.world.attach(self.vehicleNP.node())
        # Camera floater
        self.attach_camera_floater()
        # BulletVehicle
        self.vehicle = BulletVehicle(self.world, self.vehicleNP.node())
        self.world.attach(self.vehicle)
        
        # Vehicle model
        self.yugoNP = loader.load_model('models/yugo/yugo.egg')
        self.yugoNP.reparent_to(self.vehicleNP)
        # Right front wheel
        np = loader.load_model('models/yugo/yugotireR.egg')
        np.reparent_to(self.worldNP)
        self.add_wheel(LPoint3( 0.70,  1.05, 0.3), True, np)
        # Left front wheel
        np = loader.load_model('models/yugo/yugotireL.egg')
        np.reparent_to(self.worldNP)
        self.add_wheel(LPoint3(-0.70,  1.05, 0.3), True, np)
        # Right rear wheel
        np = loader.load_model('models/yugo/yugotireR.egg')
        np.reparent_to(self.worldNP)
        self.add_wheel(LPoint3( 0.70, -1.05, 0.3), False, np)
        # Left rear wheel
        np = loader.load_model('models/yugo/yugotireL.egg')
        np.reparent_to(self.worldNP)
        self.add_wheel(LPoint3(-0.70, -1.05, 0.3), False, np)
        
        # Load a skybox
        self.skybox = self.loader.load_model(
            "samples/shader-terrain/models/skybox.bam")
        self.skybox.reparent_to(self.render)
        self.skybox.set_scale(20000)
        skybox_texture = self.loader.load_texture(
            "samples/shader-terrain/textures/skybox.jpg")
        skybox_texture.set_minfilter(SamplerState.FT_linear)
        skybox_texture.set_magfilter(SamplerState.FT_linear)
        skybox_texture.set_wrap_u(SamplerState.WM_repeat)
        skybox_texture.set_wrap_v(SamplerState.WM_mirror)
        skybox_texture.set_anisotropic_degree(16)
        self.skybox.set_texture(skybox_texture)
        skybox_shader = Shader.load(Shader.SL_GLSL, 
            "samples/shader-terrain/skybox.vert.glsl", 
            "samples/shader-terrain/skybox.frag.glsl")
        self.skybox.set_shader(skybox_shader)

        # Terrain
        self.setup_terrain()
Ejemplo n.º 12
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())

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

        body = BulletRigidBodyNode('Ground')
        bodyNP = self.worldNP.attachNewNode(body)
        bodyNP.node().addShape(shape)
        bodyNP.setPos(0, 0, 0)
        bodyNP.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(bodyNP.node())

        # Bowl
        visNP = loader.loadModel('models/bowl.egg')

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

        body = BulletRigidBodyNode('Bowl')
        bodyNP = self.worldNP.attachNewNode(body)
        bodyNP.node().addShape(shape)
        bodyNP.node().setMass(10.0)
        bodyNP.setPos(0, 0, 0)
        bodyNP.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(bodyNP.node())

        visNP.reparentTo(bodyNP)

        self.bowlNP = bodyNP
        self.bowlNP.setScale(2)

        # Eggs
        self.eggNPs = []
        for i in range(5):
            x = random.gauss(0, 0.1)
            y = random.gauss(0, 0.1)
            z = random.gauss(0, 0.1) + 1
            h = random.random() * 360
            p = random.random() * 360
            r = random.random() * 360

            visNP = loader.loadModel('models/egg.egg')

            geom = visNP.findAllMatches('**/+GeomNode').getPath(
                0).node().getGeom(0)
            shape = BulletConvexHullShape()
            shape.addGeom(geom)

            body = BulletRigidBodyNode('Egg-%i' % i)
            bodyNP = self.worldNP.attachNewNode(body)
            bodyNP.node().setMass(1.0)
            bodyNP.node().addShape(shape)
            bodyNP.node().setDeactivationEnabled(False)
            bodyNP.setCollideMask(BitMask32.allOn())
            bodyNP.setPosHpr(x, y, z, h, p, r)
            #bodyNP.setScale(1.5)
            self.world.attachRigidBody(bodyNP.node())

            visNP.reparentTo(bodyNP)

            self.eggNPs.append(bodyNP)
Ejemplo n.º 13
0
	def __init__(self):
		GameBase.__init__(self, KEY_LIST)
		
		FSM.__init__(self, 'Game')
		self.setBackgroundColor(0,0,0)
		
		self.accept("space", self.toggleFPS)
		self.accept("escape", self.taskMgr.stop)
		
		
		'''
		self.shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
 
		self.node = BulletRigidBodyNode('Ground')
		self.node.addShape(self.shape)
		 
		self.np = self.render.attachNewNode(self.node)
		self.np.setPos(0, 0, 0)
		
		self.world.attachRigidBody(self.node)
		'''
		
		self.debugNode = BulletDebugNode('Debug')
		self.debugNode.showWireframe(True)
		self.debugNode.showConstraints(True)
		self.debugNode.showBoundingBoxes(True)
		self.debugNode.showNormals(True)
		self.debugNP = self.render.attachNewNode(self.debugNode)
		self.debugNP.show()
		
		
		self.bulletbox = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

		self.bulletboxnode = BulletRigidBodyNode('Box')
		self.bulletboxnode.setMass(1.0)
		self.bulletboxnode.addShape(self.bulletbox)
		 
		self.bulletboxnp = self.render.attachNewNode(self.bulletboxnode)
		#self.bulletboxnp = NodePath(self.bulletboxnode)
		#self.bulletboxnp.reparentTo(self.render)
		self.bulletboxnp.setPos(0, 0, 15)
		self.bulletboxnp.setScale(5,3,0.5)
		self.world.attachRigidBody(self.bulletboxnode)
		self.model = self.loader.loadModel("models/props/crate.egg")
		self.model.reparentTo(self.bulletboxnp)
		
		
		#---------------------------------------------------------------
		# Ground (StaticTerrain)
		self.ground = StaticTerrain(self, 'models/terrain.jpg', 50)
		self.ground.setTexture(self.loader.loadTexture("models/ground.jpg"))
		
		self.sky = SkyBox(self)
		self.sky.set("teal1")
		
		self.cursor = MouseCursor(self)
		self.cursor.addCursor("cursor2")
		
		self.hideCursor()
		self.lightManager = LightManager(self)
		self.lightManager.addAmbientLight(Vec4(.5,.5,.5,1))
		self.lightManager.addPointLight(Vec4(1.0,1.0,1.0,1.0), Point3(2,-4,5))
		self.taskMgr.add(self.update, "update")
		
		print self.getAspectRatio()
		
		self.camHandler = CamHandler(self)
		self.accept(K_DRAG, self.camHandler.startDrag)
		self.accept(K_DRAG+"-up", self.camHandler.stopDrag)
Ejemplo n.º 14
0
    def setup(self):

        self.targetAlt = r.randrange(100,300)
        self.Valves = np.array([0.15,0.2,0.15])
        self.EngObs = self.vulcain.predict_data_point(np.array(self.Valves).reshape(1,-1))

        if self.VISUALIZE is True:
            self.worldNP = self.render.attachNewNode('World')

        else:
            self.root = NodePath(PandaNode("world root"))
            self.worldNP = self.root.attachNewNode('World')






        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.80665))

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

        # self.debugNP.showTightBounds()
        # self.debugNP.showBounds()


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

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

        self.world.attachRigidBody(self.groundNP.node())

        # Rocket
        shape = BulletCylinderShape(self.radius, self.length, ZUp)

        self.rocketNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Cylinder'))
        self.rocketNP.node().setMass(27200 * self.scale)
        self.rocketNP.node().addShape(shape)
        #self.rocketNP.setPos(20,20,250)
        self.rocketNP.setPos(20, 20, r.randrange(100, 300)+200)
        #self.rocketNP.setPos(r.randrange(-self.lateralError, self.lateralError, 1), r.randrange(-self.lateralError, self.lateralError, 1), self.height)
        # self.rocketNP.setPos(0, 0, self.length*10)
        self.rocketNP.setCollideMask(BitMask32.allOn())
        # self.rocketNP.node().setCollisionResponse(0)
        self.rocketNP.node().notifyCollisions(True)

        self.world.attachRigidBody(self.rocketNP.node())

        for i in range(4):
            leg = BulletCylinderShape(0.1 * self.radius, 0.5 * self.length, XUp)
            self.rocketNP.node().addShape(leg, TransformState.makePosHpr(
                Vec3(6 * self.radius * math.cos(i * math.pi / 2), 6 * self.radius * math.sin(i * math.pi / 2),
                     -0.6 * self.length), Vec3(i * 90, 0, 30)))

        shape = BulletConeShape(0.75 * self.radius, 0.5 * self.radius, ZUp)
        self.rocketNP.node().addShape(shape, TransformState.makePosHpr(Vec3(0, 0, -1 / 2 * self.length), Vec3(0, 0, 0)))

        # Fuel
        self.fuelRadius = 0.9 * self.radius
        shape = BulletCylinderShape(self.fuelRadius, 0.01 * self.length, ZUp)
        self.fuelNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Cone'))
        self.fuelNP.node().setMass(self.fuelMass_full * self.fuelMass_init)
        self.fuelNP.node().addShape(shape)
        self.fuelNP.setPos(0, 0, self.rocketNP.getPos().getZ() - self.length * 0.5 * (1 - self.fuelMass_init))
        self.fuelNP.setCollideMask(BitMask32.allOn())
        self.fuelNP.node().setCollisionResponse(0)

        self.world.attachRigidBody(self.fuelNP.node())

        frameA = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 90))
        frameB = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 90))

        self.fuelSlider = BulletSliderConstraint(self.rocketNP.node(), self.fuelNP.node(), frameA, frameB, 1)
        self.fuelSlider.setTargetLinearMotorVelocity(0)
        self.fuelSlider.setDebugDrawSize(2.0)
        self.fuelSlider.set_lower_linear_limit(0)
        self.fuelSlider.set_upper_linear_limit(0)
        self.world.attachConstraint(self.fuelSlider)

        self.npThrustForce = LineNodePath(self.rocketNP, 'Thrust', thickness=4, colorVec=Vec4(1, 0.5, 0, 1))
        self.npDragForce = LineNodePath(self.rocketNP, 'Drag', thickness=4, colorVec=Vec4(1, 0, 0, 1))
        self.npLiftForce = LineNodePath(self.rocketNP, 'Lift', thickness=4, colorVec=Vec4(0, 0, 1, 1))
        self.npFuelState = LineNodePath(self.fuelNP, 'Fuel', thickness=20, colorVec=Vec4(0, 1, 0, 1))

        self.rocketCSLon = self.radius ** 2 * math.pi
        self.rocketCSLat = self.length * 2 * self.radius

        if self.VISUALIZE is True:
            self.terrain = loader.loadModel("LZGrid2.egg")
            self.terrain.setScale(10)
            self.terrain.reparentTo(self.render)
            self.terrain.setColor(Vec4(0.1, 0.2, 0.1, 1))
            self.toggleTexture()

        #self.fuelNP.setPos(0, 0, self.rocketNP.getPos().getZ() - self.length * 0.4 * (1 - self.fuelMass_init))

        for i in range(5):
            self.world.doPhysics(self.dt, 5, 1.0 / 180.0)

        self.fuelSlider.set_lower_linear_limit(-self.length * 0.5 * (1 - self.fuelMass_init))
        self.fuelSlider.set_upper_linear_limit(self.length * 0.5 * (1 - self.fuelMass_init))

        for i in range(100):
            self.world.doPhysics(self.dt, 5, 1.0 / 180.0)
            self.rocketNP.node().applyForce(Vec3(0,0,300000), Vec3(0, 0, 0))
Ejemplo n.º 15
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)

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

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

        # collision
        self.maze = []
        for pos in [(0.0, 72.0, 0.0), (-11.0, 60.0, 0.0), (11.0, 60.0, 0.0),
                    (-11.0, 48.0, 0.0), (11.0, 48.0, 0.0), (-11.0, 36.0, 0.0),
                    (11.0, 36.0, 0.0), (-11.0, 24.0, 0.0), (11.0, 24.0, 0.0),
                    (-11.0, 12.0, 0.0), (11.0, 12.0, 0.0), (-11.0, 0.0, 0.0),
                    (11.0, 0.0, 0.0), (0.0, -12.0, 0.0), (0.5, 12.0, 1.0),
                    (-0.5, 12.0, 1.0)]:
            translate = False
            if (abs(pos[0]) == 0.5):
                translate = True
                visNP = loader.loadModel('../models/ball.egg')
            else:
                visNP = loader.loadModel('../models/maze.egg')
            visNP.clearModelNodes()
            visNP.reparentTo(self.ground)
            visNP.setPos(pos[0], pos[1], pos[2])

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

                if isinstance(bodyNP.node(), BulletRigidBodyNode):
                    bodyNP.node().setMass(0.0)
                    bodyNP.node().setKinematic(True)
                    self.maze.append(bodyNP)

        for bodyNP in self.maze:
            self.world.attachRigidBody(bodyNP.node())
        # Chassis
        mass = rospy.get_param('~mass')
        #chassis_shape = rospy.get_param('~chassis_shape')
        shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
        ts = TransformState.makePos(Point3(0, 0, 0.5))

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle'))
        np.node().addShape(shape, ts)
        rand_vals = numpy.random.random(2) * 8 - 4.0
        np.setPos(rand_vals[0], 0.0, -0.6)
        np.node().setMass(mass)
        np.node().setDeactivationEnabled(False)

        first_person = rospy.get_param('~first_person')
        self.camera_sensor = Panda3dCameraSensor(base,
                                                 color=True,
                                                 depth=True,
                                                 size=(160, 90))

        self.camera_node = self.camera_sensor.cam
        if first_person:
            self.camera_node.reparentTo(np)
            self.camera_node.setPos(0.0, 1.0, 1.0)
            self.camera_node.lookAt(0.0, 6.0, 0.0)
        else:
            self.camera_node.reparentTo(np)
            self.camera_node.setPos(0.0, -10.0, 5.0)
            self.camera_node.lookAt(0.0, 5.0, 0.0)
        base.cam.reparentTo(np)
        base.cam.setPos(0.0, -10.0, 5.0)
        base.cam.lookAt(0.0, 5.0, 0.0)
        self.world.attachRigidBody(np.node())

        np.node().setCcdSweptSphereRadius(1.0)
        np.node().setCcdMotionThreshold(1e-7)

        # Vehicle
        self.vehicle_node = np.node()
        self.vehicle = BulletVehicle(self.world, np.node())
        self.vehicle.setCoordinateSystem(ZUp)
        self.world.attachVehicle(self.vehicle)

        self.yugoNP = loader.loadModel('../models/yugo/yugo.egg')
        self.yugoNP.reparentTo(np)

        # Right front wheel
        np = loader.loadModel('../models/yugo/yugotireR.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(0.70, 1.05, 0.3), True, np)

        # Left front wheel
        np = loader.loadModel('../models/yugo/yugotireL.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(-0.70, 1.05, 0.3), True, np)

        # Right rear wheel
        np = loader.loadModel('../models/yugo/yugotireR.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(0.70, -1.05, 0.3), False, np)

        # Left rear wheel
        np = loader.loadModel('../models/yugo/yugotireL.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(-0.70, -1.05, 0.3), False, np)
    def __init__(self):
        ShowBase.__init__(self)
        base.set_background_color(0.1, 0.1, 0.8, 1)
        base.set_frame_rate_meter(True)

        base.cam.set_pos_hpr(0, 0, 25, 0, -90, 0)
        base.disable_mouse()

        # Input
        self.accept('escape', self.exitGame)
        self.accept('f1', base.toggle_wireframe)
        self.accept('f2', base.toggle_texture)
        self.accept('f3', self.toggle_debug)
        self.accept('f5', self.do_screenshot)

        # Setup scene 1: World
        self.debugNP = render.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(True)
        self.debugNP.node().show_normals(True)
        self.debugNP.show()

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

        # Setup scene 2: Ball
        #visNP = loader.load_model('models/ball.egg')
        visNP = loader.load_model('samples/ball-in-maze/models/ball.egg.pz')
        visNP.clear_model_nodes()

        bodyNPs = BulletHelper.from_collision_solids(visNP, True)
        self.ballNP = bodyNPs[0]
        self.ballNP.reparent_to(render)
        self.ballNP.node().set_mass(1.0)
        self.ballNP.set_pos(4, -4, 1)
        self.ballNP.node().set_deactivation_enabled(False)

        visNP.reparent_to(self.ballNP)

        # Setup scene 3: Maze
        visNP = loader.load_model('models/maze.egg')
        #visNP = loader.load_model('samples/ball-in-maze/models/maze.egg.pz')
        visNP.clear_model_nodes()
        visNP.reparent_to(render)

        self.holes = []
        self.maze = []
        self.mazeNP = visNP

        bodyNPs = BulletHelper.from_collision_solids(visNP, True);
        for bodyNP in bodyNPs:
            bodyNP.reparent_to(render)

            if isinstance(bodyNP.node(), BulletRigidBodyNode):
                bodyNP.node().set_mass(0.0)
                bodyNP.node().set_kinematic(True)
                self.maze.append(bodyNP)

            elif isinstance(bodyNP.node(), BulletGhostNode):
                self.holes.append(bodyNP)

        # Lighting and material for the ball
        ambientLight = AmbientLight('ambientLight')
        ambientLight.set_color(LVector4(0.55, 0.55, 0.55, 1))
        directionalLight = DirectionalLight('directionalLight')
        directionalLight.set_direction(LVector3(0, 0, -1))
        directionalLight.set_color(LVector4(0.375, 0.375, 0.375, 1))
        directionalLight.set_specular_color(LVector4(1, 1, 1, 1))
        self.ballNP.set_light(render.attach_new_node(ambientLight))
        self.ballNP.set_light(render.attach_new_node(directionalLight))

        m = Material()
        m.set_specular(LVector4(1,1,1,1))
        m.set_shininess(96)
        self.ballNP.set_material(m, 1)

        # Startup
        self.start_game()
    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())

        # Soft body world information
        info = self.world.getWorldInfo()
        info.setAirDensity(1.2)
        info.setWaterDensity(0)
        info.setWaterOffset(0)
        info.setWaterNormal(Vec3(0, 0, 0))

        # Softbody
        def make(p1):
            n = 8
            p2 = p1 + Vec3(10, 0, 0)

            bodyNode = BulletSoftBodyNode.makeRope(info, p1, p2, n, 1)
            bodyNode.setTotalMass(50.0)
            bodyNP = self.worldNP.attachNewNode(bodyNode)
            self.world.attachSoftBody(bodyNode)

            # Render option 1: Line geom
            #geom = BulletSoftBodyNode.makeGeomFromLinks(bodyNode)
            #bodyNode.linkGeom(geom)
            #visNode = GeomNode('')
            #visNode.addGeom(geom)
            #visNP = bodyNP.attachNewNode(visNode)

            # Render option 2: NURBS curve
            curve = NurbsCurveEvaluator()
            curve.reset(n + 2)
            bodyNode.linkCurve(curve)

            visNode = RopeNode('')
            visNode.setCurve(curve)
            visNode.setRenderMode(RopeNode.RMTube)
            visNode.setUvMode(RopeNode.UVParametric)
            visNode.setNumSubdiv(4)
            visNode.setNumSlices(8)
            visNode.setThickness(0.4)
            visNP = self.worldNP.attachNewNode(visNode)
            #visNP = bodyNP.attachNewNode(visNode) # --> renders with offset!!!
            visNP.setTexture(loader.loadTexture('models/iron.jpg'))

            #bodyNP.showBounds()
            #visNP.showBounds()

            return bodyNP

        np1 = make(Point3(-2, -1, 8))
        np2 = make(Point3(-2, 1, 8))

        # Box
        shape = BulletBoxShape(Vec3(2, 2, 6))

        boxNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
        boxNP.node().setMass(50.0)
        boxNP.node().addShape(shape)
        boxNP.setPos(10, 0, 8)
        boxNP.setCollideMask(BitMask32.allOn())

        self.world.attachRigidBody(boxNP.node())

        np1.node().appendAnchor(np1.node().getNumNodes() - 1, boxNP.node())
        np2.node().appendAnchor(np1.node().getNumNodes() - 1, boxNP.node())

        visNP = loader.loadModel('models/box.egg')
        visNP.clearModelNodes()
        visNP.setScale(4, 4, 12)
        visNP.reparentTo(boxNP)
    def __init__(self):
        self.bspLoader = Py_CL_BSPLoader()
        self.bspLoader.setGlobalPtr(self.bspLoader)

        if metadata.USE_RENDER_PIPELINE:
            from rpcore import RenderPipeline
            self.pipeline = RenderPipeline()
            self.pipeline.create(self)
        else:
            ShowBase.__init__(self)
            self.loader.destroy()
            self.loader = CogInvasionLoader(self)
            __builtin__.loader = self.loader
            self.graphicsEngine.setDefaultLoader(self.loader.loader)

        self.cam.node().getDisplayRegion(0).setClearDepthActive(1)

        from panda3d.core import RenderAttribRegistry
        from panda3d.core import ShaderAttrib, TransparencyAttrib
        from libpandabsp import BSPMaterialAttrib
        attribRegistry = RenderAttribRegistry.getGlobalPtr()
        attribRegistry.setSlotSort(BSPMaterialAttrib.getClassSlot(), 0)
        attribRegistry.setSlotSort(ShaderAttrib.getClassSlot(), 1)
        attribRegistry.setSlotSort(TransparencyAttrib.getClassSlot(), 2)

        gsg = self.win.getGsg()

        # Let's print out the Graphics information.
        self.notify.info(
            'Graphics Information:\n\tVendor: {0}\n\tRenderer: {1}\n\tVersion: {2}\n\tSupports Cube Maps: {3}\n\tSupports 3D Textures: {4}\n\tSupports Compute Shaders: {5}'
            .format(gsg.getDriverVendor(), gsg.getDriverRenderer(),
                    gsg.getDriverVersion(), str(gsg.getSupportsCubeMap()),
                    str(gsg.getSupports3dTexture()),
                    str(gsg.getSupportsComputeShaders())))

        # Enable shader generation on all of the main scenes
        if gsg.getSupportsBasicShaders() and gsg.getSupportsGlsl():
            render.setShaderAuto()
            render2d.setShaderAuto()
            render2dp.setShaderAuto()
        else:
            # I don't know how this could be possible
            self.notify.error("GLSL shaders unsupported by graphics driver.")
            return

        # Let's disable fog on Intel graphics
        if gsg.getDriverVendor() == "Intel":
            metadata.NO_FOG = 1
            self.notify.info('Applied Intel-specific graphical fix.')

        self.win.disableClears()

        self.camNode.setCameraMask(CIGlobals.MainCameraBitmask)

        from direct.distributed.ClockDelta import globalClockDelta
        __builtin__.globalClockDelta = globalClockDelta

        # Any ComputeNodes should be parented to this node, not render.
        # We isolate ComputeNodes to avoid traversing the same ComputeNodes
        # when doing multi-pass rendering.
        self.computeRoot = NodePath('computeRoot')
        self.computeCam = self.makeCamera(base.win)
        self.computeCam.node().setCullBounds(OmniBoundingVolume())
        self.computeCam.node().setFinal(True)
        self.computeCam.reparentTo(self.computeRoot)

        # Initialized in initStuff()
        self.shaderGenerator = None

        render.hide()

        self.camLens.setNearFar(0.5, 10000)

        self.physicsWorld = BulletWorld()
        # Panda units are in feet, so the gravity is 32 feet per second,
        # not 9.8 meters per second.
        self.physicsWorld.setGravity(Vec3(0, 0, -32.1740))

        self.physicsWorld.setGroupCollisionFlag(7, 1, True)
        self.physicsWorld.setGroupCollisionFlag(7, 2, True)
        self.physicsWorld.setGroupCollisionFlag(7, 3, False)
        self.physicsWorld.setGroupCollisionFlag(7, 4, False)
        self.physicsWorld.setGroupCollisionFlag(7, 8, True)

        self.taskMgr.add(self.__physicsUpdate, "physicsUpdate", sort=30)

        debugNode = BulletDebugNode('Debug')
        self.debugNP = render.attachNewNode(debugNode)
        self.physicsWorld.setDebugNode(self.debugNP.node())

        self.physicsDbgFlag = False
        self.setPhysicsDebug(self.config.GetBool('physics-debug', False))

        #self.shadowCaster = ShadowCaster(Vec3(163, -67, 0))
        #self.shadowCaster.enable()

        self.bspLoader.setGamma(2.2)
        self.bspLoader.setWin(self.win)
        self.bspLoader.setCamera(self.camera)
        self.bspLoader.setRender(self.render)
        self.bspLoader.setMaterialsFile("phase_14/etc/materials.txt")
        #self.bspLoader.setTextureContentsFile("phase_14/etc/texturecontents.txt")
        self.bspLoader.setWantVisibility(True)
        self.bspLoader.setVisualizeLeafs(False)
        self.bspLoader.setWantLightmaps(True)
        #self.bspLoader.setShadowCamPos(Point3(-15, 5, 40))
        #self.bspLoader.setShadowResolution(60 * 2, 1024 * 1)
        self.bspLoader.setPhysicsWorld(self.physicsWorld)
        self.bspLevel = None
        self.materialData = {}
        self.skyBox = None
        self.skyBoxUtil = None

        #self.nmMgr = RNNavMeshManager.get_global_ptr()
        #self.nmMgr.set_root_node_path(self.render)
        #self.nmMgr.get_reference_node_path().reparentTo(self.render)
        #self.nmMgr.start_default_update()
        #self.nmMgr.get_reference_node_path_debug().reparentTo(self.render)
        self.navMeshNp = None

        # Setup 3d audio                                 run before igLoop so 3d positioning doesn't lag behind
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera, render)
        base.audio3d.setDropOffFactor(0.15)
        base.audio3d.setDopplerFactor(0.15)

        # Setup collision handlers
        base.cTrav = CollisionTraverser()
        base.lifter = CollisionHandlerFloor()
        base.pusher = CollisionHandlerPusher()
        base.queue = CollisionHandlerQueue()

        base.lightingCfg = None

        self.cl_attackMgr = None

        #self.accept('/', self.projectShadows)

        # Let's setup the user input storage system
        uis = UserInputStorage()
        self.inputStore = uis
        self.userInputStorage = uis
        __builtin__.inputStore = uis
        __builtin__.userInputStorage = uis

        self.credits2d = self.render2d.attachNewNode(PGTop("credits2d"))
        self.credits2d.setScale(1.0 / self.getAspectRatio(), 1.0, 1.0)

        self.wakeWaterHeight = -30.0

        self.bloomToggle = False
        self.hdrToggle = False
        self.fxaaToggle = CIGlobals.getSettingsMgr().getSetting(
            "aa").getValue() == "FXAA"
        self.aoToggle = False

        self.music = None
        self.currSongName = None

        render.show(CIGlobals.ShadowCameraBitmask)

        self.avatars = []

        wrm = WaterReflectionManager()
        self.waterReflectionMgr = wrm
        __builtin__.waterReflectionMgr = wrm

        # Let's setup our margins
        base.marginManager = MarginManager()
        base.margins = aspect2d.attachNewNode(
            base.marginManager, DirectGuiGlobals.MIDGROUND_SORT_INDEX + 1)
        base.leftCells = [
            base.marginManager.addCell(0.1, -0.6, base.a2dTopLeft),
            base.marginManager.addCell(0.1, -1.0, base.a2dTopLeft),
            base.marginManager.addCell(0.1, -1.4, base.a2dTopLeft)
        ]
        base.bottomCells = [
            base.marginManager.addCell(0.4, 0.1, base.a2dBottomCenter),
            base.marginManager.addCell(-0.4, 0.1, base.a2dBottomCenter),
            base.marginManager.addCell(-1.0, 0.1, base.a2dBottomCenter),
            base.marginManager.addCell(1.0, 0.1, base.a2dBottomCenter)
        ]
        base.rightCells = [
            base.marginManager.addCell(-0.1, -0.6, base.a2dTopRight),
            base.marginManager.addCell(-0.1, -1.0, base.a2dTopRight),
            base.marginManager.addCell(-0.1, -1.4, base.a2dTopRight)
        ]

        base.mouseWatcherNode.setEnterPattern('mouse-enter-%r')
        base.mouseWatcherNode.setLeavePattern('mouse-leave-%r')
        base.mouseWatcherNode.setButtonDownPattern('button-down-%r')
        base.mouseWatcherNode.setButtonUpPattern('button-up-%r')

        cbm = CullBinManager.getGlobalPtr()
        cbm.addBin('ground', CullBinManager.BTUnsorted, 18)
        # The portal uses the shadow bin by default,
        # but we still want to see it with real shadows.
        cbm.addBin('portal', CullBinManager.BTBackToFront, 19)
        if not metadata.USE_REAL_SHADOWS:
            cbm.addBin('shadow', CullBinManager.BTBackToFront, 19)
        else:
            cbm.addBin('shadow', CullBinManager.BTFixed, -100)
        cbm.addBin('gui-popup', CullBinManager.BTUnsorted, 60)
        cbm.addBin('gsg-popup', CullBinManager.BTFixed, 70)
        self.setBackgroundColor(CIGlobals.DefaultBackgroundColor)
        self.disableMouse()
        self.enableParticles()
        base.camLens.setNearFar(CIGlobals.DefaultCameraNear,
                                CIGlobals.DefaultCameraFar)
        base.transitions = CITransitions(loader)
        base.transitions.IrisModelName = "phase_3/models/misc/iris.bam"
        base.transitions.FadeModelName = "phase_3/models/misc/fade.bam"

        self.accept(self.inputStore.TakeScreenshot,
                    ScreenshotHandler.takeScreenshot)

        #self.accept('u', render.setShaderOff)
        #self.accept('i', render.setShaderOff, [1])
        #self.accept('o', render.setShaderOff, [2])

        # Disabled oobe culling
        #self.accept('o', self.oobeCull)
        #self.accept('c', self.reportCam)

        self.taskMgr.add(self.__updateShadersAndPostProcess,
                         'CIBase.updateShadersAndPostProcess', 47)
        self.taskMgr.add(self.__update3DAudio, 'CIBase.update3DAudio', 59)
    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
        p0 = LPoint3(-20, -20, 0)
        p1 = LPoint3(-20, 20, 0)
        p2 = LPoint3(20, -20, 0)
        p3 = LPoint3(20, 20, 0)
        mesh = BulletTriangleMesh()
        mesh.add_triangle(p0, p1, p2)
        mesh.add_triangle(p1, p2, p3)
        shape = BulletTriangleMeshShape(mesh, dynamic=False)

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

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

        # Soft body world information
        info = self.world.get_world_info()
        info.set_air_density(1.2)
        info.set_water_density(0)
        info.set_water_offset(0)
        info.set_water_normal(LVector3(0, 0, 0))

        # Softbody
        def make_SB(pos, hpr):

            #use this to construct a torus geom.
            #import torus
            #geom = torus.make_geom()

            geom = (loader.load_model('models/torus.egg').find_all_matches(
                '**/+GeomNode').get_path(0).node().modify_geom(0))

            geomNode = GeomNode('')
            geomNode.add_geom(geom)

            node = BulletSoftBodyNode.make_tri_mesh(info, geom)
            node.link_geom(geomNode.modify_geom(0))

            node.generate_bending_constraints(2)
            node.get_cfg().set_positions_solver_iterations(2)
            node.get_cfg().set_collision_flag(
                BulletSoftBodyConfig.CF_vertex_face_soft_soft, True)
            node.randomize_constraints()
            node.set_total_mass(50, True)

            softNP = self.worldNP.attach_new_node(node)
            softNP.set_pos(pos)
            softNP.set_hpr(hpr)
            self.world.attach(node)

            geomNP = softNP.attach_new_node(geomNode)

        make_SB(LPoint3(-3, 0, 4), (0, 0, 0))
        make_SB(LPoint3(0, 0, 4), (0, 90, 90))
        make_SB(LPoint3(3, 0, 4), (0, 0, 0))
Ejemplo n.º 20
0
    # robotplot = nxtplot

    # robot.goinitpose()
    # robot.movearmfk([0.0,-20.0,-60.0,-70.0,-100.0,-30.0,0.0,0.0,0.0])
    # robot.movearmfk([0.0,-20.0,60.0,70.0,-100.0,30.0,0.0,0.0,0.0], armid = 'lft')
    # robotmnp = robotmesh.genmnp(robot)
    # robotmnp.reparentTo(base.render)

    # ur5dualmnp = ur5dualplot.genUr5dualmnp(robot, handpkg)
    # ur5dualmnp.reparentTo(base.render)
    pg.plotAxisSelf(base.render, Vec3(0,0,0))

    cdchecker = CollisionChecker(robotmesh)
    print cdchecker.isSelfCollided(robot)

    bullcldrnp = base.render.attachNewNode("bulletcollider")
    debugNode = BulletDebugNode('Debug')
    debugNode.showWireframe(True)
    debugNode.showConstraints(True)
    debugNode.showBoundingBoxes(False)
    debugNode.showNormals(False)
    debugNP = bullcldrnp.attachNewNode(debugNode)
    debugNP.show()

    cdchecker.bulletworld.setDebugNode(debugNP.node())

    def updateworld(world, task):
        world.doPhysics(globalClock.getDt())
        return task.cont
    base.taskMgr.add(updateworld, "updateworld", extraArgs=[cdchecker.bulletworld], appendTask=True)
    base.run()
Ejemplo n.º 21
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(True)

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

        # Plane (static)
        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())

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

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

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

        self.boxNP = np  # For applying force & torque

        #np.node().notifyCollisions(True)
        #self.accept('bullet-contact-added', self.doAdded)
        #self.accept('bullet-contact-destroyed', self.doRemoved)

        # Sphere (dynamic)
        shape = BulletSphereShape(0.6)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Sphere'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(-4, 0, 4)
        np.setCollideMask(BitMask32.allOn())

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

        # Cone (dynamic)
        shape = BulletConeShape(0.6, 1.2, ZUp)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Cone'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(4, 0, 4)
        np.setCollideMask(BitMask32.allOn())

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

        # Capsule (dynamic)
        shape = BulletCapsuleShape(0.5, 1.0, ZUp)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Capsule'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(0, 4, 4)
        np.setCollideMask(BitMask32.allOn())

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

        # Cyliner (dynamic)
        shape = BulletCylinderShape(0.7, 1.5, ZUp)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Cylinder'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(4, 4, 4)
        np.setCollideMask(BitMask32.allOn())

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

        # Convex (dynamic)
        shape = BulletConvexHullShape()
        shape.addPoint(Point3(1, 1, 2))
        shape.addPoint(Point3(0, 0, 0))
        shape.addPoint(Point3(2, 0, 0))
        shape.addPoint(Point3(0, 2, 0))
        shape.addPoint(Point3(2, 2, 0))

        # Another way to create the convex hull shape:
        #shape = BulletConvexHullShape()
        #shape.addArray([
        #  Point3(1, 1, 2),
        #  Point3(0, 0, 0),
        #  Point3(2, 0, 0),
        #  Point3(0, 2, 0),
        #  Point3(2, 2, 0),
        #])

        # Yet another way to create the convex hull shape:
        #geom = loader.loadModel('models/box.egg')\
        #         .findAllMatches('**/+GeomNode')\
        #         .getPath(0)\
        #         .node()\
        #         .getGeom(0)
        #shape = BulletConvexHullShape()
        #shape.addGeom(geom)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Convex'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(-4, 4, 4)
        np.setCollideMask(BitMask32.allOn())

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

        # Mesh (static)
        p0 = Point3(-10, -10, 0)
        p1 = Point3(-10, 10, 0)
        p2 = Point3(10, -10, 0)
        p3 = Point3(10, 10, 0)
        mesh = BulletTriangleMesh()
        mesh.addTriangle(p0, p1, p2)
        mesh.addTriangle(p1, p2, p3)
        shape = BulletTriangleMeshShape(mesh, dynamic=False)

        # Another way to create the triangle mesh shape:
        #geom = loader.loadModel('models/box.egg')\
        #         .findAllMatches('**/+GeomNode')\
        #         .getPath(0)\
        #         .node()\
        #         .getGeom(0)
        #mesh = BulletTriangleMesh()
        #mesh.addGeom(geom)
        #shape = BulletTriangleMeshShape(mesh, dynamic=False)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh'))
        np.node().addShape(shape)
        np.setPos(0, 0, 0.1)
        np.setCollideMask(BitMask32.allOn())

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

        # MutiSphere
        points = [Point3(-1, 0, 0), Point3(0, 0, 0), Point3(1, 0, 0)]
        radii = [.4, .8, .6]
        shape = BulletMultiSphereShape(points, radii)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('MultiSphere'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(8, 0, 4)
        np.setCollideMask(BitMask32.allOn())

        self.world.attachRigidBody(np.node())
Ejemplo n.º 22
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)
Ejemplo n.º 23
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)

        mask = BitMask32(0x0f)
        print('ground: ', mask)

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

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

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

        #mask = BitMask32.allOff()
        #print 'box-1:  ', mask

        #np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-1'))
        #np.node().setMass(1.0)
        #np.node().addShape(shape)
        #np.setPos(-6, 0, 4)
        #np.setCollideMask(mask)

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

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

        #mask = BitMask32.bit(0)
        #print 'box-2:  ', mask

        #np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-2'))
        #np.node().setMass(1.0)
        #np.node().addShape(shape)
        #np.setPos(-2, 0, 4)
        #np.setCollideMask(mask)

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

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

        #mask = BitMask32.bit(2)
        #print 'box-3:  ', mask

        #np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-3'))
        #np.node().setMass(1.0)
        #np.node().addShape(shape)
        #np.setPos(2, 0, 4)
        #np.setCollideMask(mask)

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

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

        mask = BitMask32(0x3)
        print('box-4:  ', mask)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-4'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(6, 0, 4)
        np.setCollideMask(mask)

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

        self.boxNP = np

        visualNP = loader.loadModel('models/box.egg')
        visualNP.reparentTo(self.boxNP)
Ejemplo n.º 24
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())

        # Box
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5) * 2.0)

        boxNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
        boxNP.node().setMass(150.0)
        boxNP.node().addShape(shape)
        boxNP.setPos(0, 0, 2)
        boxNP.setCollideMask(BitMask32.allOn())

        self.world.attachRigidBody(boxNP.node())

        visualNP = loader.loadModel('models/box.egg')
        visualNP.clearModelNodes()
        visualNP.setScale(2.0)
        visualNP.reparentTo(boxNP)

        # Soft body world information
        info = self.world.getWorldInfo()
        info.setAirDensity(1.2)
        info.setWaterDensity(0)
        info.setWaterOffset(0)
        info.setWaterNormal(Vec3(0, 0, 0))

        # Softbody
        nx = 31
        ny = 31

        p00 = Point3(-8, -8, 0)
        p10 = Point3(8, -8, 0)
        p01 = Point3(-8, 8, 0)
        p11 = Point3(8, 8, 0)
        bodyNode = BulletSoftBodyNode.makePatch(info, p00, p10, p01, p11, nx,
                                                ny, 1 + 2 + 4 + 8, True)

        material = bodyNode.appendMaterial()
        material.setLinearStiffness(0.4)
        bodyNode.generateBendingConstraints(2, material)
        bodyNode.setTotalMass(50.0)
        bodyNode.getShape(0).setMargin(0.5)

        bodyNP = self.worldNP.attachNewNode(bodyNode)
        self.world.attachSoftBody(bodyNode)

        # Rendering with Geom:
        fmt = GeomVertexFormat.getV3n3t2()
        geom = BulletHelper.makeGeomFromFaces(bodyNode, fmt, True)
        bodyNode.linkGeom(geom)
        visNode = GeomNode('')
        visNode.addGeom(geom)
        visNP = bodyNP.attachNewNode(visNode)

        # Now we want to have a texture and texture coordinates.
        # The geom's format has already a column for texcoords, so we just need
        # to write texcoords using a GeomVertexRewriter.
        tex = loader.loadTexture('models/panda.jpg')
        visNP.setTexture(tex)
        BulletHelper.makeTexcoordsForPatch(geom, nx, ny)
Ejemplo n.º 25
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(np.random.randn()*3, np.random.randn()*3, 0))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    p0 = Point3(-20, -20, 0)
    p1 = Point3(-20, 20, 0)
    p2 = Point3(20, -20, 0)
    p3 = Point3(20, 20, 0)
    mesh = BulletTriangleMesh()
    mesh.addTriangle(p0, p1, p2)
    mesh.addTriangle(p1, p2, p3)
    shape = BulletTriangleMeshShape(mesh, dynamic=False)

    npp = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh'))
    npp.node().addShape(shape)
    npp.setPos(0, 0, -2)
    npp.setCollideMask(BitMask32.allOn())

    self.ground = npp

    self.world.attachRigidBody(npp.node())

    # Soft body world information
    info = self.world.getWorldInfo()
    info.setAirDensity(1.2)
    info.setWaterDensity(0)
    info.setWaterOffset(0)
    info.setWaterNormal(Vec3(0, 0, 0))

    # Softbody
    def makeSB(pos, hpr):
      model = loader.loadModel('moleculemesh/smoothed/clathrinfixsmth%02d.obj' % np.random.randint(1,21))
      geom = model.findAllMatches('**/+GeomNode').getPath(0).node().modifyGeom(0)

      geomNode = GeomNode('')
      geomNode.addGeom(geom)

      node = BulletSoftBodyNode.makeTriMesh(info, geom) 
      node.linkGeom(geomNode.modifyGeom(0))

      node.generateBendingConstraints(2)
      node.getCfg().setPositionsSolverIterations(6)
      node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFVertexFaceSoftSoft, True)
      node.randomizeConstraints()
      node.setTotalMass(50, True)
      node.getMaterial(0).setLinearStiffness(0.2)
      #node.getCfg().setDynamicFrictionCoefficient(1)
      #node.getCfg().setDampingCoefficient(0.001)
      node.getCfg().setPressureCoefficient(1500)


      softNP = self.worldNP.attachNewNode(node)
      softNP.setPos(pos)
      softNP.setHpr(hpr)
      self.world.attachSoftBody(node)

      geomNP = softNP.attachNewNode(geomNode)

      #softNP.node().appendAnchor(1, self.ground.node())
      softNP.node().appendAnchor(1217, self.ground.node())
      softNP.node().appendAnchor(1157, self.ground.node())
      softNP.node().appendAnchor(2052, self.ground.node())
      #softNP.node().appendAnchor(1800, self.ground.node())
      softNP.reparentTo(self.mybase)

    #makeSB(Point3(-3, 0, 4), (0, 0, 0))
    #makeSB(Point3(0, 0, 4), (0, 90, 90))
    makeSB(Point3(4+np.random.randn(), 2+np.random.randn(), 4), (0, 0, 0))
Ejemplo n.º 26
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())

        #terrain = GeoMipTerrain("mySimpleTerrain")
        #terrain.setHeightfield("./models/heightfield_2.png")
        #terrain.getRoot().reparentTo(self.worldNP)#render)
        #terrain.generate()

        # 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())

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Track'))
        np.node().setMass(5000.0)
        np.setPos(3, 0, 10)
        np.setCollideMask(BitMask32.allOn())  #(0x0f))
        #self.track = BulletVehicle(self.world, np.node())
        #self.track.setCoordinateSystem(ZUp)
        self.track_np = loader.loadModel('models/race_track.egg')
        self.track_np.setScale(100)
        self.track_np.reparentTo(np)

        self.track_np.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(np.node())
        self.track_np = np
        #self.track_np.show()

        # Chassis
        shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
        ts = TransformState.makePos(Point3(0, 0, 0.5))

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle'))
        np.node().addShape(shape, ts)
        np.setPos(0, 0, 1)
        np.node().setMass(800.0)
        np.node().setDeactivationEnabled(False)

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

        #np.node().setCcdSweptSphereRadius(1.0)
        #np.node().setCcdMotionThreshold(1e-7)
        self.cTrav = CollisionTraverser()
        # Vehicle
        self.vehicle = BulletVehicle(self.world, np.node())
        self.vehicle.setCoordinateSystem(ZUp)
        self.yugoNP = loader.loadModel('models/yugo/yugo.egg')
        self.yugoNP.reparentTo(np)
        self.colHandler = CollisionHandlerQueue()
        self.ray_col_np = {}
        self.ray_col_vec_dict = {}
        for ray_dir in range(-1, 2):  # populate collision rays
            self.ray = CollisionRay()
            self.ray.setOrigin(ray_dir, 0.5, 0.5)
            self.ray.setDirection(ray_dir, 1, 0)
            self.ray_col = CollisionNode('ray%d' % (ray_dir + 1))
            self.ray_col.addSolid(self.ray)
            self.ray_col.setFromCollideMask(
                BitMask32.allOn())  #(0x0f))#CollideMask.bit(0)
            #self.ray_col.setIntoCollideMask(CollideMask.allOff())
            self.ray_col_np['ray%d' %
                            (ray_dir + 1)] = self.yugoNP.attachNewNode(
                                self.ray_col)
            self.cTrav.addCollider(self.ray_col_np['ray%d' % (ray_dir + 1)],
                                   self.colHandler)
            self.ray_col_np['ray%d' % (ray_dir + 1)].show()
            self.ray_col_vec_dict['ray%d' % (ray_dir + 1)] = []
        self.world.attachVehicle(self.vehicle)
        self.cTrav.showCollisions(render)

        # FIXME
        base.camera.reparentTo(self.yugoNP)

        # Right front wheel
        np = loader.loadModel('models/yugo/yugotireR.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(0.70, 1.05, 0.3), True, np)

        # Left front wheel
        np = loader.loadModel('models/yugo/yugotireL.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(-0.70, 1.05, 0.3), True, np)

        # Right rear wheel
        np = loader.loadModel('models/yugo/yugotireR.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(0.70, -1.05, 0.3), False, np)

        # Left rear wheel
        np = loader.loadModel('models/yugo/yugotireL.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(-0.70, -1.05, 0.3), False, np)

        # Steering info
        self.steering = 0.0  # degree
        self.steeringClamp = 45.0  # degree
        self.steeringIncrement = 120.0  # degree per second

        # Box
        for i, j in [(0, 8), (-3, 5), (6, -5), (8, 3), (-4, -4)]:
            shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))
            # https://discourse.panda3d.org/t/wall-collision-help/23606
            np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
            np.node().setMass(1.0)
            np.node().addShape(shape)
            np.setPos(i, j, 2)
            np.setCollideMask(BitMask32.allOn())  #(0x0f))

            self.world.attachRigidBody(np.node())
            self.boxNP = np
            #self.colHandler2 = CollisionHandlerQueue()

            visualNP = loader.loadModel('models/box.egg')
            visualNP.reparentTo(self.boxNP)
        #self.cTrav.addCollider(self.boxNP,self.colHandler)
        """
    aNode = CollisionNode("TheRay")

    self.ray = CollisionRay()
    self.ray.setOrigin( self.yugoNP.getPos() )
    self.ray.setDirection( Vec3(0, 10, 0) )
    #self.ray.show()


    aNodePath = self.yugoNP.attachNewNode( CollisionNode("TheRay") )
    aNodePath.node().addSolid(self.ray)
    aNodePath.show()
    """
        #aNode.addSolid(self.ray)
        #self.ray = CollisionRay(0,0,0,10,0,0)
        #self.ray.reparentTo(self.yugoNP)
        #self.rayColl = CollisionNode('PlayerRay')
        #self.rayColl.addSolid(self.ray)

        #self.playerRayNode = self.yugoNP.attachNewNode( self.rayColl )
        #self.playerRayNode.show()

        #base.myTraverser.addCollider (self.playerRayNode, base.floor)
        #base.floor.addCollider( self.playerRayNode, self.yugoNP)
        """
Ejemplo n.º 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
        p0 = LPoint3(-20, -20, 0)
        p1 = LPoint3(-20, 20, 0)
        p2 = LPoint3(20, -20, 0)
        p3 = LPoint3(20, 20, 0)
        mesh = BulletTriangleMesh()
        mesh.add_triangle(p0, p1, p2)
        mesh.add_triangle(p1, p2, p3)
        shape = BulletTriangleMeshShape(mesh, dynamic=False)

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

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

        # Soft body world information
        info = self.world.get_world_info()
        info.set_air_density(1.2)
        info.set_water_density(0)
        info.set_water_offset(0)
        info.set_water_normal(LVector3(0, 0, 0))

        ## Softbody - From points/indices
        #import cube
        #points = [LPoint3(x,y,z) * 3 for x,y,z in cube.nodes]
        #indices = sum([list(x) for x in cube.elements], [])

        #node = BulletSoftBodyNode.make_tet_mesh(info, points, indices, True)
        #node.set_volume_mass(300);
        #node.get_shape(0).set_margin(0.01)
        #node.get_material(0).set_linear_stiffness(0.8)
        #node.get_cfg().set_positions_solver_iterations(1)
        #node.get_cfg().clear_all_collision_flags()
        #node.get_cfg().set_collision_flag(
        #BulletSoftBodyConfig.CF_cluster_soft_soft, True)
        #node.get_cfg().set_collision_flag(
        #BulletSoftBodyConfig.CF_cluster_rigid_soft, True)
        #node.generate_clusters(16)

        #softNP = self.worldNP.attach_new_node(node)
        #softNP.set_pos(0, 0, 8)
        #softNP.set_hpr(0, 0, 45)
        #self.world.attach(node)

        # Softbody - From tetgen data
        ele = open('models/cube/cube.1.ele', 'r').read()
        face = open('models/cube/cube.1.face', 'r').read()
        node = open('models/cube/cube.1.node', 'r').read()

        node = BulletSoftBodyNode.make_tet_mesh(info, ele, face, node)
        node.set_name('Tetra')
        node.set_volume_mass(300)
        node.get_shape(0).set_margin(0.01)
        node.get_material(0).set_linear_stiffness(0.1)
        node.get_cfg().set_positions_solver_iterations(1)
        node.get_cfg().clear_all_collision_flags()
        node.get_cfg().set_collision_flag(
            BulletSoftBodyConfig.CF_cluster_soft_soft, True)
        node.get_cfg().setCollisionFlag(
            BulletSoftBodyConfig.CF_cluster_rigid_soft, True)
        node.generate_clusters(6)

        softNP = self.worldNP.attach_new_node(node)
        softNP.set_pos(0, 0, 8)
        softNP.set_hpr(45, 0, 0)
        self.world.attach(node)

        # Option 1:
        visNP = loader.load_model('models/cube/cube.egg')
        visNP.reparent_to(softNP)
        geom = (visNP.findAllMatches('**/+GeomNode').getPath(
            0).node().modifyGeom(0))
        node.link_geom(geom)
Ejemplo n.º 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(-4, 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(1, 0, 0)

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

        self.world.attach(bodyB)

        # Generic
        frameA = TransformState.make_pos_hpr(LPoint3(4, 0, 0),
                                             LVector3(0, 0, 0))
        frameB = TransformState.make_pos_hpr(LPoint3(2, 0, 0),
                                             LVector3(0, 0, 0))

        generic = BulletGenericConstraint(bodyA, bodyB, frameA, frameB, True)
        generic.set_debug_draw_size(2.0)
        generic.set_linear_limit(0, 0, 0)
        generic.set_linear_limit(1, 0, 3)
        generic.set_linear_limit(2, 0, 1)
        generic.set_angular_limit(0, -60, 60)
        generic.set_angular_limit(1, -30, 30)
        generic.set_angular_limit(2, -120, 120)

        self.world.attach(generic)
Ejemplo n.º 29
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())

        # Chassis
        shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
        ts = TransformState.makePos(Point3(0, 0, 0.5))

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle'))
        np.node().addShape(shape, ts)
        np.setPos(0, 0, 1)
        np.node().setMass(800.0)
        np.node().setDeactivationEnabled(False)

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

        #np.node().setCcdSweptSphereRadius(1.0)
        #np.node().setCcdMotionThreshold(1e-7)

        # Vehicle
        self.vehicle = BulletVehicle(self.world, np.node())
        self.vehicle.setCoordinateSystem(ZUp)
        self.world.attachVehicle(self.vehicle)

        self.yugoNP = loader.loadModel('car/yugo.egg')
        self.yugoNP.reparentTo(np)

        # Right front wheel
        np = loader.loadModel('car/yugotireR.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(0.70, 1.05, 0.3), True, np)

        # Left front wheel
        np = loader.loadModel('car/yugotireL.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(-0.70, 1.05, 0.3), True, np)

        # Right rear wheel
        np = loader.loadModel('car/yugotireR.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(0.70, -1.05, 0.3), False, np)

        # Left rear wheel
        np = loader.loadModel('car/yugotireL.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(-0.70, -1.05, 0.3), False, np)

        # Steering info
        self.steering = 0.0  # degree
        self.steeringClamp = 45.0  # degree
        self.steeringIncrement = 120.0  # degree per second
Ejemplo n.º 30
0
    def __init__(self, screen_size=84, DEBUGGING=False, human_playable=False):
        ShowBase.__init__(self)
        self.forward_button = KeyboardButton.ascii_key(b'w')
        self.backward_button = KeyboardButton.ascii_key(b's')

        self.fps = 20
        self.human_playable = human_playable
        self.actions = 3
        self.last_frame_start_time = time.time()
        self.action_buffer = [1, 1, 1]
        self.last_teleport_time = 0.0
        self.time_to_teleport = False

        if self.human_playable is False:
            winprops = WindowProperties.size(screen_size, screen_size)
            fbprops = FrameBufferProperties()
            fbprops.set_rgba_bits(8, 8, 8, 0)
            fbprops.set_depth_bits(24)
            self.pipe = GraphicsPipeSelection.get_global_ptr().make_module_pipe('pandagl')
            self.imageBuffer = self.graphicsEngine.makeOutput(
                self.pipe,
                "image buffer",
                1,
                fbprops,
                winprops,
                GraphicsPipe.BFRefuseWindow)


            self.camera = Camera('cam')
            self.cam = NodePath(self.camera)
            self.cam.reparentTo(self.render)

            self.dr = self.imageBuffer.makeDisplayRegion()
            self.dr.setCamera(self.cam)

        self.render.setShaderAuto()
        self.cam.setPos(0.5, 0, 6)
        self.cam.lookAt(0.5, 0, 0)

        # Create Ambient Light
        self.ambientLight = AmbientLight('ambientLight')
        self.ambientLight.setColor((0.2, 0.2, 0.2, 1))
        self.ambientLightNP = self.render.attachNewNode(self.ambientLight)
        self.render.setLight(self.ambientLightNP)

        # Spotlight
        self.light = Spotlight('light')
        self.light.setColor((0.9, 0.9, 0.9, 1))
        self.lightNP = self.render.attachNewNode(self.light)
        self.lightNP.setPos(0, 10, 10)
        self.lightNP.lookAt(0, 0, 0)
        self.lightNP.node().getLens().setFov(40)
        self.lightNP.node().getLens().setNearFar(10, 100)
        self.lightNP.node().setShadowCaster(True, 1024, 1024)
        self.render.setLight(self.lightNP)

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

        if DEBUGGING is True:
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            debugNP = render.attachNewNode(debugNode)
            debugNP.show()
            self.world.setDebugNode(debugNP.node())

        self.finger_speed_mps = 0.0
        self.penalty_applied = False
        self.teleport_cooled_down = True
        self.fps = 20
        self.framecount = 0
        self.reset()