Beispiel #1
0
    def __init__(self, entity, mesh=None, center=(0, 0, 0)):
        super().__init__()
        center = Vec3(center)
        if mesh == None and entity.model:
            mesh = entity.model
            # print('''auto generating mesh collider from entity's mesh''')

        # from ursina import Mesh     # this part is obsolete if I use the old obj loading
        # if not isinstance(mesh, Mesh):
        #     from ursina import mesh_importer
        #     mesh = eval(mesh_importer.obj_to_ursinamesh(name=mesh.name, save_to_file=False))
        #     flipped_verts = [v*Vec3(-1,1,1) for v in mesh.vertices] # have to flip it on x axis for some reason
        #     mesh.vertices = flipped_verts
        self.node_path = entity.attachNewNode(CollisionNode('CollisionNode'))
        self.node = self.node_path.node()
        self.collision_polygons = list()

        if mesh.triangles:
            for tri in mesh.triangles:
                if len(tri) == 3:
                    poly = CollisionPolygon(
                        Vec3(mesh.vertices[tri[2]]),
                        Vec3(mesh.vertices[tri[1]]),
                        Vec3(mesh.vertices[tri[0]]),
                    )
                    self.collision_polygons.append(poly)
                elif len(tri) == 4:
                    poly = CollisionPolygon(Vec3(mesh.vertices[tri[2]]),
                                            Vec3(mesh.vertices[tri[1]]),
                                            Vec3(mesh.vertices[tri[0]]))
                    self.collision_polygons.append(poly)
                    poly = CollisionPolygon(Vec3(mesh.vertices[tri[0]]),
                                            Vec3(mesh.vertices[tri[3]]),
                                            Vec3(mesh.vertices[tri[2]]))
                    self.collision_polygons.append(poly)

        elif mesh.mode == 'triangle':
            for i in range(0, len(mesh.vertices), 3):
                poly = CollisionPolygon(
                    Vec3(mesh.vertices[i + 2]),
                    Vec3(mesh.vertices[i + 1]),
                    Vec3(mesh.vertices[i]),
                )
                self.collision_polygons.append(poly)

        else:
            print('error: mesh collider does not support', mesh.mode, 'mode')
            return None

        for poly in self.collision_polygons:
            self.node.addSolid(poly)
        self.visible = False
Beispiel #2
0
def gen_polygons_cdnp(pdnp, name='cdnp_polygons', radius=.01):
    """
    :param trimeshmodel:
    :param name:
    :param radius: TODO
    :return:
    author: weiwei
    date: 20210204
    """
    collision_node = CollisionNode(name)
    # counter = 0
    for geom in pdnp.findAllMatches('**/+GeomNode'):
        geom_node = geom.node()
        for g in range(geom_node.getNumGeoms()):
            geom = geom_node.getGeom(g).decompose()
            vdata = geom.getVertexData()
            vreader = GeomVertexReader(vdata, 'vertex')
            for p in range(geom.getNumPrimitives()):
                prim = geom.getPrimitive(p)
                for p2 in range(prim.getNumPrimitives()):
                    s = prim.getPrimitiveStart(p2)
                    e = prim.getPrimitiveEnd(p2)
                    v = []
                    for vi in range(s, e):
                        vreader.setRow(prim.getVertex(vi))
                        # TODO expand radius by moving along normal directions
                        v.append(vreader.getData3f())
                    col_poly = CollisionPolygon(*v)
                    collision_node.addSolid(col_poly)
                    # print("polygon ", counter)
                    # counter += 1
    return collision_node
Beispiel #3
0
    def _prepare_arrow(self, name, arrow_pos):
        """Prepare a manipulating arrow for this part.

        Args:
            name (str): Name of the part.
            arrow_pos (dict): Arrow position.

        Returns:
            panda3d.core.NodePath: Arrow node.
        """
        arrow = loader.loadModel(address("train_part_arrow"))  # noqa: F821
        arrow.setPos(*arrow_pos)
        arrow.setH(self.angle)
        arrow.clearLight()

        # set manipulating arrow collisions
        # used to detect pointing the arrow by mouse
        col_node = CollisionNode(name)
        col_node.setFromCollideMask(NO_MASK)
        col_node.setIntoCollideMask(MOUSE_MASK)
        col_node.addSolid(
            CollisionPolygon(
                Point3(-0.06, -0.06, 0),
                Point3(-0.06, 0.06, 0),
                Point3(0.06, 0.06, 0),
                Point3(0.06, -0.06, 0),
            )
        )
        arrow.attachNewNode(col_node)
        return arrow
