Пример #1
0
def makeRenderState(material=None,
                    diffuseTexture=None,
                    normalTexture=None,
                    glowTexture=None):
    n = NodePath("n")

    if not material:
        material = makeMaterial((0, 0, 0, 1), (1, 1, 1, 1),
                                (0.01, 0.01, 0.01, 1), 1, (1, 1, 1, 1))

    n.setMaterial(material)

    if diffuseTexture:
        tsDiffuse = TextureStage('diffuse')
        tsDiffuse.setMode(TextureStage.MModulate)
        n.setTexture(tsDiffuse, diffuseTexture)

    if glowTexture:
        tsGlow = TextureStage('glow')
        tsGlow.setMode(TextureStage.MGlow)
        n.setTexture(tsGlow, glowTexture)

    if normalTexture:
        tsNormal = TextureStage('normal')
        tsNormal.setMode(TextureStage.MNormal)
        n.setTexture(tsNormal, normalTexture)

    # weird bugs :|
    #n.setTransparency(True)
    #n.setColorOff()
    return n.getState()
Пример #2
0
    def create_instance(self):
        self.create_buffer()
        # Water surface
        maker = CardMaker('water')
        maker.setFrame(self.x1, self.x2, self.y1, self.y2)

        self.waterNP = self.parent.instance.attachNewNode(maker.generate())
        self.waterNP.setHpr(0, -90, 0)
        self.waterNP.setPos(0, 0, self.z)
        self.waterNP.setTransparency(TransparencyAttrib.MAlpha)
        self.waterNP.setShader(Shader.load(Shader.SL_GLSL,
                                           vertex=defaultDirContext.find_shader('water-vertex.glsl'),
                                           fragment=defaultDirContext.find_shader('water-fragment.glsl')))
        self.waterNP.setShaderInput('wateranim', Vec4(0.03, -0.015, self.scale, 0)) # vx, vy, scale, skip
        # offset, strength, refraction factor (0=perfect mirror, 1=total refraction), refractivity
        self.waterNP.setShaderInput('waterdistort', Vec4(0.4, 4.0, 0.25, 0.45))
        self.waterNP.setShaderInput('time', 0)

        # Reflection plane
        self.waterPlane = Plane(Vec3(0, 0, self.z + 1), Point3(0, 0, self.z))
        planeNode = PlaneNode('waterPlane')
        planeNode.setPlane(self.waterPlane)

        # reflection texture, created in realtime by the 'water camera'
        tex0 = self.buffer.getTexture()
        tex0.setWrapU(Texture.WMClamp)
        tex0.setWrapV(Texture.WMClamp)
        ts0 = TextureStage('reflection')
        self.waterNP.setTexture(ts0, tex0)

        # distortion texture
        tex1 = loader.loadTexture('textures/water.png')
        ts1 = TextureStage('distortion')
        self.waterNP.setTexture(ts1, tex1)
        self.task = taskMgr.add(self.update, "waterTask")
Пример #3
0
    def apply_splatted_textures(self, tile: NodePath, first_tex, second_tex,
                                stencil_tex):
        # first = self.load("textures/sand_tex_1.png")
        # second = self.load("textures/grass_tex_1.png")
        # third = self.load("textures/water_tex_1.png")
        # stencil = self.load("textures/stencil_tex_1.png")
        # stencil_2 = self.load("textures/stencil_tex_2.png")
        # # normal = self.load("textures/sea-normal.jpg")
        # normal = self.loader.load_texture("textures/layingrock-n.jpg")

        # Apply the first texture.
        ts1 = TextureStage("stage-first")
        ts1.setSort(0)
        ts1.setMode(TextureStage.MReplace)
        ts1.setSavedResult(True)
        tile.setTexture(ts1, first_tex)
        # Apply the second texture.
        ts2 = TextureStage("stage-second")
        ts2.setSort(1)
        ts2.setMode(TextureStage.MReplace)
        tile.setTexture(ts2, second_tex)
        ts3 = TextureStage("stage-stencil")
        ts3.setSort(2)
        ts3.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSPrevious,
                          TextureStage.COSrcColor,
                          TextureStage.CSLastSavedResult,
                          TextureStage.COSrcColor, TextureStage.CSTexture,
                          TextureStage.COSrcColor)
        ts3.setSavedResult(True)
        tile.setTexture(ts3, stencil_tex)
Пример #4
0
def splatting(node, first, second, stencil, scale=None, offset=None):
    """Apply a texture splatting to the provided NodePath.
    """
    # Apply the first texture.
    ts1 = TextureStage("stage-first")
    ts1.setSort(0)
    ts1.setMode(TextureStage.MReplace)
    ts1.setSavedResult(True)
    node.setTexture(ts1, first)
    # Apply the second texture.
    ts2 = TextureStage("stage-second")
    ts2.setSort(1)
    ts2.setMode(TextureStage.MReplace)
    node.setTexture(ts2, second)
    # Apply the stencil.
    ts3 = TextureStage("stage-stencil")
    ts3.setSort(2)
    ts3.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSPrevious,
                      TextureStage.COSrcColor, TextureStage.CSLastSavedResult,
                      TextureStage.COSrcColor, TextureStage.CSTexture,
                      TextureStage.COSrcColor)
    node.setTexture(ts3, stencil)
    if scale: node.setTexScale(ts3, scale, scale)
    if offset is not None:
        node.setTexOffset(ts1, *offset)
        node.setTexOffset(ts2, *offset)
        node.setTexOffset(ts3, *offset)
