Esempio n. 1
0
 def newPlayerShip(self, account, accountEntity):
     ship = sandbox.createEntity()
     component = ships.PilotComponent()
     component.account = account
     component.accountEntityID = accountEntity.id
     ship.addComponent(component)
     component = ships.BulletPhysicsComponent()
     component.bulletShape = BulletSphereShape(5)
     component.node = BulletRigidBodyNode(account.name)
     component.node.setMass(1.0)
     component.node.addShape(component.bulletShape)
     component.nodePath = universals.solarSystemRoot.attachNewNode(component.node)
     physics.addBody(component.node)
     position = sandbox.get_system(solarSystem.SolarSystemSystem).solarSystemRoot.find("**/Earth").getPos()
     component.nodePath.setPos(position + Point3(6671, 0, 0))
     component.node.setLinearVelocity(Vec3(0, 7.72983, 0))
     ship.addComponent(component)
     component = ships.ThrustComponent()
     ship.addComponent(component)
     component = ships.InfoComponent()
     ship.addComponent(component)
     messenger.send("shipGenerated", [ship])
     messenger.send("putPlayerOnShip", [accountEntity.id, ship.id])
     #TODO Transmit player's ship data
     #TODO Broadcast new ship data
     #TODO Prioritize updating new client of surroundings
Esempio n. 2
0
    def begin(self):
        if self.cReader.dataAvailable():
            datagram = NetDatagram()  # catch the incoming data in this instance
            # Check the return value; if we were threaded, someone else could have
            # snagged this data before we did
            if self.cReader.getData(datagram):
                myIterator = PyDatagramIterator(datagram)
                msgID = myIterator.getUint8()

                #If not in our protocol range then we just reject
                if msgID < 0 or msgID > 200:
                    return

                self.lastAck[datagram.getAddress()] = datetime.datetime.now()
                #TODO Switch to ip address and port

                #Order of these will need to be optimized later
                #We now pull out the rest of our headers
                remotePacketCount = myIterator.getUint8()
                ack = myIterator.getUint8()
                acks = myIterator.getUint16()
                hashID = myIterator.getUint16()

                if msgID == protocol.LOGIN:
                    username = myIterator.getString()
                    password = myIterator.getString()
                    if username not in accountEntities:
                        entity = sandbox.createEntity()
                        component = AccountComponent()
                        component.name = username
                        component.passwordHash = password
                        if not accountEntities:
                            component.owner = True
                        component.address = datagram.getAddress()
                        entity.addComponent(component)
                        accountEntities[username] = entity.id
                        log.info("New player " + username + " logged in.")
                        #
                        self.activePlayers.append(component)
                        self.activeConnections[component.address] = component
                        ackDatagram = protocol.loginAccepted(entity.id)
                        self.sendData(ackDatagram, datagram.getAddress())
                        #TODO: Send initial states?
                        messenger.send("newPlayerShip", [component, entity])
                    else:
                        component = sandbox.entities[accountEntities[username]].get_component(AccountComponent)
                        if component.passwordHash != password:
                            log.info("Player " + username + " has the wrong password.")
                        else:
                            component.connection = datagram.getConnection()
                            log.info("Player " + username + " logged in.")