Beispiel #4
0
    def __init__(self, entity, mesh=None, center=(0,0,0)):
        super().__init__()
        center = Vec3(center)
        if mesh == None and entity.model:
            print('auto gen mesh colider from entity mesh')
            mesh = entity.model

        self.node_path = entity.attachNewNode(CollisionNode('CollisionNode'))
        node = self.node_path.node()

        if mesh.triangles:
            for tri in mesh.triangles:
                if len(tri) == 3:
                    shape = CollisionPolygon(
                        swap_y_z(Vec3(mesh.vertices[tri[0]])) + center,
                        swap_y_z(Vec3(mesh.vertices[tri[1]])) + center,
                        swap_y_z(Vec3(mesh.vertices[tri[2]])) + center)
                    node.addSolid(shape)
                elif len(tri) == 4:
                    shape = CollisionPolygon(
                        swap_y_z(Vec3(mesh.vertices[tri[0]])) + center,
                        swap_y_z(Vec3(mesh.vertices[tri[1]])) + center,
                        swap_y_z(Vec3(mesh.vertices[tri[2]])) + center)
                    node.addSolid(shape)
                    shape = CollisionPolygon(
                        swap_y_z(Vec3(mesh.vertices[tri[2]])) + center,
                        swap_y_z(Vec3(mesh.vertices[tri[3]])) + center,
                        swap_y_z(Vec3(mesh.vertices[tri[0]])) + center)
                    node.addSolid(shape)

        elif mesh.mode == 'triangle':
            for i in range(0, len(mesh.vertices), 3):
                shape = CollisionPolygon(
                    swap_y_z(Vec3(mesh.vertices[i])) + center,
                    swap_y_z(Vec3(mesh.vertices[i+1])) + center,
                    swap_y_z(Vec3(mesh.vertices[i+2])) + center
                    )
                node.addSolid(shape)

        else:
            print('error: mesh collider does not support', mesh.mode, 'mode')


        self.visible = False
Beispiel #5
0
    def __init__(self, entity, mesh=None, center=(0, 0, 0)):
        super().__init__()
        if mesh == None and entity.model:
            print('auto gen mesh colider from entity mesh')
            mesh = entity.model

        self.node_path = entity.attachNewNode(CollisionNode('CollisionNode'))
        self.node_path.setP(90)
        node = self.node_path.node()
        if mesh.triangles:
            for tri in mesh.triangles:
                if len(tri) == 3:
                    shape = CollisionPolygon(
                        Point3(tri[0]) + Point3(center),
                        Point3(tri[1]) + Point3(center),
                        Point3(tri[2]) + Point3(center))
                    node.addSolid(shape)
                elif len(tri) == 4:
                    shape = CollisionPolygon(
                        Point3(tri[0]) + Point3(center),
                        Point3(tri[1]) + Point3(center),
                        Point3(tri[2]) + Point3(center))
                    node.addSolid(shape)
                    shape = CollisionPolygon(
                        Point3(tri[2]) + Point3(center),
                        Point3(tri[3]) + Point3(center),
                        Point3(tri[0]) + Point3(center))
                    node.addSolid(shape)
        else:
            for i in range(0, len(mesh.vertices) - 3, 3):
                node.addSolid(
                    CollisionPolygon(
                        Point3(mesh.vertices[i]) + Point3(center),
                        Point3(mesh.vertices[i + 1]) + Point3(center),
                        Point3(mesh.vertices[i + 2]) + Point3(center)))

        self.visible = False
Beispiel #6
0
    def createFaceCollisions(self):
        self.coll3D.node().clearSolids()
        #self.coll2D.node().clearSolids()

        self.faceCollSolids = {}

        for face in self.faces:

            numVerts = len(face.vertices)

            # Tris in 3D for ray->face selection
            for i in range(1, numVerts - 1):
                poly = CollisionPolygon(face.vertices[i + 1].pos,
                                        face.vertices[i].pos,
                                        face.vertices[0].pos)
                self.coll3D.node().addSolid(poly)
                self.faceCollSolids[poly] = face
Beispiel #7
0
    def _start_aiming(self):
        """Show aiming GUI and tweak shooting events."""
        col_node = CollisionNode("grenade_launcher_range")
        col_node.setFromCollideMask(NO_MASK)
        col_node.setIntoCollideMask(MOUSE_MASK)

        col_node.addSolid(
            CollisionPolygon(
                Point3(-1.2, -0.3, 0),
                Point3(-1.2, 1.5, 0),
                Point3(1.2, 1.5, 0),
                Point3(1.2, -0.3, 0),
            )
        )
        self._range_col_np = base.train.model.attachNewNode(col_node)  # noqa: F821

        base.accept("mouse1", self._shot)  # noqa: F821
        base.accept("mouse_ray-into", self._move_sight)  # noqa: F821
        base.accept("mouse_ray-again", self._move_sight)  # noqa: F82
Beispiel #8
0
def rebuildGeomNodesToColPolys(incomingNode,
                               relativeTo=None,
                               filter=lambda n: True):
    ''' 
    Converts GeomNodes into CollisionPolys in a straight 1-to-1 conversion 

    Returns a new NodePath containing the CollisionNodes 
    
    If the geometry is at all complex, running the result of this through colTree
    should improve performance.
    
    '''
    parent = NodePath('cGeomConversionParent')
    for c in incomingNode.findAllMatches('**/+GeomNode'):
        if not filter(c): continue
        if relativeTo:
            xform = c.getMat(relativeTo).xformPoint
        else:
            xform = (c.getMat(incomingNode) *
                     (incomingNode.getMat())).xformPoint
        geomNode = c.node()
        for g in range(geomNode.getNumGeoms()):
            geom = geomNode.getGeom(g).decompose()
            vdata = geom.getVertexData()
            vreader = GeomVertexReader(vdata, 'vertex')
            cChild = CollisionNode("")
            for p in range(geom.getNumPrimitives()):
                prim = geom.getPrimitive(p)
                for p2 in range(prim.getNumPrimitives()):
                    s = prim.getPrimitiveStart(p2)
                    e = prim.getPrimitiveEnd(p2)
                    if e - s > 2:
                        v = []
                        for vi in range(s, e):
                            vreader.setRow(prim.getVertex(vi))
                            v.append(Point3(xform(vreader.getData3f())))
                        colPoly = CollisionPolygon(*v)
                        cChild.addSolid(colPoly)
            n = parent.attachNewNode(cChild)
    return parent