Пример #5
0
    def create_texture_stages(self):
        """
        Create the texture stages: these are basically textures that you can apply
        to cards (sometimes mulitple textures at the same time -- is useful with
        masks).
        
        For more on texture stages:
        https://docs.panda3d.org/1.10/python/programming/texturing/multitexture-introduction
        """
        #Binocular cards
        if self.current_stim_params['stim_type'] == 'b':
            #TEXTURE STAGES FOR LEFT CARD
            # Texture itself
            self.left_texture_stage = TextureStage('left_texture_stage')
            # Mask
            self.left_mask = Texture("left_mask_texture")
            self.left_mask.setup2dTexture(self.texture_size, self.texture_size,
                                          Texture.T_unsigned_byte,
                                          Texture.F_luminance)
            self.left_mask_stage = TextureStage('left_mask_array')

            #TEXTURE STAGES FOR RIGHT CARD
            self.right_texture_stage = TextureStage('right_texture_stage')
            #Mask
            self.right_mask = Texture("right_mask_texture")
            self.right_mask.setup2dTexture(self.texture_size,
                                           self.texture_size,
                                           Texture.T_unsigned_byte,
                                           Texture.F_luminance)
            self.right_mask_stage = TextureStage('right_mask_stage')
        # Tex card
        elif self.current_stim_params['stim_type'] == 's':
            self.texture_stage = TextureStage("texture_stage")
        return
Пример #6
0
 def __init__(self, render, loader, location, sizeX, sizeY):
     self.water = loader.loadModel(
         'assets/environment/arctic/nature/water.bam')
     self.water.setPos(location)
     self.water.setSx(sizeX)
     self.water.setSy(sizeY)
     self.newTS = TextureStage('ts')
     self.normal_TS = TextureStage('normal')
     self.normal_TS.setMode(TextureStage.MNormal)
     self.water.setTexture(
         self.newTS,
         loader.loadTexture(
             'assets/environment/arctic/nature/textures/water_colormap.jpg')
     )
     self.water.setTexScale(self.newTS, 80)
     self.water.setTexture(
         self.normal_TS,
         loader.loadTexture(
             'assets/environment/arctic/nature/textures/water_normalmap.jpg'
         ))
     self.water.setTexScale(self.normal_TS, 80)
     self.water.setShaderAuto()
     ambiet = AmbientLight('ambient')
     ambiet.setColor((0.2, 0.2, 0.2, 1))
     alight = self.water.attachNewNode(ambiet)
     self.water.setLight(alight)
     self.water.reparentTo(render)
     self.skybox = loader.loadModel(
         "assets/environment/arctic/nature/skybox.bam")
     self.skybox.setPos(location)
     self.skybox.setScale(2000)
Пример #7
0
    def generateSurfaceTextures(self):
        # Textureize
        self.grassTexture = loader.loadTexture("Textures/grass.png")
        self.grassTS = TextureStage('grass')
        self.grassTS.setSort(1)

        self.rockTexture = loader.loadTexture("Textures/rock.jpg")
        self.rockTS = TextureStage('rock')
        self.rockTS.setSort(2)
        self.rockTS.setCombineRgb(TextureStage.CMAdd,
                                  TextureStage.CSLastSavedResult,
                                  TextureStage.COSrcColor,
                                  TextureStage.CSTexture,
                                  TextureStage.COSrcColor)

        self.sandTexture = loader.loadTexture("Textures/sand.jpg")
        self.sandTS = TextureStage('sand')
        self.sandTS.setSort(3)
        self.sandTS.setPriority(5)

        self.snowTexture = loader.loadTexture("Textures/ice.png")
        self.snowTS = TextureStage('snow')
        self.snowTS.setSort(4)
        self.snowTS.setPriority(0)

        # Grid for city placement and guide and stuff
        self.gridTexture = loader.loadTexture("Textures/grid.png")
        self.gridTexture.setWrapU(Texture.WMRepeat)
        self.gridTexture.setWrapV(Texture.WMRepeat)
        self.gridTS = TextureStage('grid')
        self.gridTS.setSort(5)
        self.gridTS.setPriority(10)