Esempio n. 3
0
    def processPacket(self, msgID, remotePacketCount, ack, acks, hashID,
                      serialized, address):
        #If not in our protocol range then we just reject
        if msgID < 0 or msgID > 200:
            return
        data = protocol.readProto(msgID, serialized)
        if data is None and msgID != protocol.LOGIN:
            log.warning("Package reading error: " + str(msgID) + " " +
                        serialized)
            return

        #Order of these will need to be optimized later
        if msgID == protocol.LOGIN:
            #TODO, if connection previously existed, reconnect
            #TODO: send current mission status.
            #TODO: Move ship select to separate function
            ackDatagram = protocol.shipClasses(shipSystem.shipClasses)
            self.sendData(ackDatagram, address)
            ackDatagram = protocol.playerShipStations()
            self.sendData(ackDatagram, address)
            entity = sandbox.createEntity()
            component = AccountComponent()
            component.address = address
            entity.addComponent(component)
            self.activeConnections[component.address] = component
        elif msgID == protocol.REQUEST_CREATE_SHIP:
            sandbox.send('spawnShip', [data.name, data.className, True])
        elif msgID == protocol.REQUEST_STATIONS:
            entity = sandbox.entities[data.ship[0].id]
            #info = entity.getComponent(shipComponents.InfoComponent)
            player = entity.getComponent(shipComponents.PlayerComponent)
            stations = data.ship[0].stations
            for stationName in universals.playerStations:
                if getattr(player, stationName) != 0:
                    print "Resend ship select window"
            sandbox.send('setPlayerStations',
                         [address, data.ship[0].id, stations])
        elif msgID == protocol.SET_THROTTLE:
            sandbox.send('setThrottle', [self.playerMap[address], data])
        elif msgID == protocol.SET_TARGET:
            sandbox.send('setTarget', [self.playerMap[address], data])
        '''if username not in accountEntities:
Esempio n. 4
0
    def process_packet(
        self, msgID, remotePacketCount,
        ack, acks, hashID, serialized, address
    ):
        #If not in our protocol range then we just reject
        if msgID < 0 or msgID > 200:
            return
        data = protocol_old.readProto(msgID, serialized)
        if data is None and msgID != protocol_old.LOGIN:
            log.warning("Package reading error: " + str(msgID) + " " + serialized)
            return

        #Order of these will need to be optimized later
        if msgID == protocol_old.LOGIN:
            #TODO, if connection previously existed, reconnect
            #TODO: send current mission status.
            #TODO: Move ship select to separate function
            ackDatagram = protocol_old.shipClasses(shipSystem.shipClasses)
            self.sendData(ackDatagram, address)
            ackDatagram = protocol_old.playerShipStations()
            self.sendData(ackDatagram, address)
            entity = sandbox.createEntity()
            component = AccountComponent()
            component.address = address
            entity.addComponent(component)
            self.activeConnections[component.address] = component
        elif msgID == protocol_old.REQUEST_CREATE_SHIP:
            sandbox.send('spawnShip', [data.name, data.className, True])
        elif msgID == protocol_old.REQUEST_STATIONS:
            entity = sandbox.entities[data.ship[0].id]
            #info = entity.get_component(shipComponents.InfoComponent)
            player = entity.get_component(shipComponents.PlayerComponent)
            stations = data.ship[0].stations
            for stationName in universals.playerStations:
                if getattr(player, stationName) != 0:
                    log.info("Resend ship select window")
            sandbox.send('setPlayerStations', [address, data.ship[0].id, stations])
        elif msgID == protocol_old.SET_THROTTLE:
            sandbox.send('setThrottle', [self.playerMap[address], data])
        elif msgID == protocol_old.SET_TARGET:
            sandbox.send('setTarget', [self.playerMap[address], data])
        '''if username not in accountEntities:
