def __init__(self): self.sphere = loader.loadModel("InvertedSphere.egg") # Load a sphere with a radius of 1 unit and the faces directed inward. self.sphere.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.sphere.setTexProjector(TextureStage.getDefault(), render, self.sphere) self.sphere.setTexPos(TextureStage.getDefault(), 0, 0, 0) self.sphere.setTexScale(TextureStage.getDefault(), .5) # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual. tex = loader.loadCubeMap("BlueGreenNebula_#.png") self.sphere.setTexture(tex) # Load the cube map and apply it to the sphere. self.sphere.setLightOff() # Tell the sphere to ignore the lighting. self.sphere.setScale(1000) # Increase the scale of the sphere so it will be larger than the scene. self.sphere.reparentTo(render) # Reparent the sphere to render so you can see it. result = self.sphere.writeBamFile("SkySphere.bam") # Save out the bam file. print(result)
def __initSceneGraph(self): #load various texture stages of the planet self.forge_tex = TextureStage('forge') self.forge_tex.setMode(TextureStage.MDecal) self.nexus_tex = TextureStage('nexus') self.nexus_tex.setMode(TextureStage.MDecal) self.extractor_phylon_ge_tex = TextureStage('extractor_phylon_ge') self.extractor_phylon_ge_tex.setMode(TextureStage.MDecal) # Parent node for relative position (no scaling) self.point_path = self.parent_star.point_path.attachNewNode("planet_node") self.point_path.setPos(self.position) #Models & textures self.model_path = loader.loadModel("models/planets/planet_sphere") self.model_path.setTexture(SphericalBody.dead_planet_tex, 1) self.model_path.reparentTo(self.point_path) self.model_path.setScale(self.radius) self.model_path.setPythonTag('pyPlanet', self); cnode = CollisionNode("coll_sphere_node") cnode.setTag('planet', str(id(self))) #We use no displacement (0,0,0) and no scaling factor (1) cnode.addSolid(CollisionSphere(0,0,0,1)) cnode.setIntoCollideMask(BitMask32.bit(1)) # Reparenting the collision sphere so that it # matches the planet perfectly. self.cnode_path = self.model_path.attachNewNode(cnode) self.lines = LineNodePath(parent = self.parent_star.point_path, thickness = 4.0, colorVec = Vec4(1.0, 1.0, 1.0, 0.2)) self.quad_path = None
def __init__(self): self.sphere = loader.loadModel("InvertedSphere.egg") # Load a sphere with a radius of 1 unit and the faces directed inward. self.sphere.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.sphere.setTexProjector(TextureStage.getDefault(), render, self.sphere) self.sphere.setTexPos(TextureStage.getDefault(), 0, 0, 0) self.sphere.setTexScale(TextureStage.getDefault(), .5) # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual. tex = loader.loadCubeMap("data/skybox/sky_#.png") self.sphere.setTexture(tex) # Load the cube map and apply it to the sphere. self.sphere.setLightOff() # Tell the sphere to ignore the lighting. self.sphere.setScale(1000) # Increase the scale of the sphere so it will be larger than the scene. self.sphere.reparentTo(render) # Reparent the sphere to render so you can see it. result = self.sphere.writeBamFile("skysphere.bam") # Save out the bam file. print(result)
def setup(cls, loader): cls.noisetex = loader.load3DTexture("texture/noise/fbm_###.tif") cls.noisestage = TextureStage('noise') cls.layer1stage = TextureStage('layer1') cls.layer2stage = TextureStage('layer2') cls.layer3stage = TextureStage('layer3') cls.layer4stage = TextureStage('layer4') cls.texture_sets = {} layernames = ["layer1", "layer2", "layer3", "layer4"] stages = [ cls.layer1stage, cls.layer2stage, cls.layer3stage, cls.layer4stage ] texture_files = os.listdir("texture/planet/layers/") for filename in texture_files: name, ext = os.path.splitext(filename) if name.endswith("layer1"): paths = [ "texture/planet/layers/" + filename.replace("layer1", layer) for layer in layernames ] if all(os.path.exists(path) for path in paths): setname = name.replace("layer1", "").strip("_") texture_set = [(cls.noisestage, cls.noisetex)] for stage, path in zip(stages, paths): tex = loader.loadTexture(path) tex.setWrapU(Texture.WMClamp) tex.setWrapV(Texture.WMClamp) texture_set.append((stage, tex)) cls.texture_sets[setname] = texture_set cls.ready = True
def __init__(self, scene, dynamic=True, rate=Vec4(0.004, 0.002, 0.008, 0.010), skycolor=Vec4(0.25, 0.5, 1, 0), texturescale=Vec4(1, 1, 1, 1), scale=(4000, 4000, 1000), texturefile=None): Att_base.__init__(self, False, "Sky Dome 2") self.skybox = loader.loadModel("./media/models/dome2") self.skybox.reparentTo(scene) self.skybox.setScale(scale[0], scale[1], scale[2]) self.skybox.setLightOff() if texturefile == None: texturefile = "./media/textures/clouds_bw.png" texture = loader.loadTexture(texturefile) self.textureStage0 = TextureStage("stage0") self.textureStage0.setMode(TextureStage.MReplace) self.skybox.setTexture(self.textureStage0, texture, 1) #self.skybox.setTexScale(self.textureStage0, texturescale[0], texturescale[1]) self.rate = rate self.textureScale = texturescale self.skycolor = skycolor self.dynamic = dynamic if self.dynamic: self.skybox.setShader( loader.loadShader('./media/shaders/skydome2.sha')) self.setShaderInput()
class SkyDome1(Att_base): def __init__(self, scene, dynamic=True, rate=(0.005,0.05), texturescale=(1000,1000), scale=(40,40,10), texturefile=None): Att_base.__init__(self,False, "Sky Dome 1") self.skybox = loader.loadModel("../media/models/dome2") self.skybox.setCollideMask(BitMask32().allOff()) self.skybox.setTwoSided(False) self.skybox.setScale(scale[0],scale[1],scale[2]) self.skybox.setLightOff() if texturefile == None: texturefile = "../media/textures/concrete.jpg" texture = loader.loadTexture(texturefile) self.textureStage0 = TextureStage("stage0") self.textureStage0.setMode(TextureStage.MReplace) self.skybox.setTexture(self.textureStage0,texture,1) self.skybox.setTexScale(self.textureStage0, texturescale[0], texturescale[1]) self.skybox.reparentTo(scene) def setTextureScale(self, texturescale): self.skybox.setTexScale(self.textureStage0, texturescale[0], texturescale[1]) def Destroy(self): self.skybox.removeNode() def setPos(self, v): self.skybox.setPos(v) def show(self): self.skybox.show() def hide(self): self.skybox.hide()
def loadDetail(self): self.detailTS = TextureStage('ts') tex = self.loadTexture("Detail_COLOR.jpg") tex.setWrapU(Texture.WMMirror) tex.setWrapV(Texture.WMMirror) self.detailTexture = tex self.textureBlendMode = self.detailTS.MHeight self.detailTS.setMode(self.textureBlendMode)
class DetailTexturer(TerrainTexturer): """adds a texture + detail texture to TerrainTiles""" def load(self): self.ts1 = TextureStage('ts2') tex = self.loadTexture("snow.jpg") tex.setWrapU(Texture.WMMirror) tex.setWrapV(Texture.WMMirror) self.monoTexture = tex self.loadDetail() def loadDetail(self): self.detailTS = TextureStage('ts') tex = self.loadTexture("Detail_COLOR.jpg") tex.setWrapU(Texture.WMMirror) tex.setWrapV(Texture.WMMirror) self.detailTexture = tex self.textureBlendMode = self.detailTS.MHeight self.detailTS.setMode(self.textureBlendMode) def apply(self, input): """Apply textures and shaders to the input.""" input.setTexture(self.ts1, self.monoTexture) input.setTexScale(self.ts1, 5, 5) input.setTexture(self.detailTS, self.detailTexture) input.setTexScale(self.detailTS, 120, 120) def setDetailBlendMode(self, num): """Set the blending mode of the detail texture.""" if (not self.detailTexture): return self.textureBlendMode = num #for pos, tile in self.tiles.items(): # if tile.detailTS: # tile.detailTS.setMode(self.textureBlendMode) self.detailTS.setMode(self.textureBlendMode) def incrementDetailBlendMode(self): """Set the blending mode of the detail texture.""" if (not self.detailTexture): return self.textureBlendMode += 1 self.setDetailBlendMode(self.textureBlendMode) def decrementDetailBlendMode(self): """Set the blending mode of the detail texture.""" if (not self.detailTexture): return self.textureBlendMode -= 1 self.setDetailBlendMode(self.textureBlendMode)
def UpdateTexture(self): if(not self.model): self.LoadContent() (u, v) = BlockGeometryGenerator.BlockIdToUV(self.currentBlockIdToPlace + 1) # Add 1 to offset from Air Id = 0 ts = TextureStage('ts') ts.setMode(TextureStage.MReplace) self.model.clearTexture() self.model.setTexture(ts, self.blockTexture) self.model.setTexOffset(ts, u[0], v[0]) self.model.setTexScale(ts, 0.0625, 0.0625)
def __init__(self, x1, y1, x2, y2, z): Att_base.__init__(self, False, "Water1") # Water surface maker = CardMaker( 'water' ) maker.setFrame( x1, x2, y1, y2 ) self.waterNP = render.attachNewNode(maker.generate()) self.waterNP.setHpr(0,-90,0) self.waterNP.setPos(0,0,z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha ) self.waterNP.setShader(loader.loadShader( 'Shaders/water1.sha' )) # Reflection plane self.waterPlane = Plane( Vec3( 0, 0, z+1 ), Point3( 0, 0, z ) ) planeNode = PlaneNode( 'waterPlane' ) planeNode.setPlane( self.waterPlane ) # Buffer and reflection camera self.buffer = base.win.makeTextureBuffer( 'waterBuffer', 512, 512 ) self.buffer.setClearColor( Vec4( 0, 0, 0, 1 ) ) cfa = CullFaceAttrib.makeReverse( ) rs = RenderState.make(cfa) self.watercamNP = base.makeCamera( self.buffer ) self.watercamNP.reparentTo(render) sa = ShaderAttrib.make() sa = sa.setShader(loader.loadShader('Shaders/splut3Clipped.sha') ) self.cam = self.watercamNP.node() self.cam.getLens( ).setFov( base.camLens.getFov( ) ) self.cam.getLens().setNear(1) self.cam.getLens().setFar(5000) self.cam.setInitialState( rs ) self.cam.setTagStateKey('Clipped') self.cam.setTagState('True', RenderState.make(sa)) # ---- water textures --------------------------------------------- # 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)
def __init__(self, base): tex = base.loader.loadCubeMap("./sky/sky_#.png") cube = base.loader.loadModel("./sky/icube.egg") cube.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) cube.setTexProjector(TextureStage.getDefault(), base.render, cube) cube.setTexture(tex) cube.setBin("background", 1) cube.setLightOff() cube.setDepthWrite(False) cube.setScale(5, 5, 5) cube.reparentTo(base.camera) cube.setCompass()
def loadAndSetCubeTexture2( self, nodePath1, nodePath2, fileName, textureStageName, texCoordName, sort ): #load texture from file texture = loader.loadCubeMap(fileName) #set texture stage textureStage=TextureStage(textureStageName) textureStage.setTexcoordName(texCoordName) textureStage.setSort(sort) #set texture and texture stage nodePath1.setTexture(textureStage,texture) nodePath2.setTexture(textureStage,texture)
def loadAndSetTexture(self,nodePath,fileName,textureStageName,texCoordName,sort): #load texture from file texture=loader.loadTexture(fileName) texture.setWrapU(Texture.WMClamp) texture.setWrapV(Texture.WMClamp) #set texture stage textureStage=TextureStage(textureStageName) textureStage.setTexcoordName(texCoordName) textureStage.setSort(sort) #set texture and texture stage nodePath.setTexture(textureStage,texture)
def flipTexture(self): """ Sets the texture coordinates of the texture to the current frame""" sU = self.offsetX * self.repeatX sV = self.offsetY * self.repeatY oU = 0 + self.frames[self.currentFrame].col * self.uSize oV = 1 - self.frames[self.currentFrame].row * self.vSize - self.offsetY if self.flip['x']: sU *= -1 oU = self.uSize + self.frames[self.currentFrame].col * self.uSize if self.flip['y']: sV *= -1 oV = 1 - self.frames[self.currentFrame].row * self.vSize self.node.setTexScale(TextureStage.getDefault(), sU, sV) self.node.setTexOffset(TextureStage.getDefault(), oU, oV)
def SetGeomTexture(geom, geomId, node, blockTexture): """ Applies the texture to the visible geometry of the Chunk.""" ts = TextureStage('ts') ts.setMode(TextureStage.MDecal) ts.setTexcoordName('light') # Setup the block texture attrib = TextureAttrib.make(blockTexture) # Add the light overlay #attrib = attrib.addOnStage(ts, geom['lighttexture']) # Apply the texture to the node node.setGeomState(geomId, node.getGeomState(geomId).addAttrib(attrib))
def makeFadeIn(self, nodePath): # make a fade in of the new objects # our alpha gradient texture transTex = loader.loadTexture("data/textures/transSlider.tif") transTex.setWrapU(Texture.WMClamp) # our texture stage. By default it's set to modulate. # we give it a high sort value since it needs to be # 'above' the rest. ts = TextureStage("alpha") ts.setSort(1000) # apply the texture nodePath.setTexture(ts, transTex) nodePath.setTexScale(ts, Vec2(0)) nodePath.setTransparency(1) self.fadingNodepaths[nodePath] = [time.time(), ts]
def AddNewTextureStage(self, type=Texture.TT2dTexture): """Adds a new texture input to Fragment and returns a two-tuple with the texnum and new TextureStage.""" ts = TextureStage("tex_%d" % self.__curTex) if type == Texture.TT1dTexture: type = "sampler1D" elif type == Texture.TT2dTexture: type = "sampler2D" elif type == Texture.TT3dTexture: type = "sampler2D" elif type == Texture.TTCubeMap: type = "samplerCUBE" if not (isinstance(type, str) and type.startswith("sampler")): raise TypeError, "Unknown texture type %s!" % str(type) self.AddInput("tex_%d" % self.__curTex, "uniform " + type, "TEXUNIT%d" % self.__curTex) self.__curTex += 1 ts.setSort(self.__curTex) return self.__curTex - 1, ts
def __initSceneGraph(self): # Parent node for relative position (no scaling) self.point_path = render.attachNewNode("star_node") self.point_path.setPos(self.position) #For transforming the object with scaling, colors, shading, etc. # Hosting the actual 3d model object. #Models & textures self.flare_ts = TextureStage('flare') self.flare_ts.setMode(TextureStage.MModulateGlow) self.model_path = loader.loadModel("models/stars/planet_sphere") self.model_path.setTexture(SphericalBody.star_dead_tex, 1) self.model_path.reparentTo(self.point_path) self.model_path.setScale(self.radius) self.model_path.setPythonTag('pyStar', self); # Collision sphere for object picking #----------------------------------------------------- # As described in the Tut-Chessboard.py sample: "If this model was # any more complex than a single polygon, you should set up a collision # sphere around it instead." cnode = CollisionNode("coll_sphere_node") cnode.setTag('star', str(id(self))) #We use no displacement (0,0,0) and no scaling factor (1) cnode.addSolid(CollisionSphere(0,0,0,1)) cnode.setIntoCollideMask(BitMask32.bit(1)) self.cnode_path = self.model_path.attachNewNode(cnode) #For temporary testing, display collision sphere. # self.cnode_path.show() self.quad_path = None
def __init__(self, **kwargs): """ See the Element class to find out what attributes are available from scratch """ super(VideoPlayer, self).__init__(**kwargs) self.videofile = getattr(self.config, 'file_video', None) self.loopCount = getattr(self.config, 'loop', 1) self.hoffset = getattr(self.config, 'hoffset', 0) self.voffset = getattr(self.config, 'voffset', 0) #self.videoScale = getattr(self.config, 'scale', (1,1)) #self.playrate = getattr(self.config, 'speed', 1.0) if self.videofile: movieTexture = loader.loadTexture(self.videofile) cm = CardMaker("video_card") # cm.setFrameFullscreenQuad() cm.setUvRange(movieTexture) card = NodePath(cm.generate()) card.reparentTo(self.hudNP) card.setTexture(movieTexture) card.setTexScale(TextureStage.getDefault(), movieTexture.getTexScale()) card.setPos(-0.5 + self.hoffset, 0.0, -0.5 + self.voffset) self.movie = movieTexture print card.getScale() self.time = 0 self.movie.stop() self.hideElement()
def set_leaf_tex(self, leaf_tex): if leaf_tex != None: ts = TextureStage('ts') for leaf in self.leafs: leaf.setTexture(ts, leaf_tex) leaf.setTexScale(ts, 10, 10) leaf.setTransparency(TransparencyAttrib.MAlpha)
def setupRightTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT) / float(WIN_HEIGHT) # the html area will be center aligned and vertically top aligned #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0) cm.setFrame(0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) card = cm.generate() self.rightQuad = NodePath(card) self.rightQuad.reparentTo(self.parent) self.rightGuiTex = Texture("guiTex") self.rightGuiTex.setupTexture(Texture.TT2dTexture, WEB_HALF_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.rightGuiTex.setKeepRamImage(True) self.rightGuiTex.makeRamImage() self.rightGuiTex.setWrapU(Texture.WMClamp) self.rightGuiTex.setWrapV(Texture.WMClamp) ts = TextureStage('rightWebTS') self.rightQuad.setTexture(ts, self.rightGuiTex) self.rightQuad.setTexScale(ts, 1.0, -1.0) self.rightQuad.setTransparency(0) self.rightQuad.setTwoSided(True) self.rightQuad.setColor(1.0, 1.0, 1.0, 1.0)
def __setupLevel(self): """ Originally planned to have multiple levels, that never happened. """ level1 = render.attachNewNode("level 1 node path") execfile("rooms/room.py") self.room = loader.loadModel("rooms/room") self.room.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear) self.room.setScale(10,10,5) self.room.setTexScale(TextureStage.getDefault(), 10) self.room.reparentTo(render) self.room.find("**/Cube;+h").setTag("Room", "1") gate = loader.loadModel("models/box") gateTo2 = self.room.attachNewNode("gateTo2") gate.instanceTo(gateTo2) gateTo2.setPos(8, -10, 0) gateTo2.hide() self.physicsCollisionHandler.addInPattern("%fn-into-%in") self.physicsCollisionHandler.addOutPattern("%fn-out-%in") #messenger.toggleVerbose() self.gate = gate
def __init__(self): tex1 = loader.loadTexture('textures/clouds.jpg') tex1.setMagfilter(Texture.FTLinearMipmapLinear) tex1.setMinfilter(Texture.FTLinearMipmapLinear) tex1.setAnisotropicDegree(2) tex1.setWrapU(Texture.WMRepeat) tex1.setWrapV(Texture.WMRepeat) tex1.setFormat(Texture.FAlpha) self.ts1 = TextureStage('clouds') #self.ts1.setMode(TextureStage.MBlend) self.ts1.setColor(Vec4(1, 1, 1, 1)) #self.plane(-2000, -2000, 2000, 2000, 100) self.sphere(10000, -9600) self.clouds.setTransparency(TransparencyAttrib.MDual) self.clouds.setTexture(self.ts1, tex1) self.clouds.setBin('background', 3) self.clouds.setDepthWrite(False) self.clouds.setDepthTest(False) self.clouds.setTwoSided(True) self.clouds.setLightOff(1) self.clouds.setShaderOff(1) self.clouds.setFogOff(1) self.clouds.hide(BitMask32.bit(2)) # Hide from the volumetric lighting camera self.speed = 0.003 self.time = 0 self.dayColor = Vec4(0.98, 0.98, 0.95, 1.0) self.nightColor = Vec4(-0.5, -0.3, .0, 1.0) self.sunsetColor = Vec4(0.75, .60, .65, 1.0) ColoredByTime.__init__(self) self.setColor = self.clouds.setColor
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 _createSpritesNodeSetup(self, parent): ''' Setups a new scenegraph that allows using screen coordinates instead of 3D. The conversions are automated by the configuration of the scene nodes. ''' screenWidth = base.win.getXSize() screenHeight = base.win.getYSize() aspect_ratio = parent.getScale()[0] screenOrigin = parent.attachNewNode('screen_origin') screenNode = screenOrigin.attachNewNode('screen_node') screenOrigin.setPos(-1.0 / aspect_ratio, 0.0, 1.0) screenOrigin.setScale(2.0, 1.0, -2.0) screenNode.setPos(0, 0, 0) screenNode.setScale(1.0 / (aspect_ratio * screenWidth), 1.0, 1.0 / screenHeight) screenNode.setTexScale(TextureStage.getDefault(), 1.0, -1.0) # test some points # points = [(0,0), (screenWidth, 0), (screenWidth, screenHeight), (screenWidth/2.0, screenHeight/2.0), (0, screenHeight)] # for pt in points: # print '%s -> %s' % (pt, str(parent.getRelativePoint(screenNode, Vec3(pt[0], 0, pt[1])))) return screenNode
def __init__(self, scene, dynamic=True, rate=Vec4(0.004, 0.002, 0.008, 0.010), skycolor=Vec4(0.25, 0.5, 1, 0), texturescale=Vec4(1,1,1,1), scale=(4000,4000,1000), texturefile=None): Att_base.__init__(self,False, "Sky Dome 2") self.skybox = loader.loadModel("./media/models/dome2") self.skybox.reparentTo(scene) self.skybox.setScale(scale[0],scale[1],scale[2]) self.skybox.setLightOff() if texturefile == None: texturefile = "./media/textures/clouds_bw.png" texture = loader.loadTexture(texturefile) self.textureStage0 = TextureStage("stage0") self.textureStage0.setMode(TextureStage.MReplace) self.skybox.setTexture(self.textureStage0,texture,1) #self.skybox.setTexScale(self.textureStage0, texturescale[0], texturescale[1]) self.rate = rate self.textureScale = texturescale self.skycolor = skycolor self.dynamic = dynamic if self.dynamic: self.skybox.setShader( loader.loadShader( './media/shaders/skydome2.sha' ) ) self.setShaderInput()
def renderToGeom(resources, geom, video, audio): videoTex = loader.loadTexture( resources.getResourceFullPath(PanoConstants.RES_TYPE_VIDEOS, video)) if videoTex is None: print "Couldn't load video %s" % video return None # if (base.sfxManagerList[0].getType().getName() != "OpenALAudioManager"): # self.log.error("OpenAL support is not enabled, cannot proceed.") # return None if (videoTex.getType().getName() != "MovieTexture"): print "MovieTexture support is not enabled, cannot proceed." return None geom.setTexture(videoTex) videoTex.setWrapU(Texture.WMClamp) videoTex.setWrapV(Texture.WMClamp) if videoTex.getTexturesPower2(): geom.setTexScale(TextureStage.getDefault(), videoTex.getTexScale()) if audio is not None: vidSound = loader.loadSfx( resources.getResourceFullPath(PanoConstants.RES_TYPE_MUSIC, audio)) videoTex.synchronizeTo(vidSound) return vidSound else: return videoTex
def __init__(self, world, parent, pos, dir, width, height, color, name, textureFilename=None): self.node = parent.attachNewNode("") self.node.setPos(*pos) self.node.lookAt(self.node, *dir) self.name = name divisions = 1 for i in range(divisions): for j in range(divisions): self.makeCard(color, width, height, i, j, divisions) if textureFilename == None: self.texture = None else: self.texture = loader.loadTexture(textureFilename) self.texture.setWrapU(Texture.WMRepeat) self.texture.setWrapV(Texture.WMRepeat) self.node.setTexture(self.texture) self.node.setTexScale(TextureStage.getDefault(), 0.5, 0.5) self.geom = OdePlaneGeom(world.space, makeVec4FromPointAndNormal(pos, dir)) world.space.setSurfaceType(self.geom, world.surfaces["plane"])
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
def __setupLevel(self): """ Originally planned to have multiple levels, that never happened. """ level1 = render.attachNewNode("level 1 node path") execfile("rooms/room.py") self.room = loader.loadModel("rooms/room") self.room.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear) self.room.setScale(10, 10, 5) self.room.setTexScale(TextureStage.getDefault(), 10) self.room.reparentTo(render) self.room.find("**/Cube;+h").setTag("Room", "1") gate = loader.loadModel("models/box") gateTo2 = self.room.attachNewNode("gateTo2") gate.instanceTo(gateTo2) gateTo2.setPos(8, -10, 0) gateTo2.hide() self.physicsCollisionHandler.addInPattern("%fn-into-%in") self.physicsCollisionHandler.addOutPattern("%fn-out-%in") #messenger.toggleVerbose() self.gate = gate
def __init__(self, phasedLoading = False): self.wantProws = config.GetBool('want-sprits', 0) self.hulls = { } self.texInfo = ({ }, { }, { }) self.models = { } self.mastSets = { } ShipBlueprints.setupWheel() ShipBlueprints.setupShipTextures() self.preprocessMast(ShipGlobals.Masts.Main_Tri) self.preprocessMast(ShipGlobals.Masts.Fore_Tri) self.preprocessHull(ShipGlobals.INTERCEPTORL1) self.preprocessMast(ShipGlobals.Masts.Skel_Main_A) self.preprocessMast(ShipGlobals.Masts.Skel_Main_B) self.preprocessMast(ShipGlobals.Masts.Skel_Tri) self.preprocessMast(ShipGlobals.Masts.Skel_Fore) self.preprocessMast(ShipGlobals.Masts.Skel_Aft) self.preprocessHull(ShipGlobals.SKEL_INTERCEPTORL3) self.preprocessHull(ShipGlobals.SKEL_WARSHIPL3) if not phasedLoading: self.handlePhase4() self.handlePhase5() self.baseLayer = TextureStage('base') self.colorLayer = TextureStage('color') self.logoLayer = TextureStage('logo') self.logoLayerNoColor = TextureStage('logoNoColor') self.vertLayer = TextureStage('vertex') self.colorLayer.setSort(1) self.colorLayer.setCombineRgb(TextureStage.CMReplace, TextureStage.CSTexture, TextureStage.COSrcColor) self.colorLayer.setCombineAlpha(TextureStage.CMReplace, TextureStage.CSTexture, TextureStage.COSrcAlpha) self.colorLayer.setTexcoordName('uvColor') self.logoLayer.setSort(2) self.logoLayer.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSTexture, TextureStage.COSrcColor, TextureStage.CSPrevious, TextureStage.COSrcColor, TextureStage.CSTexture, TextureStage.COSrcAlpha) self.logoLayer.setCombineAlpha(TextureStage.CMReplace, TextureStage.CSPrevious, TextureStage.COSrcAlpha) self.logoLayer.setTexcoordName('uvLogo') self.logoLayerNoColor.setSort(2) self.logoLayerNoColor.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSTexture, TextureStage.COSrcColor, TextureStage.CSConstant, TextureStage.COSrcColor, TextureStage.CSTexture, TextureStage.COSrcAlpha) self.logoLayerNoColor.setCombineAlpha(TextureStage.CMReplace, TextureStage.CSPrevious, TextureStage.COSrcAlpha) self.logoLayerNoColor.setTexcoordName('uvLogo') self.logoLayerNoColor.setColor((1, 1, 1, 1)) self.vertLayer.setSort(3) self.vertLayer.setCombineRgb(TextureStage.CMModulate, TextureStage.CSPrevious, TextureStage.COSrcColor, TextureStage.CSPrimaryColor, TextureStage.COSrcColor) self.vertLayer.setCombineAlpha(TextureStage.CMReplace, TextureStage.CSPrimaryColor, TextureStage.COSrcAlpha) self.baseLayer.setSort(4) self.baseLayer.setCombineRgb(TextureStage.CMModulate, TextureStage.CSTexture, TextureStage.COSrcColor, TextureStage.CSPrevious, TextureStage.COSrcColor) self.baseLayer.setCombineAlpha(TextureStage.CMModulate, TextureStage.CSTexture, TextureStage.COSrcAlpha, TextureStage.CSPrevious, TextureStage.COSrcAlpha)
def updateHeightField( self ): ''' recalculate heightfield ''' if self.mHeightFieldNode != None: self.mHeightFieldNode.removeNode() posX, posY = self.world2MapPos( ( self.cameraPos.getX(), self.cameraPos.getY() ) ) self.mHeightFieldTesselator.setFocalPoint( int(posX), int(posY) ) self.mHeightFieldNode = self.mHeightFieldTesselator.generate() self.mHeightFieldNode.setPos( MAPSIZE/2, MAPSIZE/2, 0 ) self.mHeightFieldNode.setHpr( 270, 0, 0 ) self.mHeightFieldNode.reparentTo(render) self.mHeightFieldNode.setTexGen( TextureStage.getDefault(), TexGenAttrib.MWorldPosition ) scale = 1.0/8.0 self.mHeightFieldNode.setTexScale( TextureStage.getDefault(), scale, scale ); self.mHeightFieldNode.setTexture( self.tex0, 1 )
def ry_floor(self, gso): tex = self.loader.loadTexture("wood_floor_tex_0.jpg") ts = TextureStage.getDefault() gso.setTexGen(ts, TexGenAttrib.MWorldPosition) gso.setTexProjector(ts, self.render, gso) gso.setTexture(ts, tex) gso.setTexScale(ts, Vec2(0.25, 0.25) * 10.) gso.setColor((0.99, 0.99, 0.99, 1.))
def load(self): self.ts1 = TextureStage('ts2') tex = self.loadTexture("snow.jpg") tex.setWrapU(Texture.WMMirror) tex.setWrapV(Texture.WMMirror) self.monoTexture = tex self.loadDetail()
def load(self): """single texture""" self.ts = TextureStage('ts') tex = self.loadTexture("rock.jpg") tex.setWrapU(Texture.WMMirror) tex.setWrapV(Texture.WMMirror) self.monoTexture = tex
def __setupEnvironment(self): cm = CardMaker("ground") size = 200 cm.setFrame(-size, size, -size, size) environment = render.attachNewNode(cm.generate()) environment.lookAt(0, 0, -1) environment.setPos(100, -100, 0) environment.setCollideMask(BitMask32.allOn()) environment.reparentTo(render) texture = loader.loadTexture("textures/ground.png") # This is so the textures can look better from a distance texture.setMinfilter(Texture.FTLinearMipmapLinear) environment.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) environment.setTexScale(TextureStage.getDefault(), 0.02, 0.02) environment.setTexture(texture, 1)
def add_texture(self,tex_path): plat_texture = loader.loadTexture(tex_path) #plat_texture.setWrapU(Texture.WMRepeat) #plat_texture.setWrapV(Texture.WMRepeat) self.model.setTexture(plat_texture,1) ts = TextureStage.getDefault() texture = self.model.getTexture() #self.model.setTexOffset(ts, -0.5, -0.5) self.model.setTexScale(ts, 2, 2)
def __init__(self, cubeMapPath=None): yawOff = 198 self.sphere = loader.loadModel("InvertSphereBlend.egg") # self.sphere = loader.loadModel("InvertedSphere.egg") # Load a sphere with a radius of 1 unit and the faces directed inward. self.sphere.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.sphere.setTexProjector(TextureStage.getDefault(), render, self.sphere) self.sphere.setTexTransform( TextureStage.getDefault(), TransformState.makeHpr(VBase3(yawOff, 0, 0))) # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual. self.sphere.setPos((0, 0, 0)) self.sphere.setTexPos(TextureStage.getDefault(), 0, 0, 0) self.sphere.setTexScale(TextureStage.getDefault(), 1) # tex = loader.loadCubeMap(cubeMapPath) if cubeMapPath is None: cubeMapPath = renamer() tex = loader.loadCubeMap(cubeMapPath) self.sphere.setTexture(tex) # Load the cube map and apply it to the sphere. self.sphere.setLightOff() # Tell the sphere to ignore the lighting. self.sphere.setScale(10) # Increase the scale of the sphere so it will be larger than the scene. print self.sphere.getHpr() print self.sphere.getPos() self.sphere.reparentTo(render) # Reparent the sphere to render so you can see it. # result = self.sphere.writeBamFile(cubeMapPath.split('_#.tga')[0]+'.bam') print '/'.join(cubeMapPath.split('/')[:-1]) + '.bam' base.saveCubeMap('streetscene_cube_#.jpg', size=512) result = self.sphere.writeBamFile( '/'.join(cubeMapPath.split('/')[:-1]) + '.bam') # Save out the bam file. print(result)
def loadFlatQuad(self, fullFilename): """Load the flat jpg into a quad.""" assert self.notify.debugStateCall(self) #Texture.setTexturesPower2(AutoTextureScale.ATSUp) #Texture.setTexturesPower2(2) 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) # the html area will be center aligned and vertically top aligned #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0) 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,0), Point2(bottomRightX, bottomRightY)) cm.setUvRange(Point2(0,1-bottomRightY), Point2(bottomRightX,1)) card = cm.generate() quad = NodePath(card) #quad.reparentTo(self.parent) 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.setKeepRamImage(True) #guiTex.makeRamImage() guiTex.setWrapU(Texture.WMClamp) guiTex.setWrapV(Texture.WMClamp) ts = TextureStage('webTS') quad.setTexture(ts, guiTex) #quad.setTexScale(ts, 1.0, -1.0) quad.setTransparency(0) quad.setTwoSided(True) quad.setColor(1.0, 1.0, 1.0, 1.0) result= quad else: # if we have an error loading the file, return None to signify an error result = None #Texture.setTexturesPower2(AutoTextureScale.ATSDown) Texture.setTexturesPower2(1) return result
def render(self): LOG.debug("[SkyBox] Rendering") # If we are an orphan use render if self.parent is None: self.parent = render #LOG.debug("[SkyBox] model=%s"%self.modelFile) self.node = loader.loadModel(self.modelFile) #print("tf1 = %s, tf2 = %s"%(self.texture1File,self.texture2File)) if self.texture1File != '' and self.texture2File == '': #LOG.debug("[SkyBox] single texture = %s"%self.texture1File) t = loader.loadTexture(self.texture1File) self.node.setTexture(t) elif self.texture1File != '' and self.texture2File != '': #LOG.debug("[SkyBox] texture staging 1 = %s, 2 = %s"%(self.texture1File,self.texture2File)) t1 = loader.loadTexture(self.texture1File) t1.setWrapU(Texture.WMClamp) t1.setWrapV(Texture.WMClamp) ts1 = TextureStage('Space') ts1.setSort(self.texture1Sort) t2 = loader.loadTexture(self.texture2File) t2.setWrapU(Texture.WMClamp) t2.setWrapV(Texture.WMClamp) ts2 = TextureStage('SpaceClouds') ts2.setSort(self.texture2Sort) self.node.setTexture(ts1, t1) self.node.setTexture(ts2, t2) if self.shaderFile: LOG.debug("[SkyBox] shader = %s" % self.shaderFile) #skyShader = Shader.load("./data/shaders/%s"%self.shaderFile) skyShader = Shader.load("%s" % self.shaderFile) self.node.setShader(skyShader) # Should this be scaled here or done to the model? # It doesn't look like scaling the objects looks any different. self.node.setScale(280) # make sure it's drawn first (this can be done with shaders?) self.node.setBin('background', 0) # dont set depth attribute when rendering the sky (this can be done with shaders?) self.node.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff)) # We don't want shadows on the skybox self.node.setLightOff() # Render self.node.reparentTo(self.parent) taskMgr.add(self.moveSkyTask, "Move the sky box with the cam")
def __init__(self,cubeMapPath=None): yawOff=198 self.sphere = loader.loadModel("InvertSphereBlend.egg") # self.sphere = loader.loadModel("InvertedSphere.egg") # Load a sphere with a radius of 1 unit and the faces directed inward. self.sphere.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.sphere.setTexProjector(TextureStage.getDefault(), render, self.sphere) self.sphere.setTexTransform(TextureStage.getDefault(), TransformState.makeHpr(VBase3(yawOff, 0, 0))) # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual. self.sphere.setPos((0,0,0)) self.sphere.setTexPos(TextureStage.getDefault(), 0, 0, 0) self.sphere.setTexScale(TextureStage.getDefault(), 1) # tex = loader.loadCubeMap(cubeMapPath) if cubeMapPath is None: cubeMapPath=renamer() tex = loader.loadCubeMap(cubeMapPath) self.sphere.setTexture(tex) # Load the cube map and apply it to the sphere. self.sphere.setLightOff() # Tell the sphere to ignore the lighting. self.sphere.setScale(10) # Increase the scale of the sphere so it will be larger than the scene. print self.sphere.getHpr() print self.sphere.getPos() self.sphere.reparentTo(render) # Reparent the sphere to render so you can see it. # result = self.sphere.writeBamFile(cubeMapPath.split('_#.tga')[0]+'.bam') print '/'.join(cubeMapPath.split('/')[:-1])+'.bam' base.saveCubeMap('streetscene_cube_#.jpg', size=512) result = self.sphere.writeBamFile('/'.join(cubeMapPath.split('/')[:-1])+'.bam') # Save out the bam file. print(result)
def __setupEnvironment(self): cm = CardMaker("ground") size = 100 cm.setFrame(-size, size, -size, size) environment = render.attachNewNode(cm.generate()) environment.lookAt(0, 0, -1) environment.setPos(0, 0, 0) environment.setCollideMask(BitMask32.allOn()) environment.reparentTo(render) texture = loader.loadTexture("textures/ground.png") # This is so the textures can look better from a distance texture.setMinfilter(Texture.FTLinearMipmapLinear) environment.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) environment.setTexScale(TextureStage.getDefault(), 0.02, 0.02) environment.setTexture(texture, 1)
def Texture(self): """Applies textures and if needed shaders to the terrain. Call this initially, and whenever you have changed the size of some important textures, or added/removed some textures or changed the lighting mode. This function is automatically called by Initialize().""" if self.TextureMap == "": self.TextureMap = None if self.LightMap == "": self.LightMap = None # Does it have a detail map? if len(self.AlphaMaps) > 0: self._textureDetailed() elif self.TextureMap != None: self.Root.setTexture(self.TextureMap, 1) if self.LightMap != None: ts = TextureStage("LightMap") ts.setMode(TextureStage.MModulate) ts.setSort(2) self.Root.setTexture(ts, self.LightMap, 2) elif self.LightMap != None: self.Root.setTexture(ts, self.LightMap, 1)
def applyTexture(self): self.texture = loader.loadTexture("media/gray_stone_tile.png") self.texture.setWrapU(Texture.WMRepeat) self.texture.setWrapV(Texture.WMRepeat) self.model.setTexture(self.texture, 1) # Calculate and apply texture scale factors. sizes = entrywiseMult(vecInvert(self.tileDir), self.size) scales = [] for i in sizes: scales.append(i) if i != 0 else None self.model.setTexScale(TextureStage.getDefault(), scales[0], scales[1])
class SkyDome1(Att_base): def __init__(self, scene, dynamic=True, rate=(0.005, 0.05), texturescale=(1000, 1000), scale=(40, 40, 10), texturefile=None): Att_base.__init__(self, False, "Sky Dome 1") self.skybox = loader.loadModel("../media/models/dome2") self.skybox.setCollideMask(BitMask32().allOff()) self.skybox.setTwoSided(False) self.skybox.setScale(scale[0], scale[1], scale[2]) self.skybox.setLightOff() if texturefile == None: texturefile = "../media/textures/concrete.jpg" texture = loader.loadTexture(texturefile) self.textureStage0 = TextureStage("stage0") self.textureStage0.setMode(TextureStage.MReplace) self.skybox.setTexture(self.textureStage0, texture, 1) self.skybox.setTexScale(self.textureStage0, texturescale[0], texturescale[1]) self.skybox.reparentTo(scene) def setTextureScale(self, texturescale): self.skybox.setTexScale(self.textureStage0, texturescale[0], texturescale[1]) def Destroy(self): self.skybox.removeNode() def setPos(self, v): self.skybox.setPos(v) def show(self): self.skybox.show() def hide(self): self.skybox.hide()
def flipTexture(self): """ Sets the texture coordinates of the texture to the current frame""" for i in range(len(self.cards)): currentRow = self.rowPerFace[i] sU = self.offsetX * self.repeatX sV = self.offsetY * self.repeatY oU = 0 + self.currentFrame * self.uSize #oU = 0 + self.frames[self.currentFrame].col * self.uSize #oV = 1 - self.frames[self.currentFrame].row * self.vSize - self.offsetY oV = 1 - currentRow * self.vSize - self.offsetY if self.flip['x'] ^ i == 1: ##hack to fix side view #print "flipping, i = ",i sU *= -1 #oU = self.uSize + self.frames[self.currentFrame].col * self.uSize oU = self.uSize + self.currentFrame * self.uSize if self.flip['y']: sV *= -1 #oV = 1 - self.frames[self.currentFrame].row * self.vSize oV = 1 - currentRow * self.vSize self.cards[i].setTexScale(TextureStage.getDefault(), sU, sV) self.cards[i].setTexOffset(TextureStage.getDefault(), oU, oV)
def flipTexture(self): """ Sets the texture coordinates of the texture to the current frame""" for i in range(len(self.cards)): currentRow = self.rowPerFace[i] sU = self.offsetX * self.repeatX sV = self.offsetY * self.repeatY oU = 0 + self.currentFrame * self.uSize #oU = 0 + self.frames[self.currentFrame].col * self.uSize #oV = 1 - self.frames[self.currentFrame].row * self.vSize - self.offsetY oV = 1 - currentRow * self.vSize - self.offsetY if self.flip['x'] ^ i==1: ##hack to fix side view #print "flipping, i = ",i sU *= -1 #oU = self.uSize + self.frames[self.currentFrame].col * self.uSize oU = self.uSize + self.currentFrame * self.uSize if self.flip['y']: sV *= -1 #oV = 1 - self.frames[self.currentFrame].row * self.vSize oV = 1 - currentRow * self.vSize self.cards[i].setTexScale(TextureStage.getDefault(), sU, sV) self.cards[i].setTexOffset(TextureStage.getDefault(), oU, oV)
def __init__(self, panda3d): # Inicialización de variables self.winsize = [0, 0] self.panda3d = panda3d sha_normal = "data/shaders/normalGen.sha" sha_depth = "data/shaders/depthGen.sha" sha_color = "data/shaders/colorGen.sha" sha_ink = "data/shaders/inkGen.sha" self.normal_buff, self.normal_cam = self.make_buffer( "normalsBuffer", sha_normal, 0.5) # self.depth_buff, self.depth_cam = self.make_buffer("depthBuffer", sha_depth, 0.5) self.color_buff, self.color_cam = self.make_buffer( "colorsBuffer", sha_color, 0.5) tex_normal = self.normal_buff.getTextureCard() # tex_depth = self.depth_buff.getTextureCard() tex_color = self.color_buff.getTextureCard() tex_normal.setTransparency(1) tex_normal.setColor(1, 1, 1, 1) tex_normal.reparentTo(self.panda3d.render2d) stage_border = TextureStage("border") stage_border.setSort(1) # tex_normal.setTexture(stage_border, tex_color.getTexture()) # stage_depth = TextureStage("depth") # stage_depth.setSort(2) # tex_normal.setTexture(stage_depth, tex_depth.getTexture()) shader_ink = self.panda3d.loader.loadShader(sha_ink) #tex_normal.setShader(shader_ink) width = self.panda3d.win.getXSize() height = self.panda3d.win.getYSize() tex_normal.setShaderInput("screen", width, height) self.tex_normal = tex_normal
def renderObject(self,scale,hpr,collisionOn=False): (x_scale,y_scale,z_scale) = scale (h,p,r) = hpr if collisionOn is True: if self.name is 'wide_ramp': (x_c,y_c,z_c) = (x_scale + .2,y_scale+2.5,z_scale+1.75) if self.name is 'tree1': (x_c,y_c,z_c) = (x_scale,y_scale,z_scale) if self.name is 'tree2': (x_c,y_c,z_c) = (x_scale,y_scale,z_scale) if self.name is 'rock1': (x_c,y_c,z_c) = (x_scale * 2,y_scale * 2,z_scale*2) if self.name is 'rock2': (x_c,y_c,z_c) = (x_scale*100,y_scale*100,z_scale*100) if self.name is 'gate': (x_c,y_c,z_c) = (x_scale * 10,y_scale,z_scale*3.5) if self.name is 'statue': (x_c,y_c,z_c) = (x_scale,y_scale,z_scale) mesh = BulletTriangleMesh() for geomNP in self.model.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.model) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) node = BulletRigidBodyNode(self.name) node.setMass(0) node.addShape(shape) np = self.__game.render.attachNewNode(node) np.setPos(self.x,self.y,self.z) np.setHpr(h,p,r) np.setScale(x_c,y_c,z_c) self.__game.world.attachRigidBody(node) self.model.setPos(self.x,self.y,self.z) self.model.setHpr(h,p,r) self.model.setScale(x_scale,y_scale,z_scale) self.model.reparentTo(self.__game.render) if self.name is 'statue': plat_texture = loader.loadTexture('models/textures/rocky.jpg') self.model.setTexture(plat_texture,1) ts = TextureStage.getDefault() texture = self.model.getTexture() self.model.setTexScale(ts, 1, 1)
def loadIcon(self, iconsFile, name): retVal = iconsFile.find(name) retVal.setBillboardAxis() retVal.reparentTo(self) dark = retVal.copyTo(NodePath()) dark.reparentTo(retVal) dark.setColor(0.5, 0.5, 0.5, 1) retVal.setEffect(DecalEffect.make()) retVal.setTransparency(TransparencyAttrib.MAlpha, 1) ll, ur = dark.getTightBounds() center = retVal.attachNewNode('center') center.setPos(0, 0, ll[2]) dark.wrtReparentTo(center) dark.setTexProjector(TextureStage.getDefault(), center, retVal) retVal.hide() return (retVal, center)
def createSpritesNodeSetup(self): aspect_ratio = self.mainRef.render2d.getScale()[0] screenOrigin = self.mainRef.render2d.attachNewNode('screen_origin') screenNode = screenOrigin.attachNewNode('screen_node') screenOrigin.setPos(-1.0/aspect_ratio, 0.0, 1.0) screenOrigin.setScale(2.0, 1.0, -2.0) screenNode.setPos(0, 0, 0) screenNode.setScale(1.0/(aspect_ratio*self.winSizeX), 1.0, 1.0/self.winSizeY) screenNode.setTexScale(TextureStage.getDefault(), 1.0, -1.0) return screenNode
def render(self): LOG.debug("[SkyBox] Rendering") # If we are an orphan use render if self.parent is None: self.parent = render #LOG.debug("[SkyBox] model=%s"%self.modelFile) self.node = loader.loadModel(self.modelFile) #print("tf1 = %s, tf2 = %s"%(self.texture1File,self.texture2File)) if self.texture1File != '' and self.texture2File == '': #LOG.debug("[SkyBox] single texture = %s"%self.texture1File) t = loader.loadTexture(self.texture1File) self.node.setTexture(t) elif self.texture1File != '' and self.texture2File != '': #LOG.debug("[SkyBox] texture staging 1 = %s, 2 = %s"%(self.texture1File,self.texture2File)) t1 = loader.loadTexture(self.texture1File) t1.setWrapU(Texture.WMClamp) t1.setWrapV(Texture.WMClamp) ts1 = TextureStage('Space') ts1.setSort(self.texture1Sort) t2 = loader.loadTexture(self.texture2File) t2.setWrapU(Texture.WMClamp) t2.setWrapV(Texture.WMClamp) ts2 = TextureStage('SpaceClouds') ts2.setSort(self.texture2Sort) self.node.setTexture(ts1, t1) self.node.setTexture(ts2, t2) if self.shaderFile: LOG.debug("[SkyBox] shader = %s"%self.shaderFile) #skyShader = Shader.load("./data/shaders/%s"%self.shaderFile) skyShader = Shader.load("%s"%self.shaderFile) self.node.setShader(skyShader) # Should this be scaled here or done to the model? # It doesn't look like scaling the objects looks any different. self.node.setScale(280) # make sure it's drawn first (this can be done with shaders?) self.node.setBin('background', 0) # dont set depth attribute when rendering the sky (this can be done with shaders?) self.node.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff)) # We don't want shadows on the skybox self.node.setLightOff() # Render self.node.reparentTo(self.parent) taskMgr.add(self.moveSkyTask, "Move the sky box with the cam")
class ShipFactory: notify = DirectNotifyGlobal.directNotify.newCategory("ShipFactory") def __init__(self, phasedLoading=False): self.wantProws = config.GetBool("want-sprits", 0) self.hulls = {} self.texInfo = ({}, {}, {}) self.models = {} self.mastSets = {} ShipBlueprints.setupWheel() ShipBlueprints.setupShipTextures() self.preprocessMast(ShipGlobals.Masts.Main_Tri) self.preprocessMast(ShipGlobals.Masts.Fore_Tri) self.preprocessHull(ShipGlobals.INTERCEPTORL1) self.preprocessMast(ShipGlobals.Masts.Skel_Main_A) self.preprocessMast(ShipGlobals.Masts.Skel_Main_B) self.preprocessMast(ShipGlobals.Masts.Skel_Tri) self.preprocessMast(ShipGlobals.Masts.Skel_Fore) self.preprocessMast(ShipGlobals.Masts.Skel_Aft) self.preprocessHull(ShipGlobals.SKEL_INTERCEPTORL3) self.preprocessHull(ShipGlobals.SKEL_WARSHIPL3) if not phasedLoading: self.handlePhase4() self.handlePhase5() self.baseLayer = TextureStage("base") self.colorLayer = TextureStage("color") self.logoLayer = TextureStage("logo") self.logoLayerNoColor = TextureStage("logoNoColor") self.vertLayer = TextureStage("vertex") self.colorLayer.setSort(1) self.colorLayer.setCombineRgb(TextureStage.CMReplace, TextureStage.CSTexture, TextureStage.COSrcColor) self.colorLayer.setCombineAlpha(TextureStage.CMReplace, TextureStage.CSTexture, TextureStage.COSrcAlpha) self.colorLayer.setTexcoordName("uvColor") self.logoLayer.setSort(2) self.logoLayer.setCombineRgb( TextureStage.CMInterpolate, TextureStage.CSTexture, TextureStage.COSrcColor, TextureStage.CSPrevious, TextureStage.COSrcColor, TextureStage.CSTexture, TextureStage.COSrcAlpha, ) self.logoLayer.setCombineAlpha(TextureStage.CMReplace, TextureStage.CSPrevious, TextureStage.COSrcAlpha) self.logoLayer.setTexcoordName("uvLogo") self.logoLayerNoColor.setSort(2) self.logoLayerNoColor.setCombineRgb( TextureStage.CMInterpolate, TextureStage.CSTexture, TextureStage.COSrcColor, TextureStage.CSConstant, TextureStage.COSrcColor, TextureStage.CSTexture, TextureStage.COSrcAlpha, ) self.logoLayerNoColor.setCombineAlpha(TextureStage.CMReplace, TextureStage.CSPrevious, TextureStage.COSrcAlpha) self.logoLayerNoColor.setTexcoordName("uvLogo") self.logoLayerNoColor.setColor((1, 1, 1, 1)) self.vertLayer.setSort(3) self.vertLayer.setCombineRgb( TextureStage.CMModulate, TextureStage.CSPrevious, TextureStage.COSrcColor, TextureStage.CSPrimaryColor, TextureStage.COSrcColor, ) self.vertLayer.setCombineAlpha(TextureStage.CMReplace, TextureStage.CSPrimaryColor, TextureStage.COSrcAlpha) self.baseLayer.setSort(4) self.baseLayer.setCombineRgb( TextureStage.CMModulate, TextureStage.CSTexture, TextureStage.COSrcColor, TextureStage.CSPrevious, TextureStage.COSrcColor, ) self.baseLayer.setCombineAlpha( TextureStage.CMModulate, TextureStage.CSTexture, TextureStage.COSrcAlpha, TextureStage.CSPrevious, TextureStage.COSrcAlpha, ) def handlePhase4(self): self.preprocessHull(ShipGlobals.INTERCEPTORL2) self.preprocessHull(ShipGlobals.INTERCEPTORL3) self.preprocessMast(ShipGlobals.Masts.Main_Square) self.preprocessMast(ShipGlobals.Masts.Aft_Tri) self.preprocessMast(ShipGlobals.Masts.Fore_Multi) self.preprocessHull(ShipGlobals.WARSHIPL1) self.preprocessHull(ShipGlobals.WARSHIPL2) self.preprocessHull(ShipGlobals.WARSHIPL3) self.preprocessHull(ShipGlobals.MERCHANTL1) self.preprocessHull(ShipGlobals.MERCHANTL2) self.preprocessHull(ShipGlobals.MERCHANTL3) self.preprocessHull(ShipGlobals.QUEEN_ANNES_REVENGE) self.sprits = ShipBlueprints.preprocessSprits() def handlePhase5(self): self.preprocessHull(ShipGlobals.BLACK_PEARL) self.preprocessHull(ShipGlobals.GOLIATH) self.preprocessHull(ShipGlobals.SHIP_OF_THE_LINE) def preprocessMast(self, mastClass): self.mastSets[mastClass] = ShipBlueprints.generateMastCache(mastClass) def preprocessHull(self, modelClass): self.hulls[modelClass] = ShipBlueprints.generateHullCache(modelClass) def getHull(self, modelClass, custom): return self.hulls[modelClass].getHullAsset(custom) def getShip( self, shipClass, style=ShipGlobals.Styles.Undefined, logo=ShipGlobals.Logos.Undefined, hullDesign=None, detailLevel=2, wantWheel=True, hullMaterial=None, sailMaterial=None, sailPattern=None, prowType=None, ): Ship = Ship import pirates.ship modelClass = ShipGlobals.getModelClass(shipClass) shipConfig = ShipGlobals.getShipConfig(shipClass) if style == ShipGlobals.Styles.Undefined: style = shipConfig["defaultStyle"] complexCustomization = 0 if sailPattern and sailMaterial and hullMaterial or SailReplace.has_key(shipClass): complexCustomization = 1 if not prowType: prowType = shipConfig["prow"] if not hullMaterial: hullMaterial = style if not sailMaterial: if SailReplace.has_key(shipClass): sailMaterial = SailReplace[shipClass] else: sailMaterial = style if not sailPattern: sailPattern = style shipHullTexture = ShipBlueprints.getShipTexture(hullMaterial) shipTextureSail = ShipBlueprints.getShipTexture(sailMaterial) logoTex = None if logo: logoTex = ShipBlueprints.getLogoTexture(logo) sailPatternTex = None if sailPattern: sailPatternTex = ShipBlueprints.getSailTexture(sailPattern) self.notify.debug("%s %s" % (sailPattern, logo)) if logo == ShipGlobals.Logos.Undefined: logo = shipConfig["sailLogo"] if logo in ShipGlobals.MAST_LOGO_PLACEMENT_LIST: placeLogos = 1 else: placeLogos = 0 if modelClass <= ShipGlobals.INTERCEPTORL3: mastHax = True else: mastHax = False customHull = hullDesign is not None if not logo != 0: pass customMasts = sailPattern != 0 hull = self.getHull(modelClass, customHull) breakAnims = {} metaAnims = {} hitAnims = {} root = NodePath("Ship") hull.locators.reparentTo(root) charRoot = root.attachNewNode(Character("ShipChar")) collisions = root.attachNewNode("collisions") lodNode = charRoot.attachNewNode(LODNode("lod")) if detailLevel == 0: lodNode.node().addSwitch(200, 0) lodNode.node().addSwitch(800, 200) lodNode.node().addSwitch(100000, 800) high = lodNode.attachNewNode("high") low = lodNode.attachNewNode("low") med = NodePath("med") superlow = lodNode.attachNewNode("superlow") elif detailLevel == 1: lodNode.node().addSwitch(300, 0) lodNode.node().addSwitch(1000, 300) lodNode.node().addSwitch(2000, 1000) lodNode.node().addSwitch(100000, 2000) high = lodNode.attachNewNode("high") med = lodNode.attachNewNode("med") low = lodNode.attachNewNode("low") superlow = lodNode.attachNewNode("superlow") else: lodNode.node().addSwitch(750, 0) lodNode.node().addSwitch(3000, 750) lodNode.node().addSwitch(8000, 3000) lodNode.node().addSwitch(100000, 8000) high = lodNode.attachNewNode("high") med = lodNode.attachNewNode("med") low = lodNode.attachNewNode("low") superlow = lodNode.attachNewNode("superlow") mastSetup = ShipGlobals.getMastSetup(shipClass) for data in [ (0, "location_mainmast_0"), (1, "location_mainmast_1"), (2, "location_mainmast_2"), (3, "location_aftmast*"), (4, "location_foremast*"), ]: mastData = mastSetup.get(data[0]) if mastData: mast = self.mastSets[mastData[0]].getMastSet(mastData[1] - 1, customMasts) mastRoot = hull.locators.find("**/%s" % data[1]).getTransform(hull.locators) model = NodePath(mast.charRoot) model.setTransform(mastRoot) if complexCustomization: model.setTexture(shipTextureSail) useLogoTex = logoTex if placeLogos: mastNum = data[0] if mastNum not in ShipGlobals.MAST_LOGO_PLACEMENT.get(modelClass): useLogoTex = None charBundle = mast.charRoot.getBundle(0) if data[0] < 3: for side in ["left", "right"]: ropeNode = hull.locators.find("**/location_ropeLadder_%s_%s" % (side, data[0])) if ropeNode: transform = ropeNode.getTransform(NodePath(mast.charRoot)) charBundle.findChild("def_ladder_0_%s" % side).applyFreeze(transform) continue if sailPatternTex and useLogoTex: for node in model.findAllMatches("**/sails"): node.setTextureOff(TextureStage.getDefault()) node.setTexture(self.colorLayer, sailPatternTex) node.setTexture(self.logoLayer, logoTex) node.setTexture(self.vertLayer, shipTextureSail) node.setTexture(self.baseLayer, shipTextureSail) elif sailPatternTex: for node in model.findAllMatches("**/sails"): node.setTextureOff(TextureStage.getDefault()) node.setTexture(self.colorLayer, sailPatternTex) node.setTexture(self.vertLayer, shipTextureSail) node.setTexture(self.baseLayer, shipTextureSail) elif useLogoTex: for node in model.findAllMatches("**/sails"): node.setTextureOff(TextureStage.getDefault()) node.setTexture(self.logoLayerNoColor, logoTex) node.setTexture(self.vertLayer, shipTextureSail) node.setTexture(self.baseLayer, shipTextureSail) model.flattenLight() if detailLevel == 0: model.find("**/low").copyTo(high) model.find("**/low").copyTo(low) model.find("**/superlow").copyTo(superlow) elif detailLevel == 1: model.find("**/med").copyTo(high) model.find("**/med").copyTo(med) low.node().stealChildren(model.find("**/low").node()) superlow.node().stealChildren(model.find("**/superlow").node()) elif detailLevel == 2: high.node().stealChildren(model.find("**/high").node()) med.node().stealChildren(model.find("**/med").node()) low.node().stealChildren(model.find("**/low").node()) superlow.node().stealChildren(model.find("**/superlow").node()) mastRoot = mast.collisions.find("**/collision_masts") if modelClass > ShipGlobals.INTERCEPTORL3 or data[0] != 3: mastCode = str(data[0]) mastRoot.setTag("Mast Code", mastCode) else: mastRoot.setName("colldision_sub_mast") mastRoot.reparentTo(collisions.find("**/collision_masts")) mastCode = "0" for coll in mast.collisions.findAllMatches("**/collision_sail_*"): coll.setName("Sail-%s" % data[0]) coll.setTag("Mast Code", mastCode) for coll in mast.collisions.findAllMatches("**/sail_*"): coll.setName("Sail-%s" % data[0]) coll.setTag("Mast Code", mastCode) collisions.node().stealChildren(mast.collisions.node()) charBundle = mast.charRoot.getBundle(0) if mastHax and data[0] == 3: breakAnims[0][0].storeAnim( charBundle.loadBindAnim(loader.loader, mast.breakAnim[0], -1, MastSubset, True), "1" ) breakAnims[0][1].storeAnim( charBundle.loadBindAnim(loader.loader, mast.breakAnim[1], -1, MastSubset, True), "1" ) tempHit = hitAnims[0] tempHit[0].storeAnim( charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, HitMastSubset, True), "1" ) tempHit[1].storeAnim( charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, PartSubset(), True), "1" ) else: breakAnims[data[0]] = (AnimControlCollection(), AnimControlCollection()) breakAnims[data[0]][0].storeAnim( charBundle.loadBindAnim(loader.loader, mast.breakAnim[0], -1, MastSubset, True), "0" ) breakAnims[data[0]][1].storeAnim( charBundle.loadBindAnim(loader.loader, mast.breakAnim[1], -1, MastSubset, True), "0" ) tempHit = [AnimControlCollection(), AnimControlCollection()] tempHit[0].storeAnim( charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, HitMastSubset, True), "0" ) tempHit[1].storeAnim( charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, PartSubset(), True), "0" ) hitAnims[data[0]] = tempHit for (anim, fileName) in mast.metaAnims.iteritems(): if anim not in metaAnims: metaAnims[anim] = AnimControlCollection() if anim not in MissingAnims.get(modelClass, []): ac = charBundle.loadBindAnim(loader.loader, fileName, -1, SailSubset, True) if ac: metaAnims[anim].storeAnim(ac, str(metaAnims[anim].getNumAnims())) charRoot.node().combineWith(mast.charRoot) continue if self.wantProws and prowType: (highSprit, medSprit, lowSprit) = self.sprits[prowType].getAsset() transform = hull.locators.find("**/location_bowsprit").getTransform(hull.locators) highSprit.setTransform(transform) medSprit.setTransform(transform) lowSprit.setTransform(transform) highSprit.reparentTo(hull.geoms[0]) medSprit.reparentTo(hull.geoms[1]) lowSprit.reparentTo(hull.geoms[2]) if wantWheel: shipWheel = ShipBlueprints.getWheel() wheelPoint = hull.locators.find("**/location_wheel;+s").getTransform(hull.locators) shipWheel.setTransform(wheelPoint) shipWheel.flattenLight() shipWheel.find("**/collisions").copyTo(collisions) hull.geoms[0].node().stealChildren(shipWheel.find("**/high").node()) hull.geoms[1].node().stealChildren(shipWheel.find("**/med").node()) hull.geoms[2].node().stealChildren(shipWheel.find("**/low").node()) if complexCustomization: hull.geoms[0].setTexture(shipHullTexture) hull.geoms[0].flattenLight() hull.geoms[1].setTexture(shipHullTexture) hull.geoms[1].flattenLight() hull.geoms[2].setTexture(shipHullTexture) hull.geoms[2].flattenLight() hull.geoms[3].setTexture(shipHullTexture) hull.geoms[3].flattenLight() high.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[0].node()) med.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[1].node()) low.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[2].node()) superlow.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[3].node()) collisions.node().stealChildren(hull.collisions.node()) hull.locators.stash() charRoot.flattenStrong() ship = Ship.Ship(shipClass, root, breakAnims, hitAnims, metaAnims, collisions, hull.locators) if not complexCustomization: ship.char.setTexture(shipHullTexture) return ship def getAIShip(self, shipClass): ShipAI = ShipAI import pirates.ship modelClass = ShipGlobals.getModelClass(shipClass) hull = self.getHull(modelClass, 0) root = NodePath("Ship") collisions = root.attachNewNode("collisions") mastSetup = ShipGlobals.getMastSetup(shipClass) for data in [ (0, "location_mainmast_0"), (1, "location_mainmast_1"), (2, "location_mainmast_2"), (3, "location_aftmast*"), (4, "location_foremast*"), ]: mastData = mastSetup.get(data[0]) if mastData: mast = self.mastSets[mastData[0]].getMastSet(mastData[1] - 1) model = NodePath(mast.charRoot) model.setPos(hull.locators.find("**/%s" % data[1]).getPos(hull.locators)) model.setHpr(hull.locators.find("**/%s" % data[1]).getHpr(hull.locators)) model.setScale(hull.locators.find("**/%s" % data[1]).getScale(hull.locators)) if modelClass > ShipGlobals.INTERCEPTORL3 or data[0] != 3: mastCode = str(data[0]) else: mastCode = "0" mast.collisions.find("**/collision_masts").setTag("Mast Code", mastCode) collisions.node().stealChildren(mast.collisions.node()) continue collisions.node().stealChildren(hull.collisions.node()) hull.locators.reparentTo(root) ship = ShipAI.ShipAI(root, collisions, hull.locators) ship.modelRoot.setTag("Mast Code", str(255)) ship.modelRoot.setTag("Hull Code", str(255)) return ship