本文整理汇总了Python中direct.filter.CommonFilters.CommonFilters.setBloom方法的典型用法代码示例。如果您正苦于以下问题:Python CommonFilters.setBloom方法的具体用法?Python CommonFilters.setBloom怎么用?Python CommonFilters.setBloom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类direct.filter.CommonFilters.CommonFilters
的用法示例。
在下文中一共展示了CommonFilters.setBloom方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MyApp
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# Turn Auto Shaders and Antialiasing
self.render.setShaderAuto()
self.render.setAntialias(AntialiasAttrib.MAuto)
# Setup Bloom and Blur Filters
self.filters = CommonFilters(base.win, base.cam)
self.filters.setBloom(blend=(1,0,0,1), desat=-0.5, intensity=6.0, size=2)
#self.filters.setBlurSharpen(amount=0.5)
# Create Ambient Lighting
alight = AmbientLight('alight')
alight.setColor(VBase4(1, 1, 1, 1))
alnp = render.attachNewNode(alight)
self.render.setLight(alnp)
# Load Model and Add it to Scene
self.environ = self.loader.loadModel("untitled.egg")
self.environ.reparentTo(self.render)
self.environ.setTransparency(TransparencyAttrib.MAlpha)
示例2: BurdenOfProof
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class BurdenOfProof(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.useAdvancedVisualEffects = ConfigVariableBool(
"use-advanced-visual-effects", True)
self.game = Game()
self.setupFilters()
self.setupModels()
self.setupKeyboardControl()
self.motionController = MotionController(self)
self.camera.setPos(0.0, 0.0, 1.7)
def setupKeyboardControl(self):
self.accept("escape", sys.exit)
def setupFilters(self):
if (self.useAdvancedVisualEffects):
self.filters = CommonFilters(self.win, self.cam)
self.filters.setBloom()
def setupModels(self):
self.cityModel = self.loader.loadModel("data/models/city")
self.cityModel.reparentTo(self.render)
self.cityModel.setP(-90.0)
self.pandaActor = Actor("models/panda-model",
{"walk": "models/panda-walk4"})
self.pandaActor.setScale(0.005, 0.005, 0.005)
self.pandaActor.loop("walk")
population = self.game.getPopulation()
self.characterInstances = []
for i in range(1, population.getCharacterCount()):
instance = self.render.attachNewNode("characterInstance")
instance.setPos(
population.getCharacter(i).getPosition(self.game.getTime()))
self.pandaActor.instanceTo(instance)
self.characterInstances.append(instance)
self.taskMgr.add(self.update, "updateTask")
def update(self, task):
self.game.update(oneMinute) # TODO(?) compute actual milliseconds
population = self.game.getPopulation()
for i in range(1, population.getCharacterCount()):
self.characterInstances[i - 1].setPos(
population.getCharacter(i).getPosition(self.game.getTime()))
return Task.cont
示例3: _loadFilters
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
def _loadFilters(self):
self.terrain.setShaderInput('waterlevel', self._water_level)
# load default shaders
cf = CommonFilters(base.win, base.cam)
# bloomSize
cf.setBloom(size='small', desat=0.7, intensity=1.5, mintrigger=0.6, maxtrigger=0.95)
# hdrtype:
render.setAttrib(LightRampAttrib.makeHdr1())
# perpixel:
render.setShaderAuto()
示例4: postProcessingChanged
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
def postProcessingChanged():
global filters
if enablePostProcessing:
if filters == None:
filters = CommonFilters(base.win, base.cam)
render.setAttrib(LightRampAttrib.makeHdr1())
filters.setBloom(intensity = 1, size = 2)
else:
if filters != None:
filters.delBloom()
saveConfigFile()
示例5: __init__
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class Filters:
"""Class handles postprocessing filters and effects"""
def __init__(self,manager,xml):
self.cf = CommonFilters(base.win,base.cam)
self.reload(manager,xml)
def reload(self,manager,xml):
hdr = xml.find('hdr')
if hdr!=None:
self.hdrtype = hdr.get('type')
assert self.hdrtype in ['0', '1', '2']
else:
self.hdrtype = None
self.perpixel = xml.find('perpixel')!=None
bloom = xml.find('bloom')
if bloom!=None:
self.bloomSize = bloom.get('size', 'medium')
else:
self.bloomSize = None
self.showbuffers = xml.find('showbuffers')!=None
def start(self):
if self.hdrtype!=None:
render.setAttrib(getattr(LightRampAttrib, "makeHdr" + self.hdrtype)())
if self.perpixel:
render.setShaderAuto()
if self.bloomSize!=None:
self.cf.setBloom(size=self.bloomSize)
if self.showbuffers:
base.bufferViewer.toggleEnable()
def stop(self):
if self.hdrtype!=None:
render.clearAttrib(LightRampAttrib.getClassType())
if self.perpixel:
render.setShaderOff()
if self.bloomSize!=None:
self.cf.delBloom()
if self.showbuffers:
base.bufferViewer.toggleEnable()
示例6: Filters
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class Filters():
def __init__(self):
self.filters = CommonFilters(base.win, base.cam)
self.glowShader = loader.loadShader("./shaders/glowShader.sha")
def enableFilters(self, player):
#self.filters.setBloom(mintrigger=.35)
self.filters.setBloom(blend=(1, 0, .2, 1), desat=-1, intensity=10, size="small")
#self.filters.setCartoonInk(separation=-5)
self.filters.setAmbientOcclusion(numsamples = 2, radius = 0.0025, amount = 2, strength = 0.001, falloff = 0.01)
player.setShader(self.glowShader)
player.setShaderInput("scale",4,4)
path = render.find("renderDummy")
path.setShader(self.glowShader)
path.setShaderInput("scale",1,1,1)
示例7: __init__
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
def __init__(self, app_object):
self.app = app_object
self.n = 0
cmnd = ""
self.commandBox = ""
self.store = ["","","",""]
ShowBase.__init__(self)
self.title1 = self.AddTitle(-0.65, "Type your commands here:")
self.title2 = self.AddTitle(0.90, "You have entered:")
self.instArea = self.AddInstructions(0.82, cmnd)
self.cmndArea = self.AddArea()
base.setFrameRateMeter(True)
base.setBackgroundColor(0,0,0)
self.cube = loader.loadModel("models/cube")
self.cube.setPos(0, 0, 0)
self.cube.reparentTo(self.render)
self.cube.setScale((cx), 3, 1)
# cam
self.cam.setPos(60, -80, 22)
light = PointLight('light')
self.render.setLight(self.cam.attachNewNode(light))
self.cam.lookAt(self.cube)
self.i = 1
self.sy = 1
self.sx = 1
self.sz = 1
self.addx =1
self.addy =1
self.addz =1
#self.negy = -7
#self.posy = 7
#CENTER
#setting up the bloom effect
filters = CommonFilters(base.win, base.cam)
filters.setBloom(blend=(0.0,0.0,0.0,1.0), mintrigger = 0.9, desat=-0.5, intensity=8.0, size="small")
rootDir = os.path.abspath(os.path.dirname(sys.argv[0]))
loadPrcFile(os.path.join(rootDir, "config.prc"))
示例8: __init__
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class World:
def __init__(self):
base.disableMouse()
base.setBackgroundColor(0.52, 0.80, 0.99)
self.inputManager = InputManager()
self.filters = CommonFilters(base.win, base.cam)
filterok = self.filters.setBloom(blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0, size=2)
render.setShaderAuto()
self.menuGraphics = loader.loadModel("Models/MenuGraphics.egg")
self.fonts = {
"silver": loader.loadFont("Fonts/LuconSilver.egg"),
"blue": loader.loadFont("Fonts/LuconBlue.egg"),
"orange": loader.loadFont("Fonts/LuconOrange.egg")
}
gui = Gui(self.fonts)
self.race = Race(self.inputManager, gui)
self.race.createDemoRace()
self.createStartMenu()
musicMgr = base.musicManager
self.music = musicMgr.getSound("Sound/music_1.wav")
self.music.setLoop(True)
self.music.setVolume(.5)
self.music.play()
def createStartMenu(self):
menu = Menu(self.menuGraphics, self.fonts, self.inputManager)
menu.initMenu([0, None, ["New Game", "Quit Game"], [[self.race.createRace, self.createReadyDialogue], [base.userExit]], [[None, None], [None]]])
def createReadyDialogue(self):
menu = Menu(self.menuGraphics, self.fonts, self.inputManager)
menu.initMenu([3, "Ready?", ["Yes", "Exit"], [[self.race.startRace], [self.race.createDemoRace]], [[3], [None]]])
def debugTask(self, task):
print(taskMgr)
return task.again
示例9: Arena
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class Arena(DirectObject):
collshow = False
def initShader(self):
tempnode = NodePath(PandaNode("temp node"))
tempnode.setAttrib(LightRampAttrib.makeSingleThreshold(0.5, 0.9))
tempnode.setShaderAuto()
base.cam.node().setInitialState(tempnode.getState())
self.separation = 1 # Pixels
self.filters = CommonFilters(base.win, base.cam)
filterok = self.filters.setBloom()
if (filterok == False):
addTitle("Toon Shader: Video card not powerful enough to do image postprocessing")
sys.exit
def initCollision(self):
base.cTrav = CollisionTraverser()
base.collisionHandlerEvent = CollisionHandlerEvent()
base.collisionHandlerEvent.addInPattern('%fn-i-%in')
base.collisionHandlerEvent.addOutPattern('%fn-o-%in')
base.collisionHandlerEvent.addAgainPattern('%fn-a-%in')
self.accept('mouseray-a-ground',self.collideGroundAgain)
self.lastX = 0
self.lastDirection = 0
def collideGroundAgain(self,entry):
np_into=entry.getIntoNodePath()
pos = entry.getSurfacePoint(np_into)
pos.setZ(1)
x = pos.getX()
if(x == self.lastX):
return
if(x < self.lastX):
direction = -1
else:
direction = 1
if(direction != self.lastDirection):
if(direction == -1):
self.sonic.left()
self.tails.left()
else:
self.sonic.right()
self.tails.right()
self.lastDirection = direction
self.lastX = x
if (x < -7 ) : pos.setX(-7)
if (x > 7 ) : pos.setX(7)
pos.setY(-7)
self.sonic.collisionNodePath.setPos(pos)
pos.setY(-5)
self.tails.collisionNodePath.setPos(pos)
# self.pandaActor.setPos(pos)
def updateMouseTask(self, task):
if base.mouseWatcherNode.hasMouse():
mpos=base.mouseWatcherNode.getMouse()
self.mouse.collisionRay.setFromLens(base.camNode, mpos.getX(),mpos.getY())
return task.cont
def mouseClick(self):
messenger.send("Spider")
print 'click'
def toggle_collisions(self):
self.collshow = not self.collshow
if self.collshow:
self.collisionTraverser.showCollisions(base.render)
l=base.render.findAllMatches("**/+CollisionNode")
for cn in l: cn.show()
else:
self.collisionTraverser.hideCollisions()
l=base.render.findAllMatches("**/+CollisionNode")
for cn in l: cn.hide()
def toggle_wire(self):
base.toggleWireframe()
base.toggleTexture()
def __init__(self):
base.audio = Audio()
base.audio.play('complex')
self.initShader()
self.initCollision()
self.camera = Camera()
self.mouse = Mouse()
self.ground = Ground()
self.smiley = Smiley()
self.frowney = Frowney()
self.gorrila = Gorrila()
self.sonic = Sonic()
self.tails = Tails()
self.monster = Monster()
base.arrow = Arrow()
self.dragon = Dragon()
self.panda = Panda()
self.pandaren = Pandaren()
self.tombstone = Tombstone()
self.tombstone.spiders = []
for i in range(50):
self.tombstone.spiders.append(Spider(str(i)))
self.tombstone.batch()
#.........这里部分代码省略.........
示例10: Engine
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class Engine(ShowBase):
def __init__(self, mouse):
ShowBase.__init__(self)
self.mouse = mouse
self.joy_x = None
self.joy_y = None
props = WindowProperties()
props.setMouseMode(WindowProperties.MRelative) # keep mouse in screen
self.disableMouse()
self.win.requestProperties(props)
self.setBackgroundColor(0, 0, 0)
# Make missiles glow
self.filters = CommonFilters(self.win, self.cam)
self.filters.setBloom(blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0, size="large")
self.screen_width = self.win.getXSize()
self.screen_height = self.win.getYSize()
self.center_x = self.screen_width/2
self.center_y = self.screen_height/2
# self.win.movePointer(0, self.center_x, self.center_y)
self.enableParticles()
self.cTrav = CollisionTraverser()
# self.cTrav.setRespectPrevTransform(True)
self.pusher = PhysicsCollisionHandler()
self.pusher.addInPattern('%fn-into-%in')
self.target = None
self.maxvel = 50
self.roll_time = 0
self.fuel = 1000
self.ship()
self.sounds()
self.hud()
self.part = Spacedust(self)
self.events()
self.camLens.setFov(70)
self.camLens.setNear(1)
self.camLens.setFar(500)
self.get_key = {
"ACCEL": False,
"DECEL": False,
"FORWARD_THRUST": False,
"REVERSE_THRUST": False,
"ROLL_LEFT": False,
"ROLL_RIGHT": False,
"ROLL_LEFT_BEG": False,
"ROLL_RIGHT_BEG": False,
"FIRE": False,
"FIRING": False,
"LOCK": False,
"LOCKING": False,
}
self.AIworld = AIWorld(self.render)
self.taskMgr.add(self.update, "task-update")
self.taskMgr.doMethodLater(1, self.fuel_usage, "task-fuel-usage")
self.taskMgr.add(self.AI_update, "AI-update")
self.gen_enemy()
def gen_enemy(self):
x = randint(-1000, 1000)
y = randint(-1000, 1000)
z = randint(-1000, 1000)
Enemy(self, 0, x, y, z)
def AI_update(self, task):
self.AIworld.update()
return task.cont
def hud(self):
self.font = self.loader.loadFont("./fnt/subatomic.tsoonami.ttf")
self.aim = OnscreenImage(image="./png/ring.png", pos=Vec3(0), scale=0.02)
self.aim.setTransparency(TransparencyAttrib.MAlpha)
self.locker = OnscreenImage(image="./png/ring.png", pos=Vec3(0), scale=0.12)
self.locker.setTransparency(TransparencyAttrib.MAlpha)
self.locker.hide()
self.txtFuel = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.8), text='FUEL', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
self.txtSpeed = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.7), text='SPEED', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
self.txtDist = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.6), text='DIST', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
self.txtCoord = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.5), text='COORD', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
self.taskMgr.doMethodLater(1, self.instruments, "task-instruments")
def instruments(self, task):
self.txtSpeed.setText("SPEED: %s" % str(int(self.mvel)))
self.txtFuel.setText("FUEL: %s" % str(self.fuel))
if self.target is not None:
self.txtDist.setText("DISTANCE: %s" % str(round(self.dist, 1)))
else:
self.txtDist.setText("DISTANCE: ---")
self.txtCoord.setText("COORD: %s %s %s" % (str(round(self.fighter.getX(), 1)), str(round(self.fighter.getY(), 1)), str(round(self.fighter.getZ(), 1))))
return task.again
def set_key(self, key, value):
self.get_key[key] = value
def toggle_key(self, key):
self.set_key(key, not self.get_key[key])
def init_roll(self, a, task):
if task.time <= 2:
if self.roll_time <= task.time:
#.........这里部分代码省略.........
示例11: Engine
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class Engine(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.disableMouse()
props = WindowProperties()
props.setTitle('Test')
self.win.requestProperties(props)
# self.render.setAntiAlias(AntialiasAttrib.MAuto)
self.transitions = Transitions(self.loader)
self.transitions.setFadeColor(0, 0, 0)
self.filters = CommonFilters(self.win, self.cam)
# self.filters.setCartoonInk()
self.filters.setBlurSharpen(1)
# self.filters.setVolumetricLighting(self.render)
# self.buffer = self.win.makeTextureBuffer("Post-processing buffer", self.win.getXSize(), self.win.getXSize())
# print self.buffer.getYSize()
# self.texture = self.buffer.getTexture()
# self.buffer.setSort(-100)
#
# self.originalCamera = self.camera
# self.offScreenCamera = self.makeCamera(self.buffer)
# self.camera = self.offScreenCamera
#
# self.img = OnscreenImage(image=self.texture, pos=(0, 0, 0.5))
self.scene = None
self.channel = Channel()
def set_scene(self, scene_module):
# self.transitions.fadeOut(0.2)
args = []
if self.scene:
args.append(Parallel(Func(self.fade_out), LerpFunc(self.blur_out, duration=0.2)))
args.append(Wait(0.2))
args.append(Func(self._set_scene, scene_module))
args.append(Parallel(Func(self.fade_in), LerpFunc(self.blur_in, duration=0.4)))
Sequence(*args).start()
def blur_out(self, t):
# index = int(t)
# self.filters.delBlurSharpen()
self.filters.setBlurSharpen(1 - t)
self.filters.setBloom(intensity=t)
def blur_in(self, t):
# index = int(t)
# self.filters.delBlurSharpen()
self.filters.setBlurSharpen(t)
self.filters.setBloom(intensity=-t)
def fade_out(self):
self.transitions.fadeOut(0.2)
def fade_in(self):
self.transitions.fadeIn(0.2)
def _set_scene(self, scene_module):
group, class_ = scene_module.split('.')
module = importlib.import_module('game.scenes.{}'.format(group))
scene_class = getattr(module, class_)
if self.scene:
self.scene.destroy()
del self.scene
self.scene = scene_class(self)
# self.transitions.fadeIn(0.2)
def start(self):
self.channel = Channel()
self.channel.connect()
self.set_scene('auth.AuthScene')
while True:
self.taskMgr.step()
if self.channel.can_read():
for packet in self.channel.read_packets():
self.scene.on_packet(packet)
示例12: GlowDemo
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class GlowDemo(ShowBase):
def __init__(self):
# Initialize the ShowBase class from which we inherit, which will
# create a window and set up everything we need for rendering into it.
ShowBase.__init__(self)
base.disableMouse()
base.setBackgroundColor(0, 0, 0)
camera.setPos(0, -50, 0)
# Check video card capabilities.
if not base.win.getGsg().getSupportsBasicShaders():
addTitle(
"Glow Filter: Video driver reports that Cg shaders are not supported.")
return
# Use class 'CommonFilters' to enable a bloom filter.
# The brightness of a pixel is measured using a weighted average
# of R,G,B,A. We put all the weight on Alpha, meaning that for
# us, the framebuffer's alpha channel alpha controls bloom.
self.filters = CommonFilters(base.win, base.cam)
filterok = self.filters.setBloom(
blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0, size="small")
if (filterok == False):
addTitle(
"Toon Shader: Video card not powerful enough to do image postprocessing")
return
self.glowSize = 1
# Post the instructions
self.title = addTitle("Panda3D: Tutorial - Glow Filter")
self.inst1 = addInstructions(0.06, "ESC: Quit")
self.inst2 = addInstructions(0.12, "Space: Toggle Glow Filter Small/Med/Large/Off")
self.inst3 = addInstructions(0.18, "Enter: Toggle Running/Spinning")
self.inst4 = addInstructions(0.24, "V: View the render-to-texture results")
# load our model
self.tron = Actor()
self.tron.loadModel("models/tron")
self.tron.loadAnims({"running": "models/tron_anim"})
self.tron.reparentTo(render)
self.interval = self.tron.hprInterval(60, LPoint3(360, 0, 0))
self.interval.loop()
self.isRunning = False
# put some lighting on the model
dlight = DirectionalLight('dlight')
alight = AmbientLight('alight')
dlnp = render.attachNewNode(dlight)
alnp = render.attachNewNode(alight)
dlight.setColor((1.0, 0.7, 0.2, 1))
alight.setColor((0.2, 0.2, 0.2, 1))
dlnp.setHpr(0, -60, 0)
render.setLight(dlnp)
render.setLight(alnp)
# Panda contains a built-in viewer that lets you view the results of
# your render-to-texture operations. This code configures the viewer.
self.accept("v", base.bufferViewer.toggleEnable)
self.accept("V", base.bufferViewer.toggleEnable)
base.bufferViewer.setPosition("llcorner")
base.bufferViewer.setLayout("hline")
# base.camLens.setFov(100)
# event handling
self.accept("space", self.toggleGlow)
self.accept("enter", self.toggleDisplay)
self.accept("escape", sys.exit, [0])
def toggleGlow(self):
self.glowSize = self.glowSize + 1
if self.glowSize == 4:
self.glowSize = 0
self.filters.setBloom(blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0,
size=self.glowSize)
def toggleDisplay(self):
self.isRunning = not self.isRunning
if not self.isRunning:
camera.setPos(0, -50, 0)
self.tron.stop("running")
self.tron.pose("running", 0)
self.interval.loop()
else:
camera.setPos(0, -170, 3)
self.interval.finish()
self.tron.setHpr(0, 0, 0)
self.tron.loop("running")
示例13: Universe
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
#.........这里部分代码省略.........
#mouse keys
#mouse1 is left click
#Call function to set the player's target
#set_target_on_mouseclick also sets the mouse1 key value...need to make
# this more extensible
self.accept("mouse1", self.set_target_on_mouseclick)
self.accept("mouse1-up", self.controls_set_key, ["mouse1", 0])
#mouse3 is right click
self.accept("mouse3", self.controls_set_key, ["mouse3", 1])
self.accept("mouse3-up", self.controls_set_key, ["mouse3", 0])
#mouse2 is scroll wheel click
self.accept("mouse2", self.controls_set_key, ["mouse2", 1])
self.accept("mouse2-up", self.controls_set_key, ["mouse2", 0])
#mouse scroll
self.accept('wheel_up', self.controls_set_key,["scroll_up", 1 ])
self.accept('wheel_down', self.controls_set_key, ["scroll_down", 1])
self.accept ('escape', sys.exit) # hit escape to quit!
def controls_set_key(self, key, value):
"""Set up keyboard keys
Create a key_map dictionary to store the key being pressed and the
value (which will be either 1 for on or 0 for off)
"""
self.controls['key_map'][key] = value
"""=======Lights==============================================="""
def init_lights(self):
"""init_lights
Set up light system
"""
self.filters = CommonFilters(base.win, base.cam)
filterok = self.filters.setBloom(blend=(0,0,0,.5), desat=-0.5,
intensity=1.0, size="small")
if filterok == False:
print "Your video card cannot handle this"
return
self.glowSize=.2
# Create a simple directional light
self.lights = {}
#Set up directional light
self.lights['dlight'] = render.attachNewNode (DirectionalLight\
('DirectionalLight'))
self.lights['dlight'].setColor(VBase4(1, 1, 1, 1))
render.setLight(self.lights['dlight'])
self.lights['dlight'].setPos(50,50,50)
self.lights['dlight'].lookAt(0,0,0)
#Sun position
self.lights['sunPos'] = 0
# Create an ambient light
self.lights['alight'] = AmbientLight('AmbientLight')
self.lights['alight'].setColor(VBase4(0.1, 0.1, 0.1, 0.1))
self.lights['alnp'] = render.attachNewNode(self.lights['alight'])
render.setLight(self.lights['alnp'])
#Create an invisible "sun" node which the dlight will lookAt()
self.lights['sun_node'] = render.attachNewNode("sun_node")
self.lights['sun_node'].setPos(10,10,10)
self.lights['sun_node'].setScale(2)
#Create a sun model that will be a visual representation of where the
示例14: Application
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
class Application(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.useAdvancedVisualEffects =\
ConfigVariableBool("use-advanced-visual-effects", True) and\
base.win.getGsg().getSupportsBasicShaders() and\
base.win.getGsg().getSupportsGlsl() and\
base.win.getGsg().getSupportsDepthTexture()
self.game = Game(scriptPath)
self.phoneState = PhoneState(self)
self.setupFilters()
self.setupModels()
self.setupLighting()
self.setupKeyboardControl()
self.camera.setPos(0.0, 0.0, 1.7)
self.setupMouseControl()
self.phoneState.request("Hidden")
blockSize = 10.0
self.maxX = self.game.getCityBlueprint().getSizeWE() * blockSize / 2.0
self.maxY = self.game.getCityBlueprint().getSizeNS() * blockSize / 2.0
self.setBackgroundColor(0.2, 0.4, 1.0, 1.0)
def setupFilters(self):
if (self.useAdvancedVisualEffects):
self.filters = CommonFilters(self.win, self.cam)
self.filters.setBloom()
def setupKeyboardControl(self):
self.accept("escape", sys.exit)
def setupMouseControl(self):
self.disableMouse()
self.mousex = 0
self.mousey = 0
self.last = 0
self.mousebtn = [0,0,0]
self.accept("mouse1", self.setMouseBtn, [0, 1])
self.accept("mouse1-up", self.setMouseBtn, [0, 0])
self.taskMgr.add(self.controlCamera, "cameraTask")
def setupLights(self):
self.sunLight = self.render.attachNewNode(DirectionalLight("sunLight"))
self.sunLight.setColor(Vec4(0.8, 0.8, 0.8, 1))
self.sunLight.node().getLens().setFilmSize(128, 64)
self.sunLight.node().getLens().setNearFar(20,2000)
self.sunLight.setPos(60, 30, 50)
self.sunLight.lookAt(0, 0, 0)
self.render.setLight(self.sunLight)
# self.sunLight.node().showFrustum()
if self.useAdvancedVisualEffects:
self.sunLight.node().setShadowCaster(True, 256, 256)
self.render.setShaderAuto()
self.ambientLight = self.render.attachNewNode(AmbientLight("ambientLight"))
self.ambientLight.node().setColor(Vec4(0.2, 0.2, 0.2, 1))
self.render.setLight(self.ambientLight)
def setupModels(self):
self.city = self.loader.loadModel("models/city")
self.city.reparentTo(self.render)
self.phoneState.setupPhone()
self.cityOutline = self.loader.loadModel("models/city_outline")
self.cityOutline.reparentTo(self.phoneState.minimap)
def setupLighting(self):
self.ambientLight = self.render.attachNewNode(AmbientLight("ambientLight"))
self.ambientLight.node().setColor(Vec4(1, 1, 1, 1))
self.render.setLight(self.ambientLight)
def setMouseBtn(self, btn, value):
self.mousebtn[btn] = value
if (btn == 0 and value == 1 and self.phoneState.state == "Center"):
phoneDisplayRegionCenterX = self.win.getXSize() * (self.phoneState.phoneDisplayRegion.getLeft() + self.phoneState.phoneDisplayRegion.getRight()) / 2.0
phoneDisplayRegionCenterY = self.win.getYSize() * (1.0 - (self.phoneState.phoneDisplayRegion.getBottom() + self.phoneState.phoneDisplayRegion.getTop()) / 2.0)
mouse = self.win.getPointer(0)
s = 2 ** self.phoneState.minimapZoom
x = clamp(self.camera.getX() + (mouse.getX() - phoneDisplayRegionCenterX) / s, -self.maxX, self.maxX)
y = clamp(self.camera.getY() + (phoneDisplayRegionCenterY - mouse.getY()) / s, -self.maxY, self.maxY)
previousHeading = self.camera.getH() % 360.0
heading = (rad2Deg(atan2(y - self.camera.getY(), x - camera.getX())) - 90.0) % 360.0
if (180.0 < abs(heading - previousHeading)):
if (previousHeading < heading):
heading -= 360.0
else:
heading += 360.0
self.camera.setH(previousHeading)
self.phoneState.orientationTriangle.setH(previousHeading)
Parallel(
self.camera.posInterval(0.5, Vec3(x, y, self.camera.getZ())),
#.........这里部分代码省略.........
示例15: MainApp
# 需要导入模块: from direct.filter.CommonFilters import CommonFilters [as 别名]
# 或者: from direct.filter.CommonFilters.CommonFilters import setBloom [as 别名]
#.........这里部分代码省略.........
def moveForward(self):
currentPosition = self.pandaActor.getPos()
newPosition = Point3(0,2,0) + currentPosition
pandaMoveForwardInterval = self.pandaActor.posInterval(0.1,
Point3(newPosition),
startPos=Point3(currentPosition))
self.pandaPace = Sequence(pandaMoveForwardInterval)
self.pandaPace.start()
return currentPosition
def moveBack(self):
currentPosition = self.pandaActor.getPos()
newPosition = Point3(0,-2,0) + currentPosition
pandaMoveForwardInterval = self.pandaActor.posInterval(0.1,
Point3(newPosition),
startPos=Point3(currentPosition))
self.pandaPace = Sequence(pandaMoveForwardInterval)
self.pandaPace.start()
return currentPosition
def moveLeft(self):
currentPosition = self.pandaActor.getPos()
newPosition = Point3(-2,0,0) + currentPosition
pandaMoveForwardInterval = self.pandaActor.posInterval(0.1,
Point3(newPosition),
startPos=Point3(currentPosition))
self.pandaPace = Sequence(pandaMoveForwardInterval)
self.pandaPace.start()
return currentPosition
def moveRight(self):
currentPosition = self.pandaActor.getPos()
newPosition = Point3(2,0,0) + currentPosition
pandaMoveForwardInterval = self.pandaActor.posInterval(0.1,
Point3(newPosition),
startPos=Point3(currentPosition))
self.pandaPace = Sequence(pandaMoveForwardInterval)
self.pandaPace.start()
return currentPosition
def pauseSequence(self):
self.pandaPace.pause()
def doLogic(self, task):
dt = globalClock.getDt()
# this method is a placeholder to test if differnt stuff has occured
# like checking wether the robot is ready for a new command, etc.
if self.cameraForwardThrottleEnabled:
currentVelocity = self.cameraActorNode.getPhysicsObject().getVelocity()
newVelocity = currentVelocity + Vec3(dt*250,0,0)
self.cameraActorNode.getPhysicsObject().setVelocity(newVelocity)
# slow down camera ("friction")
self.cameraActorNode.getPhysicsObject().setVelocity(self.cameraActorNode.getPhysicsObject().getVelocity() * 0.92)
return Task.cont
def toggleGlow(self):
self.glowSize = self.glowSize + 1
if (self.glowSize == 4): self.glowSize = 0
self.filters.setBloom(blend=(0,0,0,1), desat=-0.5, intensity=3.0, size=self.glowSize)
print "Glow size set to", self.glowSize
def printCameraPosition(self):
print self.camera.getPos()
print self.camera.getHpr()
def toggleDebugMode(self):
if(self.debugMode):
self.setDebugMode(False)
else:
self.setDebugMode(True)
def setDebugMode(self, enabled):
self.debugMode = enabled
if(enabled):
self.enableMouse()
self.accept('c', self.printCameraPosition)
else:
self.disableMouse()
self.ignore('c')
def loadShaders(self):
# Check video card capabilities for shaders.
if (base.win.getGsg().getSupportsBasicShaders() == 0):
addTitle("Glow Filter: Video driver reports that shaders are not supported.")
return False
# Load filters
self.filters = CommonFilters(base.win, base.cam)
filterok = self.filters.setBloom(blend=(0,0,0,1), desat=-0.5, intensity=3.0, size="small")
if (filterok == False):
addTitle("Toon Shader: Video card not powerful enough to do image postprocessing")
return False
self.glowSize=1
# Shadow shaders
# TODO: Implement shadows
return True