Пример #8
0
    def __init__(self, block_index: int, pre_block_socket: BlockSocket, global_network: RoadNetwork, random_seed):
        super(Block, self).__init__(random_seed)
        # block information
        assert self.ID is not None, "Each Block must has its unique ID When define Block"
        assert self.SOCKET_NUM is not None, "The number of Socket should be specified when define a new block"
        if block_index == 0:
            from pgdrive.scene_creator.blocks import FirstBlock
            assert isinstance(self, FirstBlock), "only first block can use block index 0"
        elif block_index < 0:
            logging.debug("It is recommended that block index should > 1")
        self._block_name = str(block_index) + self.ID
        self.block_index = block_index
        self.number_of_sample_trial = 0

        # each block contains its own road network and a global network
        self._global_network = global_network
        self.block_network = RoadNetwork()

        # used to spawn npc
        self._reborn_roads = []

        # own sockets, one block derives from a socket, but will have more sockets to connect other blocks
        self._sockets = []

        # used to connect previous blocks, save its info here
        self._pre_block_socket = pre_block_socket
        self.pre_block_socket_index = pre_block_socket.index

        # a bounding box used to improve efficiency x_min, x_max, y_min, y_max
        self.bounding_box = None

        # used to create this block, but for first block it is nonsense
        if block_index != 0:
            self.positive_lanes = self._pre_block_socket.positive_road.get_lanes(self._global_network)
            self.negative_lanes = self._pre_block_socket.negative_road.get_lanes(self._global_network)
            self.positive_lane_num = len(self.positive_lanes)
            self.negative_lane_num = len(self.negative_lanes)
            self.positive_basic_lane = self.positive_lanes[-1]  # most right or outside lane is the basic lane
            self.negative_basic_lane = self.negative_lanes[-1]  # most right or outside lane is the basic lane
            self.lane_width = self.positive_basic_lane.width_at(0)

        if self.render:
            # render pre-load
            self.road_texture = self.loader.loadTexture(AssetLoader.file_path("textures", "sci", "color.jpg"))
            self.road_texture.setMinfilter(SamplerState.FT_linear_mipmap_linear)
            self.road_texture.setAnisotropicDegree(8)
            self.road_normal = self.loader.loadTexture(AssetLoader.file_path("textures", "sci", "normal.jpg"))
            self.ts_color = TextureStage("color")
            self.ts_normal = TextureStage("normal")
            self.side_texture = self.loader.loadTexture(AssetLoader.file_path("textures", "side_walk", "color.png"))
            self.side_texture.setMinfilter(SamplerState.FT_linear_mipmap_linear)
            self.side_texture.setAnisotropicDegree(8)
            self.side_normal = self.loader.loadTexture(AssetLoader.file_path("textures", "side_walk", "normal.png"))
            self.side_walk = self.loader.loadModel(AssetLoader.file_path("models", "box.bam"))
Пример #9
0
    def __init__(self):

        self.enabled = True

        sMgr = CIGlobals.getSettingsMgr()
        reso = sMgr.ReflectionQuality[sMgr.getSetting("refl").getValue()]
        if reso == 0:
            self.enabled = False
            return

        self.waterPlaneNP = None

        self.waterNodes = []

        # Buffer and reflection camera
        buffer = base.win.makeTextureBuffer('waterBuffer', reso, reso)
        buffer.setClearColor(Vec4(0, 0, 0, 1))

        cfa = CullFaceAttrib.makeReverse()
        rs = RenderState.make(cfa)

        self.watercamNP = base.makeCamera(buffer)
        self.watercamNP.reparentTo(render)

        self.makePlane(0.0)

        cam = self.watercamNP.node()
        cam.getLens().setFov(base.camLens.getFov())
        cam.getLens().setNear(1)
        cam.getLens().setFar(5000)
        cam.setInitialState(rs)
        cam.setTagStateKey('Clipped')

        self.ts0 = TextureStage("tex_0")
        self.tex0 = buffer.getTexture()
        self.tex0.setWrapU(Texture.WMClamp)
        self.tex0.setWrapV(Texture.WMClamp)

        self.ts1 = TextureStage("tex_1")
        self.waterTex = loader.loadTexture('phase_3/maps/water_distort.png')
        self.waterQuad = None

        self.waterStage = TextureStage("waterStage")

        image0 = OnscreenImage(image=self.tex0, scale=0.3, pos=(-0.5, 0, 0.7))
        image1 = OnscreenImage(image=waterTex, scale=0.3, pos=(0.5, 0, 0.7))

        taskMgr.add(self.update, "waterTask")
Пример #10
0
    def fillTextureStages(self, nodePath):
        """ Prepares all materials of a given nodepath to have at least the 4 
        default textures in the correct order: [diffuse, normal, specular, roughness] """
        
        emptyDiffuseTex = loader.loadTexture("Data/Textures/EmptyDiffuseTexture.png")
        emptyNormalTex = loader.loadTexture("Data/Textures/EmptyNormalTexture.png")
        emptySpecularTex = loader.loadTexture("Data/Textures/EmptySpecularTexture.png")
        emptyRoughnessTex = loader.loadTexture("Data/Textures/EmptyRoughnessTexture.png")

        textureOrder = [emptyDiffuseTex, emptyNormalTex, emptySpecularTex, emptyRoughnessTex]
        textureSorts = [0, 10, 20, 30]

        # Prepare the textures
        for tex in textureOrder:
            tex.setMinfilter(SamplerState.FTLinear)
            tex.setMagfilter(SamplerState.FTLinear)
            tex.setFormat(Texture.FRgba)

        # Iterate over all geom nodes
        for np in nodePath.findAllMatches("**/+GeomNode"):

            # Check how many texture stages the nodepath already has
            stages = np.findAllTextureStages()
            numStages = len(stages)

            # Fill the texture stages up
            for i in xrange(numStages, 4):
                stage = TextureStage("DefaultTexStage" + str(i))
                stage.setSort(textureSorts[i])
                stage.setMode(TextureStage.CMModulate)
                stage.setColor(Vec4(0, 0, 0, 1))
                np.setTexture(stage, textureOrder[i])