Esempio n. 5
0
    def spawnShip(
        self, shipName, shipClass, spawnPoint=LPoint3d(0, 0, 0),
        playerShip=False, entityid=-1, turrets=None
    ):
        if shipName == '' or shipClass == '':
            return
        if entityid == -1:
            ship = sandbox.createEntity()
        else:
            ship = sandbox.addEntity(entityid)
        if playerShip:
            component = shipComponents.PlayerComponent()
            ship.addComponent(component)
        else:
            component = shipComponents.AIPilotComponent()
            ship.addComponent(component)
        shape = BulletSphereShape(1)
        velocity = Vec3(0, 0, 0)
        truex = spawnPoint.getX()
        truey = spawnPoint.getY()
        component = physics.addNewBody(shipName, shape, shipClasses[shipClass]['mass'], truex, truey, velocity)
        ship.addComponent(component)
        component = shipComponents.ThrustComponent()
        for engine in shipClasses[shipClass]['engines']:
            component.forward += engine['thrust'] / CONVERT
        component.heading = shipClasses[shipClass]['torque'] / CONVERT
        ship.addComponent(component)
        component = shipComponents.InfoComponent()
        component.shipClass = shipClass
        component.name = shipName
        ship.addComponent(component)

        component = graphicsComponents.RenderComponent()
        #component.mesh = sandbox.base.loader.loadModel('ships/' + shipClasses[shipClass]['path'])
        component.mesh = Actor('ships/' + shipClasses[shipClass]['path'])
        component.mesh.reparentTo(sandbox.ships)
        component.mesh.getPart('modelRoot').setPythonTag('entityID', ship.id)
        component.mesh.setScale(1 / CONVERT)
        if universals.runClient and not playerShip:
            sandbox.send('makePickable', [component.mesh])
        ship.addComponent(component)

        # Load turret info here. Also check if gun is actually on ship!
        def containsAny(string, check):
            return 1 in [c in string for c in check]

        turretsComponent = shipComponents.TurretsComponent()

        if not turrets:
            for weapon in shipClasses[shipClass]['weapons']:
                turretEntity = sandbox.createEntity()
                turret = shipComponents.TurretComponent()
                if not containsAny(shipClasses[shipClass]['weapons'][weapon]['decay'], 'abcdefghijklmnopqrstuvwyz'):
                    turret.decay = lambda x: eval(shipClasses[shipClass]['weapons'][weapon]['decay'])
                turret.name = weapon
                turret.damage = shipClasses[shipClass]['weapons'][weapon]['damage']
                if 'traverser' in shipClasses[shipClass]['weapons'][weapon]['joints']:
                    turret.traverser = shipClasses[shipClass]['weapons'][weapon]['joints']['traverser']['axes']
                if 'elevator' in shipClasses[shipClass]['weapons'][weapon]['joints']:
                    turret.elevator = shipClasses[shipClass]['weapons'][weapon]['joints']['elevator']['axes']
                turret.parentID = ship.id
                turretEntity.addComponent(turret)
                turretsComponent.turretIDs.append(turretEntity.id)
        if turrets:
            for t in turrets:
                turretEntity = sandbox.addEntity(t.turretid)
                turret = shipComponents.TurretComponent()
                weapon = t.turretName
                if not containsAny(shipClasses[shipClass]['weapons'][weapon]['decay'], 'abcdefghijklmnopqrstuvwyz'):
                    turret.decay = lambda x: eval(shipClasses[shipClass]['weapons'][weapon]['decay'])
                turret.name = weapon
                turret.damage = shipClasses[shipClass]['weapons'][weapon]['damage']
                if 'traverser' in shipClasses[shipClass]['weapons'][weapon]['joints']:
                    turret.traverser = shipClasses[shipClass]['weapons'][weapon]['joints']['traverser']['axes']
                if 'elevator' in shipClasses[shipClass]['weapons'][weapon]['joints']:
                    turret.elevator = shipClasses[shipClass]['weapons'][weapon]['joints']['elevator']['axes']
                turret.parentID = ship.id
                turretEntity.addComponent(turret)
                turretsComponent.turretIDs.append(turretEntity.id)

        ship.addComponent(turretsComponent)

        #sandbox.send("shipGenerated", [ship, playerShip])
        log.info("Ship spawned: " + shipName + " " + shipClass)