Beispiel #9
0
    def _start_aiming(self):
        """Show aiming GUI and tweak shooting events."""
        col_node = CollisionNode("machine_gun_range")
        col_node.setFromCollideMask(NO_MASK)
        col_node.setIntoCollideMask(MOUSE_MASK)
        col_node.addSolid(
            CollisionPolygon(
                Point3(-1.2, -0.3, 0),
                Point3(-1.2, 1.5, 0),
                Point3(1.2, 1.5, 0),
                Point3(1.2, -0.3, 0),
            )
        )
        self._range_col_np = base.train.model.attachNewNode(col_node)  # noqa: F821

        base.accept("mouse1", self._start_shooting)  # noqa: F821
        base.accept("mouse1-up", self._stop_shooting)  # noqa: F821
        base.accept("mouse_ray-into", self._move_sight)  # noqa: F821
        base.accept("mouse_ray-again", self._move_sight)  # noqa: F82

        taskMgr.doMethodLater(  # noqa: F82
            0.05, self._aim_machine_gun, "aim_machine_gun"
        )
Beispiel #10
0
    def collisionBoxCreator(self, posx, posy, posz, length, width, height, floorname, wallname):
        ret = ()
        #Create top face
        terrain = CollisionPolygon(Point3(posx, posy+width, posz), Point3(posx, posy, posz),
                                Point3(posx+length, posy, posz), Point3(posx+length, posy+width, posz))
        terrainCol = CollisionNode(floorname)
        terrainCol.addSolid(terrain)
        terrainCol.setIntoCollideMask(BitMask32.bit(1))
        terrainColNp = self.render.attachNewNode(terrainCol)
        self.cTrav.addCollider(terrainColNp, self.floorHandler)
        ret += (terrainColNp,)
    
        #Create left face
        sideLeft = CollisionPolygon(Point3(posx, posy+width, posz-height), Point3(posx, posy, posz-height),
                                Point3(posx, posy, posz), Point3(posx, posy+width, posz))
        sideLeftCol = CollisionNode(wallname)
        sideLeftCol.addSolid(sideLeft)
        sideLeftCol.setIntoCollideMask(BitMask32.bit(2))
        sideLeftColNp = self.render.attachNewNode(sideLeftCol)
        self.cTrav.addCollider(sideLeftColNp, self.wallHandler)
        ret += (sideLeftColNp,)
        
        #Create right face
        sideRight = CollisionPolygon(Point3(posx+length, posy+width, posz), Point3(posx+length, posy, posz),
                                Point3(posx+length, posy, posz-height), Point3(posx+length, posy+width, posz-height))
        sideRightCol = CollisionNode(wallname)
        sideRightCol.addSolid(sideRight)
        sideRightCol.setIntoCollideMask(BitMask32.bit(2))
        sideRightColNp = self.render.attachNewNode(sideRightCol)
        self.cTrav.addCollider(sideRightColNp, self.wallHandler)
        ret += (sideRightColNp,)
        
        #Create front face
        sideFront = CollisionPolygon(Point3(posx, posy+width, posz-height), Point3(posx, posy+width, posz),
                                Point3(posx+length, posy+width, posz), Point3(posx+length, posy+width, posz-height))
        sideFrontCol = CollisionNode(wallname)
        sideFrontCol.addSolid(sideFront)
        sideFrontCol.setIntoCollideMask(BitMask32.bit(2))
        sideFrontColNp = self.render.attachNewNode(sideFrontCol)
        self.cTrav.addCollider(sideFrontColNp, self.wallHandler)
        ret += (sideFrontColNp,)
        
        #Create back face
        sideBack = CollisionPolygon(Point3(posx, posy, posz), Point3(posx, posy, posz-height),
                                Point3(posx+length, posy, posz-height), Point3(posx+length, posy, posz))
        sideBackCol = CollisionNode(wallname)
        sideBackCol.addSolid(sideBack)
        sideBackCol.setIntoCollideMask(BitMask32.bit(2))
        sideBackColNp = self.render.attachNewNode(sideBackCol)
        self.cTrav.addCollider(sideBackColNp, self.wallHandler)
        ret += (sideBackColNp,)

        #Create bottom face
        sideBot = CollisionPolygon(Point3(posx, posy, posz-height), Point3(posx, posy+width, posz-height),
                                Point3(posx+length, posy+width, posz-height), Point3(posx+length, posy, posz-height))
        sideBotCol = CollisionNode(wallname)
        sideBotCol.addSolid(sideBot)
        sideBotCol.setIntoCollideMask(BitMask32.bit(2))
        sideBotColNp = self.render.attachNewNode(sideBotCol)
        self.cTrav.addCollider(sideBotColNp, self.wallHandler)
        ret += (sideBotColNp,)

        #Uncomment these lines to see the collision polygons.
        '''terrainColNp.show()
        sideLeftColNp.show()
        sideRightColNp.show()
        sideFrontColNp.show()
        sideBackColNp.show()
        sideBotColNp.show()'''

        return ret
        #Old way of creating box collisions (left here for reference)
        '''box = CollisionBox((posx+(length/2), posy+(width/2),-(posz+height/2)), length/2, width/2, height/2)
Beispiel #11
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)
        base.setBackgroundColor(0, 0, 0)

        self.accept("escape", sys.exit)  # Escape quits
        self.disableMouse()
        camera.setPosHpr(0, 0, 0, 0, 0, 0)

        lens = PerspectiveLens()
        lens.setFov(90, 60)
        lens.setNear(0.01)
        lens.setFar(100000)
        self.cam.node().setLens(lens)

        self.ballSize = 0.025
        self.cueLength = 0.2
        # self.ballRoot = render.attachNewNode("ballRoot")
        # #self.ball = loader.loadModel("models/ball")
        # self.ball = loader.loadModel("models/ball_0_center.egg")
        # #self.ball = loader.loadModel("models/ball.dae")
        # self.ball.setScale(ballSize, ballSize, ballSize)
        # self.ball.reparentTo(self.ballRoot)
        # #print(self.ball.getBounds())
        # #exit(1)
        # #self.ballSphere = self.ball.find("**/ball")
        # #print(self.ball.getScale()[0])
        # cs = CollisionSphere(0, 0, 0, 1)
        # self.ballSphere = self.ball.attachNewNode(CollisionNode('ball'))
        # self.ballSphere.node().addSolid(cs)

        # self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
        # self.ballSphere.node().setIntoCollideMask(BitMask32.bit(1))

        self.sceneIndex = 0
        self.planeInfo = PlaneScene(self.sceneIndex)

        self.planeScene = self.planeInfo.generateEggModel()
        self.planeScene.setTwoSided(True)
        self.planeScene.reparentTo(render)
        self.planeScene.hide()

        #get geometries from plane predictions
        planeTriangles, horizontalPlaneTriangles, self.gravityDirection = self.planeInfo.getPlaneTriangles(
        )

        # add pool balls
        self.ballRoots = []
        self.balls = []
        self.ballSpheres = []
        self.ballGroundRays = []
        for ballIndex in xrange(3):
            ballRoot = render.attachNewNode("ballRoot_" + str(ballIndex))
            ball = loader.loadModel("models/ball_" + str(ballIndex) +
                                    "_center.egg")
            ball.setScale(self.ballSize, self.ballSize, self.ballSize)

            cs = CollisionSphere(0, 0, 0, 1)
            ballSphere = ball.attachNewNode(
                CollisionNode('ball_' + str(ballIndex)))
            ballSphere.node().addSolid(cs)
            ballSphere.node().setFromCollideMask(
                BitMask32.bit(0) | BitMask32.bit(1) | BitMask32.bit(3)
                | BitMask32.bit(4))
            ballSphere.node().setIntoCollideMask(BitMask32.bit(1))

            ball.reparentTo(ballRoot)
            self.ballRoots.append(ballRoot)
            self.balls.append(ball)
            self.ballSpheres.append(ballSphere)

            ballGroundRay = CollisionRay()  # Create the ray
            ballGroundRay.setOrigin(0, 0, 0)  # Set its origin
            ballGroundRay.setDirection(
                self.gravityDirection[0], self.gravityDirection[1],
                self.gravityDirection[2])  # And its direction
            # Collision solids go in CollisionNode
            # Create and name the node
            ballGroundCol = CollisionNode('ball_ray_' + str(ballIndex))
            ballGroundCol.addSolid(ballGroundRay)  # Add the ray
            ballGroundCol.setFromCollideMask(
                BitMask32.bit(2))  # Set its bitmasks
            ballGroundCol.setIntoCollideMask(BitMask32.allOff())
            # Attach the node to the ballRoot so that the ray is relative to the ball
            # (it will always be 10 feet over the ball and point down)
            ballGroundColNp = ballRoot.attachNewNode(ballGroundCol)
            self.ballGroundRays.append(ballGroundColNp)

            ballRoot.hide()
            continue

        # Finally, we create a CollisionTraverser. CollisionTraversers are what
        # do the job of walking the scene graph and calculating collisions.
        # For a traverser to actually do collisions, you need to call
        # traverser.traverse() on a part of the scene. Fortunately, ShowBase
        # has a task that does this for the entire scene once a frame.  By
        # assigning it to self.cTrav, we designate that this is the one that
        # it should call traverse() on each frame.
        self.cTrav = CollisionTraverser()

        # Collision traversers tell collision handlers about collisions, and then
        # the handler decides what to do with the information. We are using a
        # CollisionHandlerQueue, which simply creates a list of all of the
        # collisions in a given pass. There are more sophisticated handlers like
        # one that sends events and another that tries to keep collided objects
        # apart, but the results are often better with a simple queue
        self.cHandler = CollisionHandlerQueue()
        # Now we add the collision nodes that can create a collision to the
        # traverser. The traverser will compare these to all others nodes in the
        # scene. There is a limit of 32 CollisionNodes per traverser
        # We add the collider, and the handler to use as a pair

        #self.cTrav.addCollider(self.ballSphere, self.cHandler)
        for ballSphere in self.ballSpheres:
            self.cTrav.addCollider(ballSphere, self.cHandler)
            continue
        for ballGroundRay in self.ballGroundRays:
            self.cTrav.addCollider(ballGroundRay, self.cHandler)
            continue
        #self.cTrav.addCollider(self.ballGroundColNp, self.cHandler)

        # Collision traversers have a built in tool to help visualize collisions.
        # Uncomment the next line to see it.
        #self.cTrav.showCollisions(render)

        # This section deals with lighting for the ball. Only the ball was lit
        # because the maze has static lighting pregenerated by the modeler
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.55, .55, .55, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(LVector3(0, 0, -1))
        directionalLight.setColor((0.375, 0.375, 0.375, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))

        for ballRoot in self.ballRoots:
            ballRoot.setLight(render.attachNewNode(ambientLight))
            ballRoot.setLight(render.attachNewNode(directionalLight))
            continue

        # This section deals with adding a specular highlight to the ball to make
        # it look shiny.  Normally, this is specified in the .egg file.
        m = Material()
        m.setSpecular((1, 1, 1, 1))
        m.setShininess(96)
        for ball in self.balls:
            ball.setMaterial(m, 1)
            continue

        # self.original = False
        # if self.original:
        #     camera.setPosHpr(0, 0, 25, 0, -90, 0)
        #     self.maze = loader.loadModel("models/maze")
        #     self.maze.reparentTo(render)
        #     self.walls = self.maze.find("**/wall_collide")
        #     self.walls.node().setIntoCollideMask(BitMask32.bit(0))
        #     self.walls.show()
        #     pass

        # create collision entities from plane predictions
        self.triNPs = []
        for triangleIndex, triangle in enumerate(planeTriangles):
            #print(triangleIndex)
            #for triangle in triangles:
            #print(triangle)
            tri = CollisionPolygon(
                Point3(triangle[0][0], triangle[0][1], triangle[0][2]),
                Point3(triangle[1][0], triangle[1][1], triangle[1][2]),
                Point3(triangle[2][0], triangle[2][1], triangle[2][2]))
            triNP = render.attachNewNode(
                CollisionNode('tri_' + str(triangleIndex)))
            triNP.node().setIntoCollideMask(BitMask32.bit(0))
            triNP.node().addSolid(tri)
            self.triNPs.append(triNP)
            #triNP.show()
            continue

        # create special collision entities for horizontal planes so that balls can fall on one horizontal plane and bounce on it
        for triangleIndex, triangle in enumerate(horizontalPlaneTriangles):
            #print(triangleIndex)
            #for triangle in triangles:
            #print(triangle)
            tri = CollisionPolygon(
                Point3(triangle[0][0], triangle[0][1], triangle[0][2]),
                Point3(triangle[1][0], triangle[1][1], triangle[1][2]),
                Point3(triangle[2][0], triangle[2][1], triangle[2][2]))
            triNP = render.attachNewNode(
                CollisionNode('ground_' + str(triangleIndex)))
            triNP.node().setIntoCollideMask(BitMask32.bit(2))
            triNP.node().addSolid(tri)
            self.triNPs.append(triNP)
            #triNP.show()
            continue

        # tri = CollisionPolygon(Point3(-1, 4, -1), Point3(2, 4, -1), Point3(2, 4, 2))
        # triNP = render.attachNewNode(CollisionNode('tri'))
        # triNP.node().setIntoCollideMask(BitMask32.bit(0))
        # triNP.node().addSolid(tri)
        # triNP.show()

        #self.planeScene.node().setIntoCollideMask(BitMask32.bit(0))
        # roomRootNP = self.planeScene
        # roomRootNP.flattenLight()
        # mesh = BulletTriangleMesh()
        # polygons = roomRootNP.findAllMatches("**/+GeomNode")

        # # p0 = Point3(-10, 4, -10)
        # # p1 = Point3(-10, 4, 10)
        # # p2 = Point3(10, 4, 10)
        # # p3 = Point3(10, 4, -10)
        # # mesh.addTriangle(p0, p1, p2)
        # # mesh.addTriangle(p1, p2, p3)

        # print(polygons)
        # for polygon in polygons:
        #     geom_node = polygon.node()
        #     #geom_node.reparentTo(self.render)
        #     #print(geom_node.getNumGeoms())
        #     ts = geom_node.getTransform()
        #     #print(ts)
        #     for geom in geom_node.getGeoms():
        #         mesh.addGeom(geom, ts)
        #         continue
        #     continue
        # #self.scene = roomRootNP
        # shape = BulletTriangleMeshShape(mesh, dynamic=False)
        # #shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        # room = BulletRigidBodyNode('scene')
        # room.addShape(shape)
        # #room.setLinearDamping(0.0)
        # #room.setFriction(0.0)
        # print(shape)
        # room.setDeactivationEnabled(False)
        # roomNP = render.attachNewNode(room)
        # roomNP.setPos(0, 0, 0)
        # roomNP.node().setIntoCollideMask(BitMask32.bit(0))
        # self.world = BulletWorld()
        # self.world.setGravity(Vec3(0, 0, 0))
        # self.world.attachRigidBody(roomNP.node())
        #room.setRestitution(1)

        #self.roomNP = self.scene

        # create the cue
        self.cueRoot = render.attachNewNode("cueRoot")
        self.cue = loader.loadModel("models/cue_center.egg")
        self.cue.setScale(self.cueLength * 3, self.cueLength * 3,
                          self.cueLength)
        self.cue.reparentTo(self.cueRoot)

        self.cuePos = (10, 0, 0)

        self.pickerNode = CollisionNode('mouseRay')
        # Attach that node to the camera since the ray will need to be positioned
        # relative to it
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        # Everything to be picked will use bit 1. This way if we were doing other
        # collision we could separate it
        self.pickerNode.setFromCollideMask(BitMask32.bit(2))
        self.pickerNode.setIntoCollideMask(BitMask32.allOff())
        self.pickerRay = CollisionRay()  # Make our ray
        # Add it to the collision node
        self.pickerNode.addSolid(self.pickerRay)
        # Register the ray as something that can cause collisions
        self.cTrav.addCollider(self.pickerNP, self.cHandler)

        self.accept("mouse1", self.hit)  # left-click grabs a piece

        # create holes
        self.holeLength = 0.06
        holePos, holeHpr = self.planeInfo.getHolePos()
        self.holeRoot = render.attachNewNode("holeRoot")
        #self.hole = loader.loadModel("models/hole_horizontal_center.egg")
        self.hole = loader.loadModel("models/hole_color.egg")
        #self.hole = loader.loadModel("models/billiards_hole_center.egg")
        self.hole.setScale(self.holeLength, self.holeLength, self.holeLength)
        self.hole.reparentTo(self.holeRoot)
        self.hole.setTwoSided(True)
        self.holeRoot.setPos(holePos[0], holePos[1], holePos[2])
        self.holeRoot.setHpr(holeHpr[0], holeHpr[1], holeHpr[2])
        #tex = loader.loadTexture('models/Black_Hole.jpg')
        #self.hole.setTexture(tex, 1)
        self.holeRoot.hide()

        ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 0.5)
        self.holeTube = self.hole.attachNewNode(CollisionNode('hole'))
        self.holeTube.node().addSolid(ct)
        self.holeTube.node().setFromCollideMask(BitMask32.allOff())
        self.holeTube.node().setIntoCollideMask(BitMask32.bit(4))
        #self.holeTube.show()

        # create portals
        inPortalPos, inPortalHpr, outPortalPos, outPortalHpr, self.portalNormal = self.planeInfo.getPortalPos(
        )
        self.portalLength = 0.06
        self.inPortalRoot = render.attachNewNode("inPortalRoot")
        self.inPortal = loader.loadModel("models/portal_2_center.egg")
        self.inPortal.setScale(self.portalLength, self.portalLength,
                               self.portalLength)
        self.inPortal.reparentTo(self.inPortalRoot)
        self.inPortalRoot.setPos(inPortalPos[0], inPortalPos[1],
                                 inPortalPos[2])
        self.inPortalRoot.setHpr(inPortalHpr[0], inPortalHpr[1],
                                 inPortalHpr[2])
        self.inPortalRoot.hide()

        ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 1)
        self.inPortalTube = self.inPortal.attachNewNode(
            CollisionNode('portal_in'))
        self.inPortalTube.node().addSolid(ct)
        self.inPortalTube.node().setFromCollideMask(BitMask32.allOff())
        self.inPortalTube.node().setIntoCollideMask(BitMask32.bit(3))
        #self.inPortalTube.hide()

        self.outPortalRoot = render.attachNewNode("outPortalRoot")
        self.outPortal = loader.loadModel("models/portal_2_center.egg")
        self.outPortal.setScale(self.portalLength, self.portalLength,
                                self.portalLength)
        self.outPortal.reparentTo(self.outPortalRoot)
        self.outPortalRoot.setPos(outPortalPos[0], outPortalPos[1],
                                  outPortalPos[2])
        self.outPortalRoot.setHpr(outPortalHpr[0], outPortalHpr[1],
                                  outPortalHpr[2])
        self.outPortalRoot.hide()

        ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 1)
        self.outPortalTube = self.outPortal.attachNewNode(
            CollisionNode('portal_out'))
        self.outPortalTube.node().addSolid(ct)
        self.outPortalTube.node().setFromCollideMask(BitMask32.allOff())
        self.outPortalTube.node().setIntoCollideMask(BitMask32.bit(3))
        #self.outPortalTube.hide()
        #self.inPortalTube.show()
        #self.outPortalTube.show()
        #self.holeTube.show()

        #self.cTrav.addCollider(self.holeTube, self.cHandler)

        # create background image
        background_image = loader.loadTexture('dump/' + str(self.sceneIndex) +
                                              '_image.png')
        cm = CardMaker('background')
        cm.setHas3dUvs(True)
        info = np.load('dump/' + str(self.sceneIndex) + '_info.npy')
        #self.camera = getCameraFromInfo(self.info)
        depth = 10.0
        sizeU = info[2] / info[0] * depth
        sizeV = info[6] / info[5] * depth
        cm.setFrame(Point3(-sizeU, depth, -sizeV),
                    Point3(sizeU, depth, -sizeV), Point3(sizeU, depth, sizeV),
                    Point3(-sizeU, depth, sizeV))
        self.card = self.render.attachNewNode(cm.generate())
        self.card.setTransparency(True)
        self.card.setTexture(background_image)
        self.card.hide()

        self.ballGroundMap = {}
        self.ballBouncing = np.full(len(self.balls), 3)

        self.started = False
        self.start()

        #self.hitIndex = -1

        self.showing = 'parts'
        self.showingProgress = 0

        partsScene = PartsScene(self.sceneIndex)
        self.planeNPs, self.planeCenters = partsScene.generateEggModel()
        return
Beispiel #12
0
    def __init__(self, entity, mesh=None, center=(0,0,0)):
        super().__init__()
        center = Vec3(center)
        if mesh == None and entity.model:
            mesh = entity.model
            # print('''auto generating mesh collider from entity's mesh''')

        self.node_path = entity.attachNewNode(CollisionNode('CollisionNode'))
        self.collision_polygons = []

        if isinstance(mesh, Mesh):
            if mesh.triangles:
                triangles = mesh.triangles
                if not isinstance(mesh.triangles[0], tuple):
                    triangles = [triangles[i:i + 3] for i in range(0, len(triangles), 3)] # group into groups of three

                for tri in triangles:
                    if len(tri) == 3:
                        poly = CollisionPolygon(
                            Vec3(mesh.vertices[tri[2]]),
                            Vec3(mesh.vertices[tri[1]]),
                            Vec3(mesh.vertices[tri[0]]),
                            )
                        self.collision_polygons.append(poly)
                    elif len(tri) == 4:
                        poly = CollisionPolygon(
                            Vec3(mesh.vertices[tri[3]]),
                            Vec3(mesh.vertices[tri[2]]),
                            Vec3(mesh.vertices[tri[1]]),
                            Vec3(mesh.vertices[tri[0]]))
                        self.collision_polygons.append(poly)


            elif mesh.mode == 'triangle': # no triangle list, so take 3 and 3 vertices
                for i in range(0, len(mesh.vertices), 3):
                    poly = CollisionPolygon(
                        Vec3(mesh.vertices[i+2]),
                        Vec3(mesh.vertices[i+1]),
                        Vec3(mesh.vertices[i]),
                        )
                    self.collision_polygons.append(poly)


            else:
                print('error: mesh collider does not support', mesh.mode, 'mode')
                return None


        elif isinstance(mesh, NodePath):
            from panda3d.core import GeomVertexReader
            verts = []
            geomNodeCollection = mesh.findAllMatches('**/+GeomNode')
            for nodePath in geomNodeCollection:
                geomNode = nodePath.node()
                for i in range(geomNode.getNumGeoms()):
                    geom = geomNode.getGeom(i)
                    vdata = geom.getVertexData()
                    for i in range(geom.getNumPrimitives()):
                        prim = geom.getPrimitive(i)
                        vertex_reader = GeomVertexReader(vdata, 'vertex')
                        prim = prim.decompose()

                        for p in range(prim.getNumPrimitives()):
                            s = prim.getPrimitiveStart(p)
                            e = prim.getPrimitiveEnd(p)
                            for i in range(s, e):
                                vi = prim.getVertex(i)
                                vertex_reader.setRow(vi)
                                verts.append(vertex_reader.getData3())

            for i in range(0, len(verts)-3, 3):
                p = CollisionPolygon(Vec3(verts[i+2]), Vec3(verts[i+1]), Vec3(verts[i]))
                self.collision_polygons.append(p)


        node = self.node_path.node()
        for poly in self.collision_polygons:
            node.addSolid(poly)
        self.visible = False