Пример #11
0
 def apply_panda(self, shape, texture, texture_lod):
     texture_stage = TextureStage(shape.str_id() + self.__class__.__name__)
     self.init_texture_stage(texture_stage, texture)
     if self.tex_matrix:
         shape.set_texture_to_lod(self, texture_stage, texture_lod,
                                  self.source.is_patched())
         if shape.swap_uv:
             shape.instance.setTexRotate(texture_stage, -90)
         scale = shape.instance.getTexScale(texture_stage)
         offset = shape.instance.getTexOffset(texture_stage)
         if shape.swap_uv:
             if shape.inv_v:
                 scale.x = -scale.x
             else:
                 offset.y += 1.0
             if not shape.inv_u:
                 scale.y = -scale.y
                 offset.x += 1.0
         else:
             if shape.inv_v:
                 scale.y = -scale.y
                 offset.y += 1.0
             if shape.inv_u:
                 scale.x = -scale.x
                 offset.x += 1.0
         shape.instance.setTexScale(texture_stage, scale)
         shape.instance.setTexOffset(texture_stage, offset)
     shape.instance.setTexture(texture_stage, texture, 1)
Пример #12
0
    def __init__(self,
                 texture_array,
                 scale=0.2,
                 window_size=512,
                 texture_size=512):
        super().__init__()
        self.scale = scale
        self.current_scale = 1
        self.texture_array = texture_array
        self.texture_dtype = type(self.texture_array.flat[0])
        self.ndims = self.texture_array.ndim
        self.center_shift = TransformState.make_pos2d((-0.5, -0.5))
        self.shift_back = TransformState.make_pos2d((0.5, 0.5))

        #Create texture stage
        self.texture = Texture("Stimulus")
        self.texture.setup2dTexture(texture_size, texture_size,
                                    Texture.T_unsigned_byte,
                                    Texture.F_luminance)
        self.texture.setWrapU(Texture.WM_clamp)
        self.texture.setWrapV(Texture.WM_clamp)
        self.texture.setRamImageAs(self.texture_array, "L")
        self.textureStage = TextureStage("Stimulus")

        #Create scenegraph
        cm = CardMaker('card1')
        cm.setFrameFullscreenQuad()
        self.card1 = self.aspect2d.attachNewNode(cm.generate())
        self.card1.setTexture(self.textureStage, self.texture)  #ts, tx

        if self.scale != 0:
            self.taskMgr.add(self.scaleTextureTask, "scaleTextureTask")
Пример #13
0
    def __init__(self, name, inclination, baseDimension):
        #public props
        self.baseDimension = baseDimension

        tex = loader.loadTexture(resourceManager.getResource(name) + '.png')

        xscaled = tex.getOrigFileXSize() / self.baseDimension
        yscaled = tex.getOrigFileYSize() / self.baseDimension

        cm = CardMaker("unscrollobject")
        cm.setFrame(0, xscaled, 0, yscaled)

        ts = TextureStage('ts')
        ts.setMode(TextureStage.MDecal)

        uvscroll = UvScrollNode("uvscrollnode", 1, 0.0, 0.0, 0.0)

        uvscroll.addChild(cm.generate())

        self.node = NodePath(uvscroll)
        self.node.setTwoSided(True)

        self.node.setX((-xscaled / 2) + 0.5)
        self.node.setP(-(360 - int(inclination)))
        self.node.setTexture(tex)
        self.node.setTransparency(TransparencyAttrib.MAlpha)
        self.node.reparentTo(render)
Пример #14
0
    def _gen_flowers(self, surf_mod, angle, side):
        """Generate texture flowers.

        Args:
            surf_mod (panda3d.core.NodePath): Surface model.
            angle (int): Surface model angle.
            side (str): Surface model side.
        """
        for i in range(random.randint(0, 3)):
            ts = TextureStage("ts_flower{}".format(str(i)))
            ts.setMode(TextureStage.MDecal)

            tex = loader.loadTexture(  # noqa: F821
                "just_tex/flower{}.png".format(str(random.randint(1, 5))))
            tex.setWrapU(Texture.WMClamp)
            tex.setWrapV(Texture.WMClamp)

            surf_mod.setTexture(ts, tex)
            surf_mod.setTexPos(
                ts,
                random.randint(*FLOWER_RANGES[(angle, side)]["u"]),
                random.randint(*FLOWER_RANGES[(angle, side)]["v"]),
                0,
            )
            surf_mod.setTexScale(ts, 20, 20)
Пример #15
0
 def enable(self):
     camNode = Camera('shadowCam')
     camNode.setCameraMask(CIGlobals.ShadowCameraBitmask)
     self.shadowLens = OrthographicLens()
     self.shadowLens.setFilmSize(60 * 4, 60 * 4)
     camNode.setLens(self.shadowLens)
     self.shadowCamArm = camera.attachNewNode('shadowCamArm')
     self.shadowCam = self.shadowCamArm.attachNewNode(camNode)
     self.shadowCamArm.setPos(0, 40, 0)
     self.shadowCam.setPos(0, -40, 0)
     self.shadowTex = Texture('shadow')
     self.shadowTex.setBorderColor(self.clearColor)
     self.shadowTex.setWrapU(Texture.WMBorderColor)
     self.shadowTex.setWrapV(Texture.WMBorderColor)
     self.casterState = NodePath('temp')
     self.casterState.setColorScaleOff(10)
     self.casterState.setColor(self.shadowColor, self.shadowColor,
                               self.shadowColor, 1, 10)
     self.casterState.setTextureOff(10)
     self.casterState.setLightOff(10)
     self.casterState.setFogOff(10)
     camNode.setInitialState(self.casterState.getState())
     render.hide(CIGlobals.ShadowCameraBitmask)
     self.shadowStage = TextureStage('shadow')
     self.shadowStage.setSort(1000)
     self.turnOnShadows()
Пример #16
0
 def makeTextureMap(self):
     '''Citymania function that generates and sets the 4 channel texture map'''
     self.colorTextures = []
     for terrain in self.terrains:
         terrain.getRoot().clearTexture()
         heightmap = terrain.heightfield()
         colormap = PNMImage(heightmap.getXSize() - 1,
                             heightmap.getYSize() - 1)
         colormap.addAlpha()
         slopemap = terrain.makeSlopeImage()
         for x in range(0, colormap.getXSize()):
             for y in range(0, colormap.getYSize()):
                 # Else if statements used to make sure one channel is used per pixel
                 # Also for some optimization
                 # Snow. We do things funky here as alpha will be 1 already.
                 if heightmap.getGrayVal(x, y) < 200:
                     colormap.setAlpha(x, y, 0)
                 else:
                     colormap.setAlpha(x, y, 1)
                 # Beach. Estimations from http://www.simtropolis.com/omnibus/index.cfm/Main.SimCity_4.Custom_Content.Custom_Terrains_and_Using_USGS_Data
                 if heightmap.getGrayVal(x, y) < 62:
                     colormap.setBlue(x, y, 1)
                 # Rock
                 elif slopemap.getGrayVal(x, y) > 170:
                     colormap.setRed(x, y, 1)
                 else:
                     colormap.setGreen(x, y, 1)
         colorTexture = Texture()
         colorTexture.load(colormap)
         colorTS = TextureStage('color')
         colorTS.setSort(0)
         colorTS.setPriority(1)
         self.colorTextures.append((colorTexture, colorTS))
Пример #17
0
    def setupTexture(self):
        """
        This is the overlay/decal/etc. which contains the typed characters.

        The texture size and the font size are currently tied together.
        :return:
        """
        self.texImage = PNMImage(1024, 1024)
        self.texImage.addAlpha()
        self.texImage.fill(1.0)
        self.texImage.alphaFill(1.0)

        self.tex = Texture('typing')
        self.tex.setMagfilter(Texture.FTLinear)
        self.tex.setMinfilter(Texture.FTLinear)

        self.typingStage = TextureStage('typing')
        self.typingStage.setMode(TextureStage.MModulate)

        self.tex.load(self.texImage)

        # ensure we can quickly update subimages
        self.tex.setKeepRamImage(True)

        # temp for drawing chars
        self.chImage = PNMImage(*self.fontCharSize)
    def __init__(self, texture_cube, window_size=512, texture_size=512):
        super().__init__()
        self.cube_ind = 0
        self.num_slices = texture_cube.shape[0]
        self.cube = texture_cube

        # SET Frame rate
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(40)  #can lock this at

        #Create texture stage
        self.texture = Texture("Stimulus")
        #        self.texture.setMagfilter(SamplerState.FT_nearest)
        #        self.texture.setMinfilter(SamplerState.FT_nearest)
        self.texture.setup2dTexture(texture_size, texture_size,
                                    Texture.T_unsigned_byte,
                                    Texture.F_luminance)
        self.texture.setRamImageAs(self.cube[0, :, :], "L")
        self.textureStage = TextureStage("Stimulus")

        #Create scenegraph
        cm = CardMaker('card1')
        cm.setFrameFullscreenQuad()
        self.card1 = self.aspect2d.attachNewNode(cm.generate())
        self.card1.setTexture(self.textureStage, self.texture)  #ts, tx
        ShowBaseGlobal.base.setFrameRateMeter(True)

        self.taskMgr.add(self.setTextureTask, "setTextureTask")
Пример #19
0
def makeSprite(name, texture, scale, add = False):
    from panda3d.core import (GeomVertexFormat, GeomVertexData, GeomEnums,
                              InternalName, GeomVertexWriter, GeomPoints,
                              Geom, GeomNode, NodePath, TextureStage,
                              TexGenAttrib, BoundingSphere)
    format = GeomVertexFormat.getV3()
    data = GeomVertexData(name + "_data", format, GeomEnums.UHStatic)
    writer = GeomVertexWriter(data, InternalName.getVertex())
    writer.addData3f((0, 0, 0))
    primitive = GeomPoints(GeomEnums.UHStatic)
    primitive.addVertex(0)
    primitive.closePrimitive()
    geom = Geom(data)
    geom.addPrimitive(primitive)
    geomNode = GeomNode(name)
    geomNode.addGeom(geom)
    np = NodePath(geomNode)
    np.setLightOff(1)
    np.setMaterialOff(1)
    np.setRenderModePerspective(True)
    ts = TextureStage('sprite')
    if add:
        ts.setMode(TextureStage.MAdd)
    np.setTexture(ts, texture)
    np.setTexGen(ts, TexGenAttrib.MPointSprite)

    np.setDepthWrite(False)
    np.setDepthOffset(1)
    np.setTransparency(True)
    np.node().setBounds(BoundingSphere((0, 0, 0), 1))
    np.node().setFinal(True)
    np.flattenStrong()
    np.setScale(scale)

    return np
Пример #20
0
 def apply_panda(self, shape, texture, texture_lod):
     texture_stage = TextureStage(shape.str_id() + self.__class__.__name__)
     self.init_texture_stage(texture_stage, texture)
     if self.tex_matrix:
         shape.set_texture_to_lod(self, texture_stage, texture_lod,
                                  self.source.is_patched())
     shape.instance.setTexture(texture_stage, texture, 1)
Пример #21
0
 def loadFlatQuad(self, fullFilename):
     cm = CardMaker('cm-%s' % fullFilename)
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0,
                 htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     quad = NodePath(card)
     jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT)
     smallerJpgFile = PNMImage()
     readFile = smallerJpgFile.read(Filename(fullFilename))
     if readFile:
         jpgFile.copySubImage(smallerJpgFile, 0, 0)
         guiTex = Texture('guiTex')
         guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1,
                             Texture.TUnsignedByte, Texture.FRgba)
         guiTex.setMinfilter(Texture.FTLinear)
         guiTex.load(jpgFile)
         guiTex.setWrapU(Texture.WMClamp)
         guiTex.setWrapV(Texture.WMClamp)
         ts = TextureStage('webTS')
         quad.setTexture(ts, guiTex)
         quad.setTransparency(0)
         quad.setTwoSided(True)
         quad.setColor(1.0, 1.0, 1.0, 1.0)
         result = quad
     else:
         result = None
     Texture.setTexturesPower2(1)
     return result
Пример #22
0
 def setupTexture(self):
     cm = CardMaker('quadMaker')
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     self.quad = NodePath(card)
     self.quad.reparentTo(self.parent_)
     self.guiTex = Texture('guiTex')
     self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba)
     self.guiTex.setMinfilter(Texture.FTLinear)
     self.guiTex.setKeepRamImage(True)
     self.guiTex.makeRamImage()
     self.guiTex.setWrapU(Texture.WMRepeat)
     self.guiTex.setWrapV(Texture.WMRepeat)
     ts = TextureStage('webTS')
     self.quad.setTexture(ts, self.guiTex)
     self.quad.setTexScale(ts, 1.0, -1.0)
     self.quad.setTransparency(0)
     self.quad.setTwoSided(True)
     self.quad.setColor(1.0, 1.0, 1.0, 1.0)
     self.calcMouseLimits()
 def applySettings(self, jsonfile):
     if not jsonfile:
         raise IOError('no file specified!')
     info = open(jsonfile, 'r')
     jsonInfo = json.load(info)
     settings = jsonInfo['settings']
     width, height = settings['resolution']
     fs = settings['fullscreen']
     music = settings['music']
     sfx = settings['sfx']
     tex_detail = settings['texture-detail']
     model_detail = settings['model-detail']
     aa = settings['aa']
     af = settings.get('af', None)
     if af == None:
         self.writeSettingToFile('af', 'off', 'settings.json')
     base.enableMusic(music)
     base.enableSoundEffects(sfx)
     if aa == 'on':
         render.set_antialias(AntialiasAttrib.MMultisample)
         aspect2d.set_antialias(AntialiasAttrib.MMultisample)
     else:
         render.clear_antialias()
     ts = TextureStage('ts')
     if tex_detail == 'high':
         pass
     else:
         if tex_detail == 'low':
             loadPrcFileData('', 'compressed-textures 1')
     wp = WindowProperties()
     wp.setSize(width, height)
     wp.setFullscreen(fs)
     base.win.requestProperties(wp)
     info.close()
     return
Пример #24
0
    def generateSurfaceTextures(self):
        # Textureize
        self.grassTexture = loader.loadTexture("Entities/Maps/grassy2.png")
        self.grassTexture.setWrapU(Texture.WMRepeat)
        self.grassTexture.setWrapV(Texture.WMRepeat)
        self.grassTexture.setMinfilter(SamplerState.FT_linear_mipmap_linear)
        self.grassTexture.setAnisotropicDegree(8)
        self.grassTS = TextureStage('grass')
        self.grassTS.setSort(
            1)  # sorting order is relevent for assigning textures to the four

        self.rockTexture = loader.loadTexture("Entities/Maps/simple.jpg")
        self.rockTexture.setWrapU(Texture.WMRepeat)
        self.rockTexture.setWrapV(Texture.WMRepeat)
        self.rockTexture.setMinfilter(SamplerState.FT_linear_mipmap_linear)
        #self.grassTexture.setAnisotropicDegree(8)
        self.rockTS = TextureStage('rock')
        self.rockTS.setSort(2)
        # self.rockTS.setCombineRgb(TextureStage.CMAdd, TextureStage.CSLastSavedResult, TextureStage.COSrcColor, TextureStage.CSTexture, TextureStage.COSrcColor)

        self.sandTexture = loader.loadTexture("Entities/Maps/stars.png")
        self.sandTexture.setWrapU(Texture.WMRepeat)
        self.sandTexture.setWrapV(Texture.WMRepeat)
        self.sandTexture.setMinfilter(SamplerState.FT_linear_mipmap_linear)
        #self.sandTexture.setAnisotropicDegree(8)
        self.sandTS = TextureStage('sand')
        self.sandTS.setSort(3)
        self.sandTS.setPriority(5)  # TODO: figure out what this is for...

        self.snowTexture = loader.loadTexture("Entities/Maps/grass.png")
        self.snowTexture.setWrapU(Texture.WMRepeat)
        self.snowTexture.setWrapV(Texture.WMRepeat)
        self.snowTexture.setMinfilter(SamplerState.FT_linear_mipmap_linear)
        #self.snowTexture.setAnisotropicDegree(8)
        self.snowTS = TextureStage('snow')
        self.snowTS.setSort(4)
        self.snowTS.setPriority(0)

        # a background (or rather freground?) texture that will be present independently from the blend map (consider removal)
        self.overlayTexture = loader.loadTexture("Entities/Maps/heightmap.png")
        self.overlayTexture.setWrapU(Texture.WMRepeat)
        self.overlayTexture.setWrapV(Texture.WMRepeat)
        self.overlayTexture.setMinfilter(SamplerState.FT_linear_mipmap_linear)
        #self.overlayTexture.setAnisotropicDegree(8)
        self.overlayTS = TextureStage('overlay')
        self.overlayTS.setSort(5)
        self.overlayTS.setPriority(10)
Пример #25
0
    def __init__(self,
                 block_index: int,
                 global_network: RoadNetwork,
                 random_seed,
                 ignore_intersection_checking=False):
        super(BaseBlock, self).__init__(str(block_index) + self.ID,
                                        random_seed,
                                        escape_random_seed_assertion=True)
        # block information
        assert self.ID is not None, "Each Block must has its unique ID When define Block"
        assert len(self.ID) == 1, "Block ID must be a character "

        self.block_index = block_index
        self.ignore_intersection_checking = ignore_intersection_checking

        # each block contains its own road network and a global network
        self._global_network = global_network
        self.block_network = RoadNetwork()

        # a bounding box used to improve efficiency x_min, x_max, y_min, y_max
        self.bounding_box = None

        # used to spawn npc
        self._respawn_roads = []
        self._block_objects = None

        if self.render:
            # render pre-load
            self.road_texture = self.loader.loadTexture(
                AssetLoader.file_path("textures", "sci", "color.jpg"))
            self.road_texture.setMinfilter(
                SamplerState.FT_linear_mipmap_linear)
            self.road_texture.setAnisotropicDegree(8)
            self.road_normal = self.loader.loadTexture(
                AssetLoader.file_path("textures", "sci", "normal.jpg"))
            self.ts_color = TextureStage("color")
            self.ts_normal = TextureStage("normal")
            self.side_texture = self.loader.loadTexture(
                AssetLoader.file_path("textures", "sidewalk", "color.png"))
            self.side_texture.setMinfilter(
                SamplerState.FT_linear_mipmap_linear)
            self.side_texture.setAnisotropicDegree(8)
            self.side_normal = self.loader.loadTexture(
                AssetLoader.file_path("textures", "sidewalk", "normal.png"))
            self.sidewalk = self.loader.loadModel(
                AssetLoader.file_path("models", "box.bam"))
Пример #26
0
 def __init__(self, rgb=(0, 0, 0), tex_name="rgb"):
     self.rgb = rgb
     self.texture_array = rgb_texture(rgb=self.rgb)
     self.texture = Texture(tex_name)
     self.texture.setup2dTexture(512, 512, Texture.T_unsigned_byte,
                                 Texture.F_rgb8)
     self.texture.setRamImageAs(self.texture_array, "RGB")
     self.texture_stage = TextureStage(tex_name)
Пример #27
0
    def __init__(self):
        fn = Filename.fromOsSpecific(self.filepath)
        self.terrain = GeoMipTerrain("mySimpleTerrain")
        self.terrain.setHeightfield("Entities/Maps/heightmap.png")
        self.terrain.getRoot().setSz(40)
        #terrain.setBruteforce(True)
        self.terrain.getRoot().reparentTo(render)

        # Set terrain properties
        self.terrain.setBlockSize(16)
        self.terrain.setNear(500)
        self.terrain.setFar(100)
        self.terrain.setFocalPoint(base.camera)

        # Store the root NodePath for convenience
        root = self.terrain.getRoot()
        root.reparentTo(render)

        # some tinkering
        """
        # tell renderer to repeat texture when reading over the edge.
        texGrass.setWrapU(Texture.WM_repeat)
        texGrass.setWrapV(Texture.WM_repeat)
        # apply mipmapping: tell renderer how to handle multiple texture pixels being rendered t a single screen pixel (makes textures 30% larger in GPU mem.)
        texGrass.setMinfilter(SamplerState.FT_linear_mipmap_linear)
        """
        self.terrain.generate()
        """
        new attempt to include blend mapping:
        """
        # determine terrain size
        self.heightmap = self.terrain.heightfield()
        if self.heightmap.getXSize() > self.heightmap.getYSize():
            self.size = self.heightmap.getXSize() - 1
        else:
            self.size = self.heightmap.getYSize() - 1
        self.xsize = self.heightmap.getXSize() - 1
        self.ysize = self.heightmap.getYSize() - 1

        # Set multi texture
        # Source http://www.panda3d.org/phpbb2/viewtopic.php?t=4536
        self.generateSurfaceTextures()

        # load a blend texture from file:
        self.blendTexture = loader.loadTexture("Entities/Maps/blendMap.png")

        self.blendTS = TextureStage('blend')
        self.blendTS.setSort(0)
        self.blendTS.setPriority(1)
        # apply textures to the terrain and connect custom shader for blend mapping:
        self.setSurfaceTextures()

        # Add a task to keep updating the terrain (for changing terrain, or synamic resolution)
        def updateTask(task):
            self.terrain.update()
            return task.cont

        taskMgr.add(updateTask, "update")
Пример #28
0
 def apply(self, instance):
     if self.texture is None:
         if self.image is None:
             self.image = self.generate()
         self.texture = Texture()
         self.texture.load(self.image)
     instance.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite)
     instance.setTransparency(TransparencyAttrib.MAlpha, 1)
     instance.setTexture(TextureStage('ts'), self.texture, 1)
Пример #29
0
def applyNoGlow(np):
    global NoGlowTS
    global NoGlowTex
    if not NoGlowTS:
        NoGlowTS = TextureStage('noglow')
        NoGlowTS.setMode(TextureStage.MGlow)
    if not NoGlowTex:
        NoGlowTex = loader.loadTexture("phase_3/maps/black.png")
    np.setTexture(NoGlowTS, NoGlowTex)
Пример #30
0
    def __init__(self,
                 texture_array,
                 scale=0.2,
                 window_size=512,
                 texture_size=512):
        super().__init__()
        self.scale = scale
        self.texture_array = texture_array
        self.texture_dtype = type(self.texture_array.flat[0])
        self.ndims = self.texture_array.ndim

        #Set window title
        self.window_properties = WindowProperties()
        self.window_properties.setSize(window_size, window_size)
        self.window_properties.setTitle("FullFieldDrift")
        ShowBaseGlobal.base.win.requestProperties(self.window_properties)

        #Create texture stage
        self.texture = Texture("Stimulus")

        #Select Texture ComponentType (e.g., uint8 or whatever)
        if self.texture_dtype == np.uint8:
            self.texture_component_type = Texture.T_unsigned_byte
        elif self.texture_dtype == np.uint16:
            self.texture_component_type = Texture.T_unsigned_short

        #Select Texture Format (color or b/w etc)
        if self.ndims == 2:
            self.texture_format = Texture.F_luminance  #grayscale
            self.texture.setup2dTexture(texture_size, texture_size,
                                        self.texture_component_type,
                                        self.texture_format)
            self.texture.setRamImageAs(self.texture_array, "L")
        elif self.ndims == 3:
            self.texture_format = Texture.F_rgb8
            self.texture.setup2dTexture(texture_size, texture_size,
                                        self.texture_component_type,
                                        self.texture_format)
            self.texture.setRamImageAs(self.texture_array, "RGB")
        else:
            raise ValueError("Texture needs to be 2d or 3d")

        self.textureStage = TextureStage("Stimulus")

        #Create scenegraph
        cm = CardMaker('card')
        cm.setFrameFullscreenQuad()
        self.card = self.aspect2d.attachNewNode(cm.generate())
        self.card.setTexture(self.textureStage, self.texture)  #ts, tx

        #Set the scale on the card (note this is different from scaling the texture)
        self.card.setScale(np.sqrt(2))

        if self.scale != 0:
            #Add task to taskmgr to translate texture
            self.taskMgr.add(self.scaleTextureTask, "scaleTextureTask")