Esempio n. 6
0
    def generateNode(self, name, DB, parentNode):
        log.debug("Setting up " + name)
        bodyEntity = sandbox.createEntity()
        component = CelestialComponent()
        if DB["type"] == "solid":
            body = Body(name)
        elif DB["type"] == "moon":
            body = Body(name)
            body.kind = "moon"
        elif DB["type"] == "star":
            body = Star(name)
            body.absoluteM = DB["absolute magnitude"]
            body.spectral = DB["spectral"]
        elif DB["type"] == "barycenter":
            body = BaryCenter(name)

        component.kind = TYPES[DB["type"]]

        if DB["type"] != "barycenter":
            component.mass = DB["mass"]
            body.radius = DB["radius"]
            body.rotation = DB["rotation"]

        if "orbit" in DB:
            component.orbit = DB["orbit"]
            body.period = DB["period"]
            # body.setPos(self.get2DBodyPosition(component, universals.day))
            component.truePos = self.get2DBodyPosition(component, universals.day)
            if name == "Earth":
                # universals.spawn = component.truePos + LPoint3d(0, 6671, 0)
                universals.spawn = component.truePos + LPoint3d(6671, 0, 0)

        if parentNode == universals.solarSystemRoot:
            universals.defaultSOIid = bodyEntity.id
            component.soi = 0
        elif DB["type"] != "star" or DB["type"] != "barycenter":
            component.soi = self.getSOI(component.mass, self.bodies[0].mass, component.orbit["a"])

        body.type = DB["type"]
        body.reparentTo(parentNode)
        component.nodePath = body
        self.bodies.append(component)
        bodyEntity.addComponent(component)

        if universals.runClient and DB["type"] == "star":
            component = graphicsComponents.RenderComponent()
            # component.mesh = NodePath(name)
            # self.sphere.copyTo(component.mesh)
            # component.mesh = shapeGenerator.Sphere(body.radius, 128, name)
            component.mesh = shapeGenerator.Sphere(body.radius, 64, name)
            # component.mesh.setScale(body.radius)
            component.mesh.reparentTo(sandbox.base.render)
            sandbox.send("makePickable", [component.mesh])
            # texture = sandbox.base.loader.loadTexture('planets/' + DB['texture'])
            # texture.setMinfilter(Texture.FTLinearMipmapLinear)
            # ts1 = TextureStage('textures1')
            # ts1.setMode(TextureStage.MGlow)
            # component.mesh.setTexture(ts1, texture)
            # component.mesh.setTexture(texture, 1)

            component.light = component.mesh.attachNewNode(PointLight("sunPointLight"))
            component.light.node().setColor(Vec4(1, 1, 1, 1))
            sandbox.base.render.setLight(component.light)
            bodyEntity.addComponent(component)

            # Shader test
            componentStar = graphicsComponents.StarRender()
            componentStar.noise_texture = Texture("noise")
            componentStar.noise_texture.setup2dTexture()
            img = PNMImage(1024, 1024)
            for y in range(1024):
                for x in range(1024):
                    img.setXel(x, y, componentStar.noise.noise(x, y))
                    # print componentStar.noise.noise(x, y)
            componentStar.noise_texture.load(img)
            # componentStar.noise_texture.write('test.png')
            # component.mesh.setTexture(componentStar.noise_texture, 1)

            texture = sandbox.base.loader.loadTexture("planets/" + DB["texture"])
            ts1 = TextureStage("textures1")
            ts1.setMode(TextureStage.MGlow)
            component.mesh.setTexture(ts1, componentStar.noise_texture)
            # component.mesh.setTexture(ts1, texture)

            component.mesh.setShaderInput("time", universals.get_day_in_seconds())
            shaders = Shader.load(Shader.SLGLSL, "vortexVertex.glsl", "starFrag.glsl")
            component.mesh.setShader(shaders)
            sandbox.send("makePickable", [component.mesh])

        if universals.runClient and (DB["type"] == "solid" or DB["type"] == "moon"):
            component = graphicsComponents.RenderComponent()
            # component.mesh = shapeGenerator.Sphere(body.radius, 128, name)
            # component.mesh = shapeGenerator.Sphere(body.radius, 64, name)
            component.mesh = surface_mesh.make_planet(name=name, scale=body.radius)
            # sandbox.send('makePickable', [component.mesh])
            sandbox.send("makePickable", [component.mesh.node_path])
            # component.mesh.setScale(body.radius)
            component.mesh.reparent_to(sandbox.base.render)
            # Doing world text
            text = TextNode("node name")
            text.setText(name)
            # textNodePath = component.mesh.attachNewNode(text)
            textNodePath = component.mesh.node_path.attachNewNode(text)
            textNodePath.setScale(0.07)

            component.mesh.set_textures(DB["texture"], night_path=DB["night"], gloss_path=DB["spec"])

            component.mesh.set_ambient(1, 1, 1, 1)
            component.mesh.set_diffuse(1, 1, 1, 1)
            component.mesh.set_specular(1, 1, 1, 1)
            component.mesh.set_shininess(100)

            """if '#' in DB['texture']:
                component.mesh.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition)
                component.mesh.setTexProjector(TextureStage.getDefault(), sandbox.base.render, component.mesh)
                component.mesh.setTexScale(TextureStage.getDefault(), 1,  1, -1)
                component.mesh.setTexHpr(TextureStage.getDefault(), 90, -18, 90)
                #self.mesh.setHpr(0, 90, 0)
                texture = loader.loadCubeMap('planets/' + DB['texture'])
            else:
                texture = sandbox.base.loader.loadTexture('planets/' + DB['texture'])
            #texture.setMinfilter(Texture.FTLinearMipmapLinear)
            component.mesh.setTexture(texture, 1)"""
            """if "atmosphere" in DB:
                component.atmosphere = shapeGenerator.Sphere(-1, 128)
                component.atmosphere.reparentTo(render)
                component.atmosphere.setScale(body.radius * 1.025)
                outerRadius = component.atmosphere.getScale().getX()
                scale = 1 / (outerRadius - component.body.getScale().getX())
                component.atmosphere.setShaderInput("fOuterRadius", outerRadius)
                component.atmosphere.setShaderInput("fInnerRadius", component.mesh.getScale().getX())
                component.atmosphere.setShaderInput("fOuterRadius2", outerRadius * outerRadius)
                component.atmosphere.setShaderInput("fInnerRadius2",
                    component.mesh.getScale().getX()
                    * component.mesh.getScale().getX())

                component.atmosphere.setShaderInput("fKr4PI",
                    0.000055 * 4 * 3.14159)
                component.atmosphere.setShaderInput("fKm4PI",
                    0.000015 * 4 * 3.14159)

                component.atmosphere.setShaderInput("fScale", scale)
                component.atmosphere.setShaderInput("fScaleDepth", 0.25)
                component.atmosphere.setShaderInput("fScaleOverScaleDepth", scale / 0.25)

                # Currently hard coded in shader
                component.atmosphere.setShaderInput("fSamples", 10.0)
                component.atmosphere.setShaderInput("nSamples", 10)
                # These do sunsets and sky colors
                # Brightness of sun
                ESun = 15
                # Reyleight Scattering (Main sky colors)
                component.atmosphere.setShaderInput("fKrESun", 0.000055 * ESun)
                # Mie Scattering -- Haze and sun halos
                component.atmosphere.setShaderInput("fKmESun", 0.000015 * ESun)
                # Color of sun
                component.atmosphere.setShaderInput("v3InvWavelength", 1.0 / math.pow(0.650, 4),
                                                  1.0 / math.pow(0.570, 4),
                                                  1.0 / math.pow(0.465, 4))
                #component.atmosphere.setShader(Shader.load("atmo.cg"))"""
            bodyEntity.addComponent(component)
        log.info(name + " set Up")
        if "bodies" in DB:
            for bodyName, bodyDB in DB["bodies"].items():
                self.generateNode(bodyName, bodyDB, body)