Beispiel #13
0
    def __init__(self, entity, mesh=None, center=(0,0,0)):
        super().__init__()
        center = Vec3(center)
        if mesh == None and entity.model:
            mesh = entity.model
            # print('''auto generating mesh collider from entity's mesh''')

        # from ursina import Mesh     # this part is obsolete if I use the old obj loading
        # if not isinstance(mesh, Mesh):
        #     from ursina import mesh_importer
        #     mesh = eval(mesh_importer.obj_to_ursinamesh(name=mesh.name, save_to_file=False))
        #     flipped_verts = [v*Vec3(-1,1,1) for v in mesh.vertices] # have to flip it on x axis for some reason
        #     mesh.vertices = flipped_verts
        self.node_path = entity.attachNewNode(CollisionNode('CollisionNode'))
        self.node = self.node_path.node()
        self.collision_polygons = list()

        if isinstance(mesh, Mesh):
            if mesh.triangles:
                for tri in mesh.triangles:
                    if len(tri) == 3:
                        poly = CollisionPolygon(
                            Vec3(mesh.vertices[tri[2]]),
                            Vec3(mesh.vertices[tri[1]]),
                            Vec3(mesh.vertices[tri[0]]),
                            )
                        self.collision_polygons.append(poly)
                    elif len(tri) == 4:
                        poly = CollisionPolygon(
                            Vec3(mesh.vertices[tri[2]]),
                            Vec3(mesh.vertices[tri[1]]),
                            Vec3(mesh.vertices[tri[0]]))
                        self.collision_polygons.append(poly)
                        poly = CollisionPolygon(
                            Vec3(mesh.vertices[tri[0]]),
                            Vec3(mesh.vertices[tri[3]]),
                            Vec3(mesh.vertices[tri[2]]))
                        self.collision_polygons.append(poly)

            elif mesh.mode == 'triangle':
                for i in range(0, len(mesh.vertices), 3):
                    poly = CollisionPolygon(
                        Vec3(mesh.vertices[i+2]),
                        Vec3(mesh.vertices[i+1]),
                        Vec3(mesh.vertices[i]),
                        )
                    self.collision_polygons.append(poly)


            else:
                print('error: mesh collider does not support', mesh.mode, 'mode')
                return None


        elif isinstance(mesh, NodePath):
            from panda3d.core import GeomVertexReader
            verts = []
            geomNodeCollection = mesh.findAllMatches('**/+GeomNode')
            for nodePath in geomNodeCollection:
                geomNode = nodePath.node()
                for i in range(geomNode.getNumGeoms()):
                    geom = geomNode.getGeom(i)
                    vdata = geom.getVertexData()
                    for i in range(geom.getNumPrimitives()):
                        prim = geom.getPrimitive(i)
                        vertex_reader = GeomVertexReader(vdata, 'vertex')
                        prim = prim.decompose()

                        for p in range(prim.getNumPrimitives()):
                            s = prim.getPrimitiveStart(p)
                            e = prim.getPrimitiveEnd(p)
                            for i in range(s, e):
                                vi = prim.getVertex(i)
                                vertex_reader.setRow(vi)
                                verts.append(vertex_reader.getData3())

            for i in range(0, len(verts)-3, 3):
                p = CollisionPolygon(Vec3(verts[i+2]), Vec3(verts[i+1]), Vec3(verts[i]))
                self.collision_polygons.append(p)


        for poly in self.collision_polygons:
            self.node.addSolid(poly)
        self.visible = False
Beispiel #14
0
    def drawBattle(self, battle):
        if not self.battleReady:
            self.battle = battle
            self.battleRender = NodePath('battleRender')
            self.battleRender.reparentTo(self.render)
            self.battleEventHandler = BattleEventHandler(self)

            self.camera.setPos(0, 0, 40)
            self.camera.setHpr(0, -90, 0)

            self.blackMaterial = Material()
            self.blackMaterial.setDiffuse(VBase4(0, 0, 0, 1))
            self.whiteMaterial = Material()
            self.whiteMaterial.setDiffuse(VBase4(256, 256, 256, 1))

            self.battleBoard = self.loader.loadModel('models/plane')
            self.battleBoard.setPos(0, 0, 4)
            self.battleBoard.setScale(2)
            self.battleBoard.setMaterial(self.blackMaterial)
            self.battleBoard.reparentTo(self.render)

            self.resources.setText('')

            self.battlePhase = 'initial'
            self.battleTurn = 0
            self.battlePlayedTurns = 0

            self.clicked = None
            self.isMoving = False
            self.mover = None

            self.battleFields = []
            for x in range(0, 8):
                self.battleFields.append([])
                for y in range(0, 8):
                    field = self.loader.loadModel('models/plane')
                    posX = x * 2.4 - 8.5
                    posY = y * 2.4 - 8.5
                    field.setPos(posX, posY, 4.2)
                    field.setScale(0.11)

                    cs = CollisionPolygon(Point3(-10, -10, 0),
                                          Point3(-10, 10, 0),
                                          Point3(10, 10, 0),
                                          Point3(10, -10, 0))
                    cnodePath = field.attachNewNode(CollisionNode('cnode'))
                    cnodePath.node().addSolid(cs)
                    field.setTag('clickable', 'true')
                    field.setTag('field', 'true')
                    field.setTag('x', str(x))
                    field.setTag('y', str(y))
                    field.reparentTo(self.battleRender)
                    self.battleFields[x].append(field)

            self.battleReady = True

        if self.mover and not self.mover.is_alive():
            self.mover = None
            self.isMoving = False
            black = False
            white = False
            for x in self.battleFields:
                for y in x:
                    child = y.getChildren()[-1]
                    if child.hasTag('piece'):
                        if child.getMaterial() == self.blackMaterial:
                            black = True
                        if child.getMaterial() == self.whiteMaterial:
                            white = True
                        if white and black:
                            return
            if not white:
                print('black wins')
                turn = self.game.turn
                self.game.players[turn ^ 1].figures.remove(self.whiteTroops)
                self.whiteTroops.model.removeNode()
            if not black:
                print('white wins')
                turn = self.game.turn
                field = self.blackTroops.field
                self.game.players[turn].figures.remove(self.blackTroops)
                self.blackTroops.model.removeNode()
                field.put(self.whiteTroops)
            if not black or not white:
                self.pop()