Esempio n. 7
0
    def spawnShip(self,
                  shipName,
                  shipClass,
                  spawnPoint=LPoint3d(0, 0, 0),
                  playerShip=False,
                  entityid=-1,
                  turrets=None):
        if shipName == '' or shipClass == '':
            return
        if entityid == -1:
            ship = sandbox.createEntity()
        else:
            ship = sandbox.addEntity(entityid)
        if playerShip:
            component = shipComponents.PlayerComponent()
            ship.addComponent(component)
        else:
            component = shipComponents.AIPilotComponent()
            ship.addComponent(component)
        shape = BulletSphereShape(1)
        velocity = Vec3(0, 0, 0)
        truex = spawnPoint.getX()
        truey = spawnPoint.getY()
        component = physics.addNewBody(shipName, shape,
                                       shipClasses[shipClass]['mass'], truex,
                                       truey, velocity)
        ship.addComponent(component)
        component = shipComponents.ThrustComponent()
        for engine in shipClasses[shipClass]['engines']:
            component.forward += engine['thrust'] / CONVERT
        component.heading = shipClasses[shipClass]['torque'] / CONVERT
        ship.addComponent(component)
        component = shipComponents.InfoComponent()
        component.shipClass = shipClass
        component.name = shipName
        ship.addComponent(component)

        component = graphicsComponents.RenderComponent()
        #component.mesh = sandbox.base.loader.loadModel('ships/' + shipClasses[shipClass]['path'])
        component.mesh = Actor('ships/' + shipClasses[shipClass]['path'])
        component.mesh.reparentTo(sandbox.ships)
        component.mesh.getPart('modelRoot').setPythonTag('entityID', ship.id)
        component.mesh.setScale(1 / CONVERT)
        if universals.runClient and not playerShip:
            sandbox.send('makePickable', [component.mesh])
        ship.addComponent(component)

        # Load turret info here. Also check if gun is actually on ship!
        def containsAny(string, check):
            return 1 in [c in string for c in check]

        turretsComponent = shipComponents.TurretsComponent()

        if not turrets:
            for weapon in shipClasses[shipClass]['weapons']:
                turretEntity = sandbox.createEntity()
                turret = shipComponents.TurretComponent()
                if not containsAny(
                        shipClasses[shipClass]['weapons'][weapon]['decay'],
                        'abcdefghijklmnopqrstuvwyz'):
                    turret.decay = lambda x: eval(shipClasses[shipClass][
                        'weapons'][weapon]['decay'])
                turret.name = weapon
                turret.damage = shipClasses[shipClass]['weapons'][weapon][
                    'damage']
                if 'traverser' in shipClasses[shipClass]['weapons'][weapon][
                        'joints']:
                    turret.traverser = shipClasses[shipClass]['weapons'][
                        weapon]['joints']['traverser']['axes']
                if 'elevator' in shipClasses[shipClass]['weapons'][weapon][
                        'joints']:
                    turret.elevator = shipClasses[shipClass]['weapons'][
                        weapon]['joints']['elevator']['axes']
                turret.parentID = ship.id
                turretEntity.addComponent(turret)
                turretsComponent.turretIDs.append(turretEntity.id)
        if turrets:
            for t in turrets:
                turretEntity = sandbox.addEntity(t.turretid)
                turret = shipComponents.TurretComponent()
                weapon = t.turretName
                if not containsAny(
                        shipClasses[shipClass]['weapons'][weapon]['decay'],
                        'abcdefghijklmnopqrstuvwyz'):
                    turret.decay = lambda x: eval(shipClasses[shipClass][
                        'weapons'][weapon]['decay'])
                turret.name = weapon
                turret.damage = shipClasses[shipClass]['weapons'][weapon][
                    'damage']
                if 'traverser' in shipClasses[shipClass]['weapons'][weapon][
                        'joints']:
                    turret.traverser = shipClasses[shipClass]['weapons'][
                        weapon]['joints']['traverser']['axes']
                if 'elevator' in shipClasses[shipClass]['weapons'][weapon][
                        'joints']:
                    turret.elevator = shipClasses[shipClass]['weapons'][
                        weapon]['joints']['elevator']['axes']
                turret.parentID = ship.id
                turretEntity.addComponent(turret)
                turretsComponent.turretIDs.append(turretEntity.id)

        ship.addComponent(turretsComponent)

        #sandbox.send("shipGenerated", [ship, playerShip])
        log.info("Ship spawned: " + shipName + " " + shipClass)
Esempio n. 8
0
    def generateNode(self, name, DB, parentNode):
        log.debug("Setting up " + name)
        bodyEntity = sandbox.createEntity()
        if DB['type'] == 'solid':
            body = Body(name)
        elif DB['type'] == 'moon':
            body = Body(name)
            body.kind = "moon"
        elif DB['type'] == 'star':
            body = Star(name)
            body.absoluteM = DB['absolute magnitude']
            body.spectral = DB['spectral']
        elif DB['type'] == 'barycenter':
            body = BaryCenter(name)

        if DB['type'] != "barycenter":
            body.mass = DB['mass']
            body.radius = DB['radius']
            body.rotation = DB['rotation']

        if 'orbit' in DB:
            body.hasOrbit = True
            body.orbit = DB['orbit']
            body.period = DB['period']
        else:
            body.hasOrbit = False

        body.type = DB['type']
        body.reparentTo(parentNode)
        bodyEntity.addComponent(body)

        if universals.runClient and DB['type'] == 'star':
            component = PlanetRender()
            component.body = shapeGenerator.Sphere(1, 128)
            component.body.reparentTo(render)
            component.light = render.attachNewNode(PointLight("sunPointLight"))
            render.setLight(component.light)

        if universals.runClient and (DB['type'] == 'solid' or DB['type'] == 'moon'):
            component = PlanetRender()
            component.body = shapeGenerator.Sphere(1, 128)
            component.body.setScale(body.radius)
            component.body.reparentTo(render)
            if "atmosphere" in DB:
                component.atmosphere = shapeGenerator.Sphere(-1, 128)
                component.atmosphere.reparentTo(render)
                component.atmosphere.setScale(body.radius * 1.025)
                outerRadius = component.atmosphere.getScale().getX()
                scale = 1 / (outerRadius - component.body.getScale().getX())
                component.atmosphere.setShaderInput("fOuterRadius", outerRadius)
                component.atmosphere.setShaderInput("fInnerRadius", component.body.getScale().getX())
                component.atmosphere.setShaderInput("fOuterRadius2", outerRadius * outerRadius)
                component.atmosphere.setShaderInput("fInnerRadius2",
                    component.body.getScale().getX()
                    * component.body.getScale().getX())

                component.atmosphere.setShaderInput("fKr4PI",
                    0.000055 * 4 * 3.14159)
                component.atmosphere.setShaderInput("fKm4PI",
                    0.000015 * 4 * 3.14159)

                component.atmosphere.setShaderInput("fScale", scale)
                component.atmosphere.setShaderInput("fScaleDepth", 0.25)
                component.atmosphere.setShaderInput("fScaleOverScaleDepth", scale / 0.25)

                # Currently hard coded in shader
                component.atmosphere.setShaderInput("fSamples", 10.0)
                component.atmosphere.setShaderInput("nSamples", 10)
                # These do sunsets and sky colors
                # Brightness of sun
                ESun = 15
                # Reyleight Scattering (Main sky colors)
                component.atmosphere.setShaderInput("fKrESun", 0.000055 * ESun)
                # Mie Scattering -- Haze and sun halos
                component.atmosphere.setShaderInput("fKmESun", 0.000015 * ESun)
                # Color of sun
                component.atmosphere.setShaderInput("v3InvWavelength", 1.0 / math.pow(0.650, 4),
                                                  1.0 / math.pow(0.570, 4),
                                                  1.0 / math.pow(0.465, 4))
                #component.atmosphere.setShader(Shader.load("atmo.cg"))
            bodyEntity.addComponent(component)

        self.bodies.append(body)
        #bods.append(body)
        log.info(name + " set Up")

        if 'bodies' in DB:
            for bodyName, bodyDB in DB['bodies'].items():
                self.generateNode(bodyName, bodyDB, body)
Esempio n. 9
0
    def generateNode(self, name, DB, parentNode):
        log.debug("Setting up " + name)
        bodyEntity = sandbox.createEntity()
        component = CelestialComponent()
        if DB['type'] == 'solid':
            body = Body(name)
        elif DB['type'] == 'moon':
            body = Body(name)
            body.kind = "moon"
        elif DB['type'] == 'star':
            body = Star(name)
            body.absoluteM = DB['absolute magnitude']
            body.spectral = DB['spectral']
        elif DB['type'] == 'barycenter':
            body = BaryCenter(name)

        component.kind = TYPES[DB['type']]

        if DB['type'] != "barycenter":
            component.mass = DB['mass']
            body.radius = DB['radius']
            body.rotation = DB['rotation']

        if 'orbit' in DB:
            component.orbit = DB['orbit']
            body.period = DB['period']
            #body.setPos(self.get2DBodyPosition(component, universals.day))
            component.truePos = self.get2DBodyPosition(component, universals.day)
            if name == "Earth":
                #universals.spawn = component.truePos + LPoint3d(0, 6671, 0)
                universals.spawn = component.truePos + LPoint3d(6671, 0, 0)

        if parentNode == universals.solarSystemRoot:
            universals.defaultSOIid = bodyEntity.id
            component.soi = 0
        elif DB['type'] != 'star' or DB['type'] != 'barycenter':
            component.soi = self.getSOI(component.mass, self.bodies[0].mass, component.orbit['a'])

        body.type = DB['type']
        body.reparentTo(parentNode)
        component.nodePath = body
        self.bodies.append(component)
        bodyEntity.addComponent(component)

        if universals.runClient and DB['type'] == 'star':
            component = graphicsComponents.RenderComponent()
            #component.mesh = NodePath(name)
            #self.sphere.copyTo(component.mesh)
            #component.mesh = shapeGenerator.Sphere(body.radius, 128, name)
            component.mesh = shapeGenerator.Sphere(body.radius, 64, name)
            #component.mesh.setScale(body.radius)
            component.mesh.reparentTo(sandbox.base.render)
            sandbox.send('makePickable', [component.mesh])
            #texture = sandbox.base.loader.loadTexture('planets/' + DB['texture'])
            #texture.setMinfilter(Texture.FTLinearMipmapLinear)
            #ts1 = TextureStage('textures1')
            #ts1.setMode(TextureStage.MGlow)
            #component.mesh.setTexture(ts1, texture)
            #component.mesh.setTexture(texture, 1)

            component.light = component.mesh.attachNewNode(PointLight("sunPointLight"))
            component.light.node().setColor(Vec4(1, 1, 1, 1))
            sandbox.base.render.setLight(component.light)
            bodyEntity.addComponent(component)

            #Shader test
            componentStar = graphicsComponents.StarRender()
            componentStar.noise_texture = Texture('noise')
            componentStar.noise_texture.setup2dTexture()
            img = PNMImage(1024, 1024)
            for y in range(1024):
                for x in range(1024):
                    img.setXel(x, y, componentStar.noise.noise(x, y))
                    #print componentStar.noise.noise(x, y)
            componentStar.noise_texture.load(img)
            #componentStar.noise_texture.write('test.png')
            #component.mesh.setTexture(componentStar.noise_texture, 1)

            texture = sandbox.base.loader.loadTexture('planets/' + DB['texture'])
            ts1 = TextureStage('textures1')
            ts1.setMode(TextureStage.MGlow)
            component.mesh.setTexture(ts1, componentStar.noise_texture)
            #component.mesh.setTexture(ts1, texture)

            component.mesh.setShaderInput('time', universals.get_day_in_seconds())
            shaders = Shader.load(Shader.SLGLSL, 'vortexVertex.glsl', 'starFrag.glsl')
            component.mesh.setShader(shaders)
            sandbox.send('makePickable', [component.mesh])


        if universals.runClient and (DB['type'] == 'solid' or DB['type'] == 'moon'):
            component = graphicsComponents.RenderComponent()
            #component.mesh = shapeGenerator.Sphere(body.radius, 128, name)
            #component.mesh = shapeGenerator.Sphere(body.radius, 64, name)
            component.mesh = surface_mesh.make_planet(name=name, scale=body.radius)
            #sandbox.send('makePickable', [component.mesh])
            sandbox.send('makePickable', [component.mesh.node_path])
            #component.mesh.setScale(body.radius)
            component.mesh.reparent_to(sandbox.base.render)
            # Doing world text
            text = TextNode('node name')
            text.setText(name)
            #textNodePath = component.mesh.attachNewNode(text)
            textNodePath = component.mesh.node_path.attachNewNode(text)
            textNodePath.setScale(0.07)

            component.mesh.set_textures(DB['texture'],
                night_path=DB['night'],
                gloss_path=DB['spec'])


            component.mesh.set_ambient(1, 1, 1, 1)
            component.mesh.set_diffuse(1, 1, 1, 1)
            component.mesh.set_specular(1, 1, 1, 1)
            component.mesh.set_shininess(100)

            '''if '#' in DB['texture']:
                component.mesh.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition)
                component.mesh.setTexProjector(TextureStage.getDefault(), sandbox.base.render, component.mesh)
                component.mesh.setTexScale(TextureStage.getDefault(), 1,  1, -1)
                component.mesh.setTexHpr(TextureStage.getDefault(), 90, -18, 90)
                #self.mesh.setHpr(0, 90, 0)
                texture = loader.loadCubeMap('planets/' + DB['texture'])
            else:
                texture = sandbox.base.loader.loadTexture('planets/' + DB['texture'])
            #texture.setMinfilter(Texture.FTLinearMipmapLinear)
            component.mesh.setTexture(texture, 1)'''
            '''if "atmosphere" in DB:
                component.atmosphere = shapeGenerator.Sphere(-1, 128)
                component.atmosphere.reparentTo(render)
                component.atmosphere.setScale(body.radius * 1.025)
                outerRadius = component.atmosphere.getScale().getX()
                scale = 1 / (outerRadius - component.body.getScale().getX())
                component.atmosphere.setShaderInput("fOuterRadius", outerRadius)
                component.atmosphere.setShaderInput("fInnerRadius", component.mesh.getScale().getX())
                component.atmosphere.setShaderInput("fOuterRadius2", outerRadius * outerRadius)
                component.atmosphere.setShaderInput("fInnerRadius2",
                    component.mesh.getScale().getX()
                    * component.mesh.getScale().getX())

                component.atmosphere.setShaderInput("fKr4PI",
                    0.000055 * 4 * 3.14159)
                component.atmosphere.setShaderInput("fKm4PI",
                    0.000015 * 4 * 3.14159)

                component.atmosphere.setShaderInput("fScale", scale)
                component.atmosphere.setShaderInput("fScaleDepth", 0.25)
                component.atmosphere.setShaderInput("fScaleOverScaleDepth", scale / 0.25)

                # Currently hard coded in shader
                component.atmosphere.setShaderInput("fSamples", 10.0)
                component.atmosphere.setShaderInput("nSamples", 10)
                # These do sunsets and sky colors
                # Brightness of sun
                ESun = 15
                # Reyleight Scattering (Main sky colors)
                component.atmosphere.setShaderInput("fKrESun", 0.000055 * ESun)
                # Mie Scattering -- Haze and sun halos
                component.atmosphere.setShaderInput("fKmESun", 0.000015 * ESun)
                # Color of sun
                component.atmosphere.setShaderInput("v3InvWavelength", 1.0 / math.pow(0.650, 4),
                                                  1.0 / math.pow(0.570, 4),
                                                  1.0 / math.pow(0.465, 4))
                #component.atmosphere.setShader(Shader.load("atmo.cg"))'''
            bodyEntity.addComponent(component)
        log.info(name + " set Up")
        if 'bodies' in DB:
            for bodyName, bodyDB in DB['bodies'].items():
                self.generateNode(bodyName, bodyDB